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