Merge remote-tracking branch 'origin/new/bug_7781'
[koha.git] / opac / opac-detail.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21
22 use strict;
23 use warnings;
24
25 use CGI;
26 use C4::Auth qw(:DEFAULT get_session);
27 use C4::Branch;
28 use C4::Koha;
29 use C4::Serials;    #uses getsubscriptionfrom biblionumber
30 use C4::Output;
31 use C4::Biblio;
32 use C4::Items;
33 use C4::Circulation;
34 use C4::Tags qw(get_tags);
35 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
36 use C4::External::Amazon;
37 use C4::External::Syndetics qw(get_syndetics_index get_syndetics_summary get_syndetics_toc get_syndetics_excerpt get_syndetics_reviews get_syndetics_anotes );
38 use C4::Review;
39 use C4::Members;
40 use C4::VirtualShelves;
41 use C4::XSLT;
42 use C4::ShelfBrowser;
43 use C4::Reserves;
44 use C4::Charset;
45 use MARC::Record;
46 use MARC::Field;
47 use List::MoreUtils qw/any none/;
48 use C4::Images;
49 use Koha::DateUtils;
50
51 BEGIN {
52         if (C4::Context->preference('BakerTaylorEnabled')) {
53                 require C4::External::BakerTaylor;
54                 import C4::External::BakerTaylor qw(&image_url &link_url);
55         }
56 }
57
58 my $query = new CGI;
59 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
60     {
61         template_name   => "opac-detail.tmpl",
62         query           => $query,
63         type            => "opac",
64         authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
65         flagsrequired   => { borrow => 1 },
66     }
67 );
68
69 my $biblionumber = $query->param('biblionumber') || $query->param('bib');
70
71 my $record       = GetMarcBiblio($biblionumber);
72 if ( ! $record ) {
73     print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
74     exit;
75 }
76 $template->param( biblionumber => $biblionumber );
77
78 # get biblionumbers stored in the cart
79 my @cart_list;
80
81 if($query->cookie("bib_list")){
82     my $cart_list = $query->cookie("bib_list");
83     @cart_list = split(/\//, $cart_list);
84     if ( grep {$_ eq $biblionumber} @cart_list) {
85         $template->param( incart => 1 );
86     }
87 }
88
89
90 SetUTF8Flag($record);
91
92 # XSLT processing of some stuff
93 if (C4::Context->preference("OPACXSLTDetailsDisplay") ) {
94     $template->param( 'XSLTBloc' => XSLTParse4Display($biblionumber, $record, "OPACXSLTDetailsDisplay" ) );
95 }
96
97
98 # We look for the busc param to build the simple paging from the search
99 my $session = get_session($query->cookie("CGISESSID"));
100 my %paging = (previous => {}, next => {});
101 if ($session->param('busc')) {
102     use C4::Search;
103
104     # Rebuild the string to store on session
105     sub rebuildBuscParam
106     {
107         my $arrParamsBusc = shift;
108
109         my $pasarParams = '';
110         my $j = 0;
111         for (keys %$arrParamsBusc) {
112             if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
113                 if (defined($arrParamsBusc->{$_})) {
114                     $pasarParams .= '&' if ($j);
115                     $pasarParams .= $_ . '=' . $arrParamsBusc->{$_};
116                     $j++;
117                 }
118             } else {
119                 for my $value (@{$arrParamsBusc->{$_}}) {
120                     $pasarParams .= '&' if ($j);
121                     $pasarParams .= $_ . '=' . $value;
122                     $j++;
123                 }
124             }
125         }
126         return $pasarParams;
127     }#rebuildBuscParam
128
129     # Search given the current values from the busc param
130     sub searchAgain
131     {
132         my ($arrParamsBusc, $offset, $results_per_page) = @_;
133
134         my $expanded_facet = $arrParamsBusc->{'expand'};
135         my $branches = GetBranches();
136         my @servers;
137         @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
138         @servers = ("biblioserver") unless (@servers);
139         my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
140         my @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
141         $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
142         my ($error, $results_hashref, $facets);
143         eval {
144             ($error, $results_hashref, $facets) = getRecords($arrParamsBusc->{'query'},$arrParamsBusc->{'simple_query'},\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'});
145         };
146         my $hits;
147         my @newresults;
148         for (my $i=0;$i<@servers;$i++) {
149             my $server = $servers[$i];
150             $hits = $results_hashref->{$server}->{"hits"};
151             my @records = $results_hashref->{$server}->{"RECORDS"};
152             @newresults = searchResults('opac', '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, \@records,, C4::Context->preference('hidelostitems'));
153         }
154         return \@newresults;
155     }#searchAgain
156
157     # Build the current list of biblionumbers in this search
158     sub buildListBiblios
159     {
160         my ($newresultsRef, $results_per_page) = @_;
161
162         my $listBiblios = '';
163         my $j = 0;
164         foreach (@$newresultsRef) {
165             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
166             $listBiblios .= $bibnum . ',';
167             $j++;
168             last if ($j == $results_per_page);
169         }
170         chop $listBiblios if ($listBiblios =~ /,$/);
171         return $listBiblios;
172     }#buildListBiblios
173
174     my $busc = $session->param("busc");
175     my @arrBusc = split(/\&(?:amp;)?/, $busc);
176     my ($key, $value);
177     my %arrParamsBusc = ();
178     for (@arrBusc) {
179         ($key, $value) = split(/=/, $_, 2);
180         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
181             $arrParamsBusc{$key} = $value;
182         } else {
183             unless (exists($arrParamsBusc{$key})) {
184                 $arrParamsBusc{$key} = [];
185             }
186             push @{$arrParamsBusc{$key}}, $value;
187         }
188     }
189     my $searchAgain = 0;
190     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
191     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
192     $arrParamsBusc{'count'} = $results_per_page;
193     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
194     # The value OPACnumSearchResults has changed and the search has to be rebuild
195     if ($count != $results_per_page) {
196         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
197             my $indexBiblio = 0;
198             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
199             for (@arrBibliosAux) {
200                 last if ($_ == $biblionumber);
201                 $indexBiblio++;
202             }
203             $indexBiblio += $offset;
204             $offset = int($indexBiblio / $count) * $count;
205             $arrParamsBusc{'offset'} = $offset;
206         }
207         $arrParamsBusc{'count'} = $count;
208         $results_per_page = $count;
209         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
210         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
211         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
212         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
213         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
214         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
215         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
216         $session->param("busc" => $newbusc);
217         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
218     } else {
219         my $modifyListBiblios = 0;
220         # We come from a previous click
221         if (exists($arrParamsBusc{'previous'})) {
222             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
223             delete $arrParamsBusc{'previous'};
224         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
225             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
226             delete $arrParamsBusc{'next'};
227         }
228         if ($modifyListBiblios) {
229             if (exists($arrParamsBusc{'newlistBiblios'})) {
230                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
231                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
232                 my @arrAux = split(',', $listBibliosAux);
233                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
234                 if ($modifyListBiblios == 1) {
235                     $arrParamsBusc{'next'} = $arrAux[0];
236                     $paging{'next'}->{biblionumber} = $arrAux[0];
237                 }else {
238                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
239                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
240                 }
241             } else {
242                 delete $arrParamsBusc{'listBiblios'};
243             }
244             my $offsetAux = $arrParamsBusc{'offset'};
245             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
246             $arrParamsBusc{'offsetSearch'} = $offsetAux;
247             $offset = $arrParamsBusc{'offset'};
248             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
249             $session->param("busc" => $newbusc);
250             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
251         }
252     }
253     my $buscParam = '';
254     my $j = 0;
255     # Rebuild the query for the button "back to results"
256     for (@arrBusc) {
257         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
258             $buscParam .= '&amp;' unless ($j == 0);
259             $buscParam .= $_;
260             $j++;
261         }
262     }
263     $template->param('busc' => $buscParam);
264     my $offsetSearch;
265     my @arrBiblios;
266     # We are inside the list of biblios and we don't have to search
267     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
268         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
269         if (@arrBiblios) {
270             # We are at the first item of the list
271             if ($arrBiblios[0] == $biblionumber) {
272                 if (@arrBiblios > 1) {
273                     for (my $j = 1; $j < @arrBiblios; $j++) {
274                         next unless ($arrBiblios[$j]);
275                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
276                         last;
277                     }
278                 }
279                 # search again if we are not at the first searching list
280                 if ($offset && !$arrParamsBusc{'previous'}) {
281                     $searchAgain = 1;
282                     $offsetSearch = $offset - $results_per_page;
283                 }
284             # we are at the last item of the list
285             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
286                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
287                     next unless ($arrBiblios[$j]);
288                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
289                     last;
290                 }
291                 if (!$offset) {
292                     # search again if we are at the first list and there is more results
293                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
294                 } else {
295                     # search again if we aren't at the first list and there is more results
296                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
297                 }
298                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
299             } else {
300                 for (my $j = 1; $j < $#arrBiblios; $j++) {
301                     if ($arrBiblios[$j] == $biblionumber) {
302                         for (my $z = $j - 1; $z >= 0; $z--) {
303                             next unless ($arrBiblios[$z]);
304                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
305                             last;
306                         }
307                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
308                             next unless ($arrBiblios[$z]);
309                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
310                             last;
311                         }
312                         last;
313                     }
314                 }
315             }
316         }
317         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
318     }
319     if ($searchAgain) {
320         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
321         my @newresults = @$newresultsRef;
322         # build the new listBiblios
323         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
324         unless (exists($arrParamsBusc{'listBiblios'})) {
325             $arrParamsBusc{'listBiblios'} = $listBiblios;
326             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
327         } else {
328             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
329         }
330         # From the new list we build again the next and previous result
331         if (@arrBiblios) {
332             if ($arrBiblios[0] == $biblionumber) {
333                 for (my $j = $#newresults; $j >= 0; $j--) {
334                     next unless ($newresults[$j]);
335                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
336                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
337                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
338                    last;
339                 }
340             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
341                 for (my $j = 0; $j < @newresults; $j++) {
342                     next unless ($newresults[$j]);
343                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
344                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
345                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
346                     last;
347                 }
348             }
349         }
350         # build new busc param
351         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
352         $session->param("busc" => $newbusc);
353     }
354     my ($previous, $next, $dataBiblioPaging);
355     # Previous biblio
356     if ($paging{'previous'}->{biblionumber}) {
357         $previous = 'opac-detail.pl?biblionumber=' . $paging{'previous'}->{biblionumber};
358         $dataBiblioPaging = GetBiblioData($paging{'previous'}->{biblionumber});
359         $template->param('previousTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
360     }
361     # Next biblio
362     if ($paging{'next'}->{biblionumber}) {
363         $next = 'opac-detail.pl?biblionumber=' . $paging{'next'}->{biblionumber};
364         $dataBiblioPaging = GetBiblioData($paging{'next'}->{biblionumber});
365         $template->param('nextTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
366     }
367     $template->param('previous' => $previous, 'next' => $next);
368     # Partial list of biblio results
369     my @listResults;
370     for (my $j = 0; $j < @arrBiblios; $j++) {
371         next unless ($arrBiblios[$j]);
372         $dataBiblioPaging = GetBiblioData($arrBiblios[$j]) if ($arrBiblios[$j] != $biblionumber);
373         push @listResults, {index => $j + 1 + $offset, biblionumber => $arrBiblios[$j], title => ($arrBiblios[$j] == $biblionumber)?'':$dataBiblioPaging->{title}, author => ($arrBiblios[$j] != $biblionumber && $dataBiblioPaging->{author})?$dataBiblioPaging->{author}:'', url => ($arrBiblios[$j] == $biblionumber)?'':'opac-detail.pl?biblionumber=' . $arrBiblios[$j]};
374     }
375     $template->param('listResults' => \@listResults) if (@listResults);
376     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
377 }
378
379
380
381 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
382 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
383
384
385
386 $template->param('OPACShowCheckoutName' => C4::Context->preference("OPACShowCheckoutName") ); 
387 # change back when ive fixed request.pl
388 my @all_items = GetItemsInfo( $biblionumber );
389
390 # adding items linked via host biblios
391 my $marcflavour  = C4::Context->preference("marcflavour");
392
393 my $analyticfield = '773';
394 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
395     $analyticfield = '773';
396 } elsif ($marcflavour eq 'UNIMARC') {
397     $analyticfield = '461';
398 }
399 foreach my $hostfield ( $record->field($analyticfield)) {
400     my $hostbiblionumber = $hostfield->subfield("0");
401     my $linkeditemnumber = $hostfield->subfield("9");
402     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
403     foreach my $hostitemInfo (@hostitemInfos){
404         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
405             push(@all_items, $hostitemInfo);
406         }
407     }
408 }
409
410 my @items;
411
412 # Getting items to be hidden
413 my @hiddenitems = GetHiddenItemnumbers(@all_items);
414
415 # Are there items to hide?
416 my $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
417
418 # Hide items
419 if ($hideitems) {
420     for my $itm (@all_items) {
421         if  ( C4::Context->preference('hidelostitems') ) {
422             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
423         } else {
424             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
425     }
426 }
427 } else {
428     # Or not
429     @items = @all_items;
430 }
431
432 my $dat = &GetBiblioData($biblionumber);
433
434 my $itemtypes = GetItemTypes();
435 # imageurl:
436 my $itemtype = $dat->{'itemtype'};
437 if ( $itemtype ) {
438     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
439     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
440 }
441 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'}, 'opac');
442 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'}, 'opac');
443
444 #coping with subscriptions
445 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
446 my @subscriptions       = GetSubscriptions( undef, undef, $biblionumber );
447
448 my @subs;
449 $dat->{'serial'}=1 if $subscriptionsnumber;
450 foreach my $subscription (@subscriptions) {
451     my $serials_to_display;
452     my %cell;
453     $cell{subscriptionid}    = $subscription->{subscriptionid};
454     $cell{subscriptionnotes} = $subscription->{notes};
455     $cell{missinglist}       = $subscription->{missinglist};
456     $cell{opacnote}          = $subscription->{opacnote};
457     $cell{histstartdate}     = $subscription->{histstartdate};
458     $cell{histenddate}       = $subscription->{histenddate};
459     $cell{branchcode}        = $subscription->{branchcode};
460     $cell{branchname}        = GetBranchName($subscription->{branchcode});
461     $cell{hasalert}          = $subscription->{hasalert};
462     #get the three latest serials.
463     $serials_to_display = $subscription->{opacdisplaycount};
464     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
465         $cell{opacdisplaycount} = $serials_to_display;
466     $cell{latestserials} =
467       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
468     push @subs, \%cell;
469 }
470
471 $dat->{'count'} = scalar(@items);
472
473 # If there is a lot of items, and the user has not decided
474 # to view them all yet, we first warn him
475 # TODO: The limit of 50 could be a syspref
476 my $viewallitems = $query->param('viewallitems');
477 if ($dat->{'count'} >= 50 && !$viewallitems) {
478     $template->param('lotsofitems' => 1);
479 }
480
481 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
482
483 my $norequests = 1;
484 my $branches = GetBranches();
485 my %itemfields;
486 for my $itm (@items) {
487     $norequests = 0
488        if ( (not $itm->{'wthdrawn'} )
489          && (not $itm->{'itemlost'} )
490          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
491                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
492          && ($itm->{'itemnumber'} ) );
493
494     if ( defined $itm->{'publictype'} ) {
495         # I can't actually find any case in which this is defined. --amoore 2008-12-09
496         $itm->{ $itm->{'publictype'} } = 1;
497     }
498
499     # get collection code description, too
500     if ( my $ccode = $itm->{'ccode'} ) {
501         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
502     }
503     if ( defined $itm->{'location'} ) {
504         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
505     }
506     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
507         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
508         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
509     }
510     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
511         $itemfields{$_} = 1 if ($itm->{$_});
512     }
513
514      # walk through the item-level authorised values and populate some images
515      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
516      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
517
518      if ( $itm->{'itemlost'} ) {
519          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
520          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
521          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
522      }
523      my ($reserve_status) = C4::Reserves::CheckReserves($itm->{itemnumber});
524       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
525       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
526     
527      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
528      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
529         $itm->{transfertwhen} = $transfertwhen;
530         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
531         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
532      }
533 }
534
535 ## get notes and subjects from MARC record
536 my $dbh              = C4::Context->dbh;
537 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
538 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
539 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
540 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
541 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
542 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
543 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
544 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
545
546     $template->param(
547                      MARCNOTES               => $marcnotesarray,
548                      MARCSUBJCTS             => $marcsubjctsarray,
549                      MARCAUTHORS             => $marcauthorsarray,
550                      MARCSERIES              => $marcseriesarray,
551                      MARCURLS                => $marcurlsarray,
552                      MARCHOSTS               => $marchostsarray,
553                      norequests              => $norequests,
554                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
555                      itemdata_ccode          => $itemfields{ccode},
556                      itemdata_enumchron      => $itemfields{enumchron},
557                      itemdata_uri            => $itemfields{uri},
558                      itemdata_copynumber     => $itemfields{copynumber},
559                      itemdata_itemnotes          => $itemfields{itemnotes},
560                      authorised_value_images => $biblio_authorised_value_images,
561                      subtitle                => $subtitle,
562     );
563
564 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
565     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
566     my $subfields = substr $fieldspec, 3;
567     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
568     my @alternateholdingsinfo = ();
569     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
570
571     for my $field (@holdingsfields) {
572         my %holding = ( holding => '' );
573         my $havesubfield = 0;
574         for my $subfield ($field->subfields()) {
575             if ((index $subfields, $$subfield[0]) >= 0) {
576                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
577                 $holding{'holding'} .= $$subfield[1];
578                 $havesubfield++;
579             }
580         }
581         if ($havesubfield) {
582             push(@alternateholdingsinfo, \%holding);
583         }
584     }
585
586     $template->param(
587         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
588         );
589 }
590
591 foreach ( keys %{$dat} ) {
592     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
593 }
594
595 # some useful variables for enhanced content;
596 # in each case, we're grabbing the first value we find in
597 # the record and normalizing it
598 my $upc = GetNormalizedUPC($record,$marcflavour);
599 my $ean = GetNormalizedEAN($record,$marcflavour);
600 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
601 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
602 my $content_identifier_exists;
603 if ( $isbn or $ean or $oclc or $upc ) {
604     $content_identifier_exists = 1;
605 }
606 $template->param(
607         normalized_upc => $upc,
608         normalized_ean => $ean,
609         normalized_oclc => $oclc,
610         normalized_isbn => $isbn,
611         content_identifier_exists =>  $content_identifier_exists,
612 );
613
614 # COinS format FIXME: for books Only
615 $template->param(
616     ocoins => GetCOinSBiblio($record),
617 );
618
619 my $libravatar_enabled = 0;
620 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) {
621     eval {
622         require Libravatar::URL;
623         Libravatar::URL->import();
624     };
625     if (!$@ ) {
626         $libravatar_enabled = 1;
627     }
628 }
629
630 my $reviews = getreviews( $biblionumber, 1 );
631 my $loggedincommenter;
632 foreach ( @$reviews ) {
633     my $borrowerData   = GetMember('borrowernumber' => $_->{borrowernumber});
634     # setting some borrower info into this hash
635     $_->{title}     = $borrowerData->{'title'};
636     $_->{surname}   = $borrowerData->{'surname'};
637     $_->{firstname} = $borrowerData->{'firstname'};
638     if ($libravatar_enabled and $borrowerData->{'email'}) {
639         $_->{avatarurl} = libravatar_url(email => $borrowerData->{'email'}, https => $ENV{HTTPS});
640     }
641     $_->{userid}    = $borrowerData->{'userid'};
642     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
643     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
644                 $_->{your_comment} = 1;
645                 $loggedincommenter = 1;
646         }
647 }
648
649
650 if(C4::Context->preference("ISBD")) {
651         $template->param(ISBD => 1);
652 }
653
654 $template->param(
655     ITEM_RESULTS        => \@items,
656     subscriptionsnumber => $subscriptionsnumber,
657     biblionumber        => $biblionumber,
658     subscriptions       => \@subs,
659     subscriptionsnumber => $subscriptionsnumber,
660     reviews             => $reviews,
661     loggedincommenter   => $loggedincommenter
662 );
663
664 # Lists
665
666 if (C4::Context->preference("virtualshelves") ) {
667    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
668 }
669
670
671 # XISBN Stuff
672 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
673     eval {
674         $template->param(
675             XISBNS => get_xisbns($isbn)
676         );
677     };
678     if ($@) { warn "XISBN Failed $@"; }
679 }
680
681 # Serial Collection
682 my @sc_fields = $record->field(955);
683 my @serialcollections = ();
684
685 foreach my $sc_field (@sc_fields) {
686     my %row_data;
687
688     $row_data{text}    = $sc_field->subfield('r');
689     $row_data{branch}  = $sc_field->subfield('9');
690
691     if ($row_data{text} && $row_data{branch}) { 
692         push (@serialcollections, \%row_data);
693     }
694 }
695
696 if (scalar(@serialcollections) > 0) {
697     $template->param(
698         serialcollection  => 1,
699         serialcollections => \@serialcollections);
700 }
701
702 # Local cover Images stuff
703 if (C4::Context->preference("OPACLocalCoverImages")){
704                 $template->param(OPACLocalCoverImages => 1);
705 }
706
707 # Amazon.com Stuff
708 if ( C4::Context->preference("OPACAmazonEnabled") ) {
709     $template->param( AmazonTld => get_amazon_tld() );
710     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
711     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
712     my @services;
713     if ( $amazon_reviews ) {
714         push( @services, 'EditorialReview', 'Reviews' );
715     }
716     if ( $amazon_similars ) {
717         push( @services, 'Similarities' );
718     }
719     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
720     my $similar_products_exist;
721     if ( $amazon_reviews ) {
722         my $item = $amazon_details->{Items}->{Item}->[0];
723         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
724         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
725         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
726         $template->param( amazon_average_rating    => $average_rating * 20);
727         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
728         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
729     }
730     if ( $amazon_similars ) {
731         my $item = $amazon_details->{Items}->{Item}->[0];
732         my @similar_products;
733         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
734             # do we have any of these isbns in our collection?
735             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
736             # verify that there is at least one similar item
737             if (scalar(@$similar_biblionumbers)){
738                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
739                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
740             }
741         }
742         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
743         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
744     }
745 }
746
747 my $syndetics_elements;
748
749 if ( C4::Context->preference("SyndeticsEnabled") ) {
750     $template->param("SyndeticsEnabled" => 1);
751     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
752         eval {
753             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
754             for my $element (values %$syndetics_elements) {
755                 $template->param("Syndetics$element"."Exists" => 1 );
756                 #warn "Exists: "."Syndetics$element"."Exists";
757         }
758     };
759     warn $@ if $@;
760 }
761
762 if ( C4::Context->preference("SyndeticsEnabled")
763         && C4::Context->preference("SyndeticsSummary")
764         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
765         eval {
766             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
767             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
768         };
769         warn $@ if $@;
770
771 }
772
773 if ( C4::Context->preference("SyndeticsEnabled")
774         && C4::Context->preference("SyndeticsTOC")
775         && exists($syndetics_elements->{'TOC'}) ) {
776         eval {
777     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
778     $template->param( SYNDETICS_TOC => $syndetics_toc );
779         };
780         warn $@ if $@;
781 }
782
783 if ( C4::Context->preference("SyndeticsEnabled")
784     && C4::Context->preference("SyndeticsExcerpt")
785     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
786     eval {
787     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
788     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
789     };
790         warn $@ if $@;
791 }
792
793 if ( C4::Context->preference("SyndeticsEnabled")
794     && C4::Context->preference("SyndeticsReviews")) {
795     eval {
796     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
797     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
798     };
799         warn $@ if $@;
800 }
801
802 if ( C4::Context->preference("SyndeticsEnabled")
803     && C4::Context->preference("SyndeticsAuthorNotes")
804         && exists($syndetics_elements->{'ANOTES'}) ) {
805     eval {
806     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
807     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
808     };
809     warn $@ if $@;
810 }
811
812 # LibraryThingForLibraries ID Code and Tabbed View Option
813 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
814
815 $template->param(LibraryThingForLibrariesID =>
816 C4::Context->preference('LibraryThingForLibrariesID') ); 
817 $template->param(LibraryThingForLibrariesTabbedView =>
818 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
819
820
821 # Novelist Select
822 if( C4::Context->preference('NovelistSelectEnabled') ) 
823
824 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
825 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
826 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
827
828
829
830 # Babelthèque
831 if ( C4::Context->preference("Babeltheque") ) {
832     $template->param( 
833         Babeltheque => 1,
834         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
835     );
836 }
837
838 # Social Networks
839 if ( C4::Context->preference( "SocialNetworks" ) ) {
840     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
841     $template->param( SocialNetworks => 1 );
842 }
843
844 # Shelf Browser Stuff
845 if (C4::Context->preference("OPACShelfBrowser")) {
846     # pick the first itemnumber unless one was selected by the user
847     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
848     if (defined($starting_itemnumber)) {
849         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
850         my $nearby = GetNearbyItems($starting_itemnumber,3);
851
852         $template->param(
853             starting_homebranch => $nearby->{starting_homebranch}->{description},
854             starting_location => $nearby->{starting_location}->{description},
855             starting_ccode => $nearby->{starting_ccode}->{description},
856             starting_itemnumber => $nearby->{starting_itemnumber},
857             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
858             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
859             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
860             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
861             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
862             NEXT_SHELF_BROWSE => $nearby->{next},
863         );
864     }
865 }
866
867 if (C4::Context->preference("BakerTaylorEnabled")) {
868         $template->param(
869                 BakerTaylorEnabled  => 1,
870                 BakerTaylorImageURL => &image_url(),
871                 BakerTaylorLinkURL  => &link_url(),
872                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
873         );
874         my ($bt_user, $bt_pass);
875         if ($isbn and
876                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
877                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
878         {
879                 $template->param(
880                 BakerTaylorContentURL   =>
881                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
882                                 $bt_user,$bt_pass,$isbn)
883                 );
884         }
885 }
886
887 my $tag_quantity;
888 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
889         $template->param(
890                 TagsEnabled => 1,
891                 TagsShowOnDetail => $tag_quantity,
892                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
893         );
894         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
895                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
896 }
897
898 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
899     # These values are going to be read by Javascript, at least in the case
900     # of the google covers
901     $template->param(covernewwindow => 'true');
902 } else {
903     $template->param(covernewwindow => 'false');
904 }
905
906 #Export options
907 my $OpacExportOptions=C4::Context->preference("OpacExportOptions");
908 my @export_options = split(/\|/,$OpacExportOptions);
909 $template->{VARS}->{'export_options'} = \@export_options;
910
911 #Search for title in links
912 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
913 my $marcissns = GetMarcISSN ( $record, $marcflavour );
914 my $issn = $marcissns->[0] || '';
915
916 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
917     $dat->{author} ? $search_for_title =~ s/{AUTHOR}/$dat->{author}/g : $search_for_title =~ s/{AUTHOR}//g;
918     $dat->{title} =~ s/\/+$//; # remove trailing slash
919     $dat->{title} =~ s/\s+$//; # remove trailing space
920     $dat->{title} ? $search_for_title =~ s/{TITLE}/$dat->{title}/g : $search_for_title =~ s/{TITLE}//g;
921     $isbn ? $search_for_title =~ s/{ISBN}/$isbn/g : $search_for_title =~ s/{ISBN}//g;
922     $issn ? $search_for_title =~ s/{ISSN}/$issn/g : $search_for_title =~ s/{ISSN}//g;
923     $marccontrolnumber ? $search_for_title =~ s/{CONTROLNUMBER}/$marccontrolnumber/g : $search_for_title =~ s/{CONTROLNUMBER}//g;
924     $search_for_title =~ s/{BIBLIONUMBER}/$biblionumber/g;
925     $template->param('OPACSearchForTitleIn' => $search_for_title);
926 }
927
928 # We try to select the best default tab to show, according to what
929 # the user wants, and what's available for display
930 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
931 my $defaulttab = 
932     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
933         ? 'subscriptions' :
934     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
935         ? 'serialcollection' :
936     $opac_serial_default eq 'holdings' && $dat->{'count'} > 0
937         ? 'holdings' :
938     $subscriptionsnumber
939         ? 'subscriptions' :
940     @serialcollections > 0 
941         ? 'serialcollection' : 'subscription';
942 $template->param('defaulttab' => $defaulttab);
943
944 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
945     my @images = ListImagesForBiblio($biblionumber);
946     $template->{VARS}->{localimages} = \@images;
947 }
948
949 output_html_with_http_headers $query, $cookie, $template->output;