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