Bug 7394 : Fixing scoping issue with XSLT processing. Also bailing out early for...
[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::Charset;
45 use MARC::Record;
46 use MARC::Field;
47 use List::MoreUtils qw/any none/;
48
49 BEGIN {
50         if (C4::Context->preference('BakerTaylorEnabled')) {
51                 require C4::External::BakerTaylor;
52                 import C4::External::BakerTaylor qw(&image_url &link_url);
53         }
54 }
55
56 my $query = new CGI;
57 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
58     {
59         template_name   => "opac-detail.tmpl",
60         query           => $query,
61         type            => "opac",
62         authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
63         flagsrequired   => { borrow => 1 },
64     }
65 );
66
67 my $biblionumber = $query->param('biblionumber') || $query->param('bib');
68
69 my $record       = GetMarcBiblio($biblionumber);
70 if ( ! $record ) {
71     print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
72     exit;
73 }
74 $template->param( biblionumber => $biblionumber );
75
76
77 SetUTF8Flag($record);
78
79 # XSLT processing of some stuff
80 if (C4::Context->preference("OPACXSLTDetailsDisplay") ) {
81     $template->param( 'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail', 'opac') );
82 }
83
84
85 # We look for the busc param to build the simple paging from the search
86 my $session = get_session($query->cookie("CGISESSID"));
87 my %paging = (previous => {}, next => {});
88 if ($session->param('busc')) {
89     use C4::Search;
90
91     # Rebuild the string to store on session
92     sub rebuildBuscParam
93     {
94         my $arrParamsBusc = shift;
95
96         my $pasarParams = '';
97         my $j = 0;
98         for (keys %$arrParamsBusc) {
99             if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
100                 if (defined($arrParamsBusc->{$_})) {
101                     $pasarParams .= '&' if ($j);
102                     $pasarParams .= $_ . '=' . $arrParamsBusc->{$_};
103                     $j++;
104                 }
105             } else {
106                 for my $value (@{$arrParamsBusc->{$_}}) {
107                     $pasarParams .= '&' if ($j);
108                     $pasarParams .= $_ . '=' . $value;
109                     $j++;
110                 }
111             }
112         }
113         return $pasarParams;
114     }#rebuildBuscParam
115
116     # Search given the current values from the busc param
117     sub searchAgain
118     {
119         my ($arrParamsBusc, $offset, $results_per_page) = @_;
120
121         my $expanded_facet = $arrParamsBusc->{'expand'};
122         my $branches = GetBranches();
123         my @servers;
124         @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
125         @servers = ("biblioserver") unless (@servers);
126         my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
127         my @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
128         $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
129         my ($error, $results_hashref, $facets);
130         eval {
131             ($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'});
132         };
133         my $hits;
134         my @newresults;
135         for (my $i=0;$i<@servers;$i++) {
136             my $server = $servers[$i];
137             $hits = $results_hashref->{$server}->{"hits"};
138             @newresults = searchResults('opac', '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, @{$results_hashref->{$server}->{"RECORDS"}},, C4::Context->preference('hidelostitems'));
139         }
140         return \@newresults;
141     }#searchAgain
142
143     # Build the current list of biblionumbers in this search
144     sub buildListBiblios
145     {
146         my ($newresultsRef, $results_per_page) = @_;
147
148         my $listBiblios = '';
149         my $j = 0;
150         foreach (@$newresultsRef) {
151             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
152             $listBiblios .= $bibnum . ',';
153             $j++;
154             last if ($j == $results_per_page);
155         }
156         chop $listBiblios if ($listBiblios =~ /,$/);
157         return $listBiblios;
158     }#buildListBiblios
159
160     my $busc = $session->param("busc");
161     my @arrBusc = split(/\&(?:amp;)?/, $busc);
162     my ($key, $value);
163     my %arrParamsBusc = ();
164     for (@arrBusc) {
165         ($key, $value) = split(/=/, $_, 2);
166         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
167             $arrParamsBusc{$key} = $value;
168         } else {
169             unless (exists($arrParamsBusc{$key})) {
170                 $arrParamsBusc{$key} = [];
171             }
172             push @{$arrParamsBusc{$key}}, $value;
173         }
174     }
175     my $searchAgain = 0;
176     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
177     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
178     $arrParamsBusc{'count'} = $results_per_page;
179     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
180     # The value OPACnumSearchResults has changed and the search has to be rebuild
181     if ($count != $results_per_page) {
182         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
183             my $indexBiblio = 0;
184             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
185             for (@arrBibliosAux) {
186                 last if ($_ == $biblionumber);
187                 $indexBiblio++;
188             }
189             $indexBiblio += $offset;
190             $offset = int($indexBiblio / $count) * $count;
191             $arrParamsBusc{'offset'} = $offset;
192         }
193         $arrParamsBusc{'count'} = $count;
194         $results_per_page = $count;
195         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
196         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
197         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
198         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
199         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
200         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
201         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
202         $session->param("busc" => $newbusc);
203         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
204     } else {
205         my $modifyListBiblios = 0;
206         # We come from a previous click
207         if (exists($arrParamsBusc{'previous'})) {
208             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
209             delete $arrParamsBusc{'previous'};
210         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
211             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
212             delete $arrParamsBusc{'next'};
213         }
214         if ($modifyListBiblios) {
215             if (exists($arrParamsBusc{'newlistBiblios'})) {
216                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
217                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
218                 my @arrAux = split(',', $listBibliosAux);
219                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
220                 if ($modifyListBiblios == 1) {
221                     $arrParamsBusc{'next'} = $arrAux[0];
222                     $paging{'next'}->{biblionumber} = $arrAux[0];
223                 }else {
224                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
225                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
226                 }
227             } else {
228                 delete $arrParamsBusc{'listBiblios'};
229             }
230             my $offsetAux = $arrParamsBusc{'offset'};
231             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
232             $arrParamsBusc{'offsetSearch'} = $offsetAux;
233             $offset = $arrParamsBusc{'offset'};
234             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
235             $session->param("busc" => $newbusc);
236             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
237         }
238     }
239     my $buscParam = '';
240     my $j = 0;
241     # Rebuild the query for the button "back to results"
242     for (@arrBusc) {
243         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
244             $buscParam .= '&amp;' unless ($j == 0);
245             $buscParam .= $_;
246             $j++;
247         }
248     }
249     $template->param('busc' => $buscParam);
250     my $offsetSearch;
251     my @arrBiblios;
252     # We are inside the list of biblios and we don't have to search
253     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
254         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
255         if (@arrBiblios) {
256             # We are at the first item of the list
257             if ($arrBiblios[0] == $biblionumber) {
258                 if (@arrBiblios > 1) {
259                     for (my $j = 1; $j < @arrBiblios; $j++) {
260                         next unless ($arrBiblios[$j]);
261                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
262                         last;
263                     }
264                 }
265                 # search again if we are not at the first searching list
266                 if ($offset && !$arrParamsBusc{'previous'}) {
267                     $searchAgain = 1;
268                     $offsetSearch = $offset - $results_per_page;
269                 }
270             # we are at the last item of the list
271             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
272                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
273                     next unless ($arrBiblios[$j]);
274                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
275                     last;
276                 }
277                 if (!$offset) {
278                     # search again if we are at the first list and there is more results
279                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
280                 } else {
281                     # search again if we aren't at the first list and there is more results
282                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
283                 }
284                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
285             } else {
286                 for (my $j = 1; $j < $#arrBiblios; $j++) {
287                     if ($arrBiblios[$j] == $biblionumber) {
288                         for (my $z = $j - 1; $z >= 0; $z--) {
289                             next unless ($arrBiblios[$z]);
290                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
291                             last;
292                         }
293                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
294                             next unless ($arrBiblios[$z]);
295                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
296                             last;
297                         }
298                         last;
299                     }
300                 }
301             }
302         }
303         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
304     }
305     if ($searchAgain) {
306         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
307         my @newresults = @$newresultsRef;
308         # build the new listBiblios
309         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
310         unless (exists($arrParamsBusc{'listBiblios'})) {
311             $arrParamsBusc{'listBiblios'} = $listBiblios;
312             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
313         } else {
314             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
315         }
316         # From the new list we build again the next and previous result
317         if (@arrBiblios) {
318             if ($arrBiblios[0] == $biblionumber) {
319                 for (my $j = $#newresults; $j >= 0; $j--) {
320                     next unless ($newresults[$j]);
321                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
322                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
323                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
324                    last;
325                 }
326             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
327                 for (my $j = 0; $j < @newresults; $j++) {
328                     next unless ($newresults[$j]);
329                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
330                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
331                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
332                     last;
333                 }
334             }
335         }
336         # build new busc param
337         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
338         $session->param("busc" => $newbusc);
339     }
340     my ($previous, $next, $dataBiblioPaging);
341     # Previous biblio
342     if ($paging{'previous'}->{biblionumber}) {
343         $previous = 'opac-detail.pl?biblionumber=' . $paging{'previous'}->{biblionumber};
344         $dataBiblioPaging = GetBiblioData($paging{'previous'}->{biblionumber});
345         $template->param('previousTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
346     }
347     # Next biblio
348     if ($paging{'next'}->{biblionumber}) {
349         $next = 'opac-detail.pl?biblionumber=' . $paging{'next'}->{biblionumber};
350         $dataBiblioPaging = GetBiblioData($paging{'next'}->{biblionumber});
351         $template->param('nextTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
352     }
353     $template->param('previous' => $previous, 'next' => $next);
354     # Partial list of biblio results
355     my @listResults;
356     for (my $j = 0; $j < @arrBiblios; $j++) {
357         next unless ($arrBiblios[$j]);
358         $dataBiblioPaging = GetBiblioData($arrBiblios[$j]) if ($arrBiblios[$j] != $biblionumber);
359         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]};
360     }
361     $template->param('listResults' => \@listResults) if (@listResults);
362     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
363 }
364
365
366
367 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
368 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
369
370
371
372 $template->param('OPACShowCheckoutName' => C4::Context->preference("OPACShowCheckoutName") ); 
373 # change back when ive fixed request.pl
374 my @all_items = GetItemsInfo( $biblionumber );
375
376 # adding items linked via host biblios
377 my $marcflavour  = C4::Context->preference("marcflavour");
378
379 my $analyticfield = '773';
380 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
381     $analyticfield = '773';
382 } elsif ($marcflavour eq 'UNIMARC') {
383     $analyticfield = '461';
384 }
385 foreach my $hostfield ( $record->field($analyticfield)) {
386     my $hostbiblionumber = $hostfield->subfield("0");
387     my $linkeditemnumber = $hostfield->subfield("9");
388     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
389     foreach my $hostitemInfo (@hostitemInfos){
390         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
391             push(@all_items, $hostitemInfo);
392         }
393     }
394 }
395
396 my @items;
397
398 # Getting items to be hidden
399 my @hiddenitems = GetHiddenItemnumbers(@all_items);
400
401 # Are there items to hide?
402 my $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
403
404 # Hide items
405 if ($hideitems) {
406     for my $itm (@all_items) {
407         if  ( C4::Context->preference('hidelostitems') ) {
408             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
409         } else {
410             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
411     }
412 }
413 } else {
414     # Or not
415     @items = @all_items;
416 }
417
418 my $dat = &GetBiblioData($biblionumber);
419
420 my $itemtypes = GetItemTypes();
421 # imageurl:
422 my $itemtype = $dat->{'itemtype'};
423 if ( $itemtype ) {
424     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
425     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
426 }
427 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'}, 'opac');
428 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'}, 'opac');
429
430 #coping with subscriptions
431 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
432 my @subscriptions       = GetSubscriptions( undef, undef, $biblionumber );
433
434 my @subs;
435 $dat->{'serial'}=1 if $subscriptionsnumber;
436 foreach my $subscription (@subscriptions) {
437     my $serials_to_display;
438     my %cell;
439     $cell{subscriptionid}    = $subscription->{subscriptionid};
440     $cell{subscriptionnotes} = $subscription->{notes};
441     $cell{missinglist}       = $subscription->{missinglist};
442     $cell{opacnote}          = $subscription->{opacnote};
443     $cell{histstartdate}     = format_date($subscription->{histstartdate});
444     $cell{histenddate}       = format_date($subscription->{histenddate});
445     $cell{branchcode}        = $subscription->{branchcode};
446     $cell{branchname}        = GetBranchName($subscription->{branchcode});
447     $cell{hasalert}          = $subscription->{hasalert};
448     #get the three latest serials.
449     $serials_to_display = $subscription->{opacdisplaycount};
450     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
451         $cell{opacdisplaycount} = $serials_to_display;
452     $cell{latestserials} =
453       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
454     push @subs, \%cell;
455 }
456
457 $dat->{'count'} = scalar(@items);
458
459 # If there is a lot of items, and the user has not decided
460 # to view them all yet, we first warn him
461 # TODO: The limit of 50 could be a syspref
462 my $viewallitems = $query->param('viewallitems');
463 if ($dat->{'count'} >= 50 && !$viewallitems) {
464     $template->param('lotsofitems' => 1);
465 }
466
467 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
468
469 my $norequests = 1;
470 my $branches = GetBranches();
471 my %itemfields;
472 for my $itm (@items) {
473     $norequests = 0
474        if ( (not $itm->{'wthdrawn'} )
475          && (not $itm->{'itemlost'} )
476          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
477                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
478          && ($itm->{'itemnumber'} ) );
479
480     if ( defined $itm->{'publictype'} ) {
481         # I can't actually find any case in which this is defined. --amoore 2008-12-09
482         $itm->{ $itm->{'publictype'} } = 1;
483     }
484     $itm->{datedue}      = format_date($itm->{datedue});
485     $itm->{datelastseen} = format_date($itm->{datelastseen});
486
487     # get collection code description, too
488     if ( my $ccode = $itm->{'ccode'} ) {
489         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
490     }
491     if ( defined $itm->{'location'} ) {
492         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
493     }
494     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
495         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
496         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
497     }
498     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
499         $itemfields{$_} = 1 if ($itm->{$_});
500     }
501
502      # walk through the item-level authorised values and populate some images
503      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
504      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
505
506      if ( $itm->{'itemlost'} ) {
507          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
508          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
509          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
510      }
511
512      if( $itm->{'count_reserves'}){
513           if( $itm->{'count_reserves'} eq "Waiting"){ $itm->{'waiting'} = 1; }
514           if( $itm->{'count_reserves'} eq "Reserved"){ $itm->{'onhold'} = 1; }
515      }
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 # Amazon.com Stuff
694 if ( C4::Context->preference("OPACAmazonEnabled") ) {
695     $template->param( AmazonTld => get_amazon_tld() );
696     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
697     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
698     my @services;
699     if ( $amazon_reviews ) {
700         push( @services, 'EditorialReview', 'Reviews' );
701     }
702     if ( $amazon_similars ) {
703         push( @services, 'Similarities' );
704     }
705     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
706     my $similar_products_exist;
707     if ( $amazon_reviews ) {
708         my $item = $amazon_details->{Items}->{Item}->[0];
709         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
710         for my $one_review ( @$customer_reviews ) {
711             $one_review->{Date} = format_date($one_review->{Date});
712         }
713         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
714         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
715         $template->param( amazon_average_rating    => $average_rating * 20);
716         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
717         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
718     }
719     if ( $amazon_similars ) {
720         my $item = $amazon_details->{Items}->{Item}->[0];
721         my @similar_products;
722         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
723             # do we have any of these isbns in our collection?
724             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
725             # verify that there is at least one similar item
726             if (scalar(@$similar_biblionumbers)){
727                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
728                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
729             }
730         }
731         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
732         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
733     }
734 }
735
736 my $syndetics_elements;
737
738 if ( C4::Context->preference("SyndeticsEnabled") ) {
739     $template->param("SyndeticsEnabled" => 1);
740     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
741         eval {
742             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
743             for my $element (values %$syndetics_elements) {
744                 $template->param("Syndetics$element"."Exists" => 1 );
745                 #warn "Exists: "."Syndetics$element"."Exists";
746         }
747     };
748     warn $@ if $@;
749 }
750
751 if ( C4::Context->preference("SyndeticsEnabled")
752         && C4::Context->preference("SyndeticsSummary")
753         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
754         eval {
755             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
756             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
757         };
758         warn $@ if $@;
759
760 }
761
762 if ( C4::Context->preference("SyndeticsEnabled")
763         && C4::Context->preference("SyndeticsTOC")
764         && exists($syndetics_elements->{'TOC'}) ) {
765         eval {
766     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
767     $template->param( SYNDETICS_TOC => $syndetics_toc );
768         };
769         warn $@ if $@;
770 }
771
772 if ( C4::Context->preference("SyndeticsEnabled")
773     && C4::Context->preference("SyndeticsExcerpt")
774     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
775     eval {
776     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
777     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
778     };
779         warn $@ if $@;
780 }
781
782 if ( C4::Context->preference("SyndeticsEnabled")
783     && C4::Context->preference("SyndeticsReviews")) {
784     eval {
785     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
786     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
787     };
788         warn $@ if $@;
789 }
790
791 if ( C4::Context->preference("SyndeticsEnabled")
792     && C4::Context->preference("SyndeticsAuthorNotes")
793         && exists($syndetics_elements->{'ANOTES'}) ) {
794     eval {
795     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
796     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
797     };
798     warn $@ if $@;
799 }
800
801 # LibraryThingForLibraries ID Code and Tabbed View Option
802 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
803
804 $template->param(LibraryThingForLibrariesID =>
805 C4::Context->preference('LibraryThingForLibrariesID') ); 
806 $template->param(LibraryThingForLibrariesTabbedView =>
807 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
808
809
810 # Novelist Select
811 if( C4::Context->preference('NovelistSelectEnabled') ) 
812
813 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
814 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
815 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
816
817
818
819 # Babelthèque
820 if ( C4::Context->preference("Babeltheque") ) {
821     $template->param( 
822         Babeltheque => 1,
823     );
824 }
825
826 # Shelf Browser Stuff
827 if (C4::Context->preference("OPACShelfBrowser")) {
828     # pick the first itemnumber unless one was selected by the user
829     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
830     if (defined($starting_itemnumber)) {
831         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
832         my $nearby = GetNearbyItems($starting_itemnumber,3);
833
834         $template->param(
835             starting_homebranch => $nearby->{starting_homebranch}->{description},
836             starting_location => $nearby->{starting_location}->{description},
837             starting_ccode => $nearby->{starting_ccode}->{description},
838             starting_itemnumber => $nearby->{starting_itemnumber},
839             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
840             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
841             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
842             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
843             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
844             NEXT_SHELF_BROWSE => $nearby->{next},
845         );
846     }
847 }
848
849 if (C4::Context->preference("BakerTaylorEnabled")) {
850         $template->param(
851                 BakerTaylorEnabled  => 1,
852                 BakerTaylorImageURL => &image_url(),
853                 BakerTaylorLinkURL  => &link_url(),
854                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
855         );
856         my ($bt_user, $bt_pass);
857         if ($isbn and
858                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
859                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
860         {
861                 $template->param(
862                 BakerTaylorContentURL   =>
863                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
864                                 $bt_user,$bt_pass,$isbn)
865                 );
866         }
867 }
868
869 my $tag_quantity;
870 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
871         $template->param(
872                 TagsEnabled => 1,
873                 TagsShowOnDetail => $tag_quantity,
874                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
875         );
876         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
877                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
878 }
879
880 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
881     # These values are going to be read by Javascript, at least in the case
882     # of the google covers
883     $template->param(covernewwindow => 'true');
884 } else {
885     $template->param(covernewwindow => 'false');
886 }
887
888 #Search for title in links
889 my $marccontrolnumber   = GetMarcControlnumber   ($record, $marcflavour);
890
891 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
892     $dat->{author} ? $search_for_title =~ s/{AUTHOR}/$dat->{author}/g : $search_for_title =~ s/{AUTHOR}//g;
893     $dat->{title} =~ s/\/+$//; # remove trailing slash
894     $dat->{title} =~ s/\s+$//; # remove trailing space
895     $dat->{title} ? $search_for_title =~ s/{TITLE}/$dat->{title}/g : $search_for_title =~ s/{TITLE}//g;
896     $isbn ? $search_for_title =~ s/{ISBN}/$isbn/g : $search_for_title =~ s/{ISBN}//g;
897     $marccontrolnumber ? $search_for_title =~ s/{CONTROLNUMBER}/$marccontrolnumber/g : $search_for_title =~ s/{CONTROLNUMBER}//g;
898     $search_for_title =~ s/{BIBLIONUMBER}/$biblionumber/g;
899  $template->param('OPACSearchForTitleIn' => $search_for_title);
900 }
901
902 # We try to select the best default tab to show, according to what
903 # the user wants, and what's available for display
904 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
905 my $defaulttab = 
906     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
907         ? 'subscriptions' :
908     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
909         ? 'serialcollection' :
910     $opac_serial_default eq 'holdings' && $dat->{'count'} > 0
911         ? 'holdings' :
912     $subscriptionsnumber
913         ? 'subscriptions' :
914     @serialcollections > 0 
915         ? 'serialcollection' : 'subscription';
916 $template->param('defaulttab' => $defaulttab);
917
918 output_html_with_http_headers $query, $cookie, $template->output;