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