Merge branch 'new/bug_6629'
[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($record),
603 );
604
605 my $libravatar_enabled = 0;
606 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) {
607     eval {
608         require Libravatar::URL;
609         Libravatar::URL->import();
610     };
611     if (!$@ ) {
612         $libravatar_enabled = 1;
613     }
614 }
615
616 my $reviews = getreviews( $biblionumber, 1 );
617 my $loggedincommenter;
618 foreach ( @$reviews ) {
619     my $borrowerData   = GetMember('borrowernumber' => $_->{borrowernumber});
620     # setting some borrower info into this hash
621     $_->{title}     = $borrowerData->{'title'};
622     $_->{surname}   = $borrowerData->{'surname'};
623     $_->{firstname} = $borrowerData->{'firstname'};
624     if ($libravatar_enabled and $borrowerData->{'email'}) {
625         $_->{avatarurl} = libravatar_url(email => $borrowerData->{'email'}, https => $ENV{HTTPS});
626     }
627     $_->{userid}    = $borrowerData->{'userid'};
628     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
629     $_->{datereviewed} = format_date($_->{datereviewed});
630     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
631                 $_->{your_comment} = 1;
632                 $loggedincommenter = 1;
633         }
634 }
635
636
637 if(C4::Context->preference("ISBD")) {
638         $template->param(ISBD => 1);
639 }
640
641 $template->param(
642     ITEM_RESULTS        => \@items,
643     subscriptionsnumber => $subscriptionsnumber,
644     biblionumber        => $biblionumber,
645     subscriptions       => \@subs,
646     subscriptionsnumber => $subscriptionsnumber,
647     reviews             => $reviews,
648     loggedincommenter   => $loggedincommenter
649 );
650
651 # Lists
652
653 if (C4::Context->preference("virtualshelves") ) {
654    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
655 }
656
657
658 # XISBN Stuff
659 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
660     eval {
661         $template->param(
662             XISBNS => get_xisbns($isbn)
663         );
664     };
665     if ($@) { warn "XISBN Failed $@"; }
666 }
667
668 # Serial Collection
669 my @sc_fields = $record->field(955);
670 my @serialcollections = ();
671
672 foreach my $sc_field (@sc_fields) {
673     my %row_data;
674
675     $row_data{text}    = $sc_field->subfield('r');
676     $row_data{branch}  = $sc_field->subfield('9');
677
678     if ($row_data{text} && $row_data{branch}) { 
679         push (@serialcollections, \%row_data);
680     }
681 }
682
683 if (scalar(@serialcollections) > 0) {
684     $template->param(
685         serialcollection  => 1,
686         serialcollections => \@serialcollections);
687 }
688
689 # Amazon.com Stuff
690 if ( C4::Context->preference("OPACAmazonEnabled") ) {
691     $template->param( AmazonTld => get_amazon_tld() );
692     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
693     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
694     my @services;
695     if ( $amazon_reviews ) {
696         push( @services, 'EditorialReview', 'Reviews' );
697     }
698     if ( $amazon_similars ) {
699         push( @services, 'Similarities' );
700     }
701     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
702     my $similar_products_exist;
703     if ( $amazon_reviews ) {
704         my $item = $amazon_details->{Items}->{Item}->[0];
705         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
706         for my $one_review ( @$customer_reviews ) {
707             $one_review->{Date} = format_date($one_review->{Date});
708         }
709         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
710         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
711         $template->param( amazon_average_rating    => $average_rating * 20);
712         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
713         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
714     }
715     if ( $amazon_similars ) {
716         my $item = $amazon_details->{Items}->{Item}->[0];
717         my @similar_products;
718         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
719             # do we have any of these isbns in our collection?
720             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
721             # verify that there is at least one similar item
722             if (scalar(@$similar_biblionumbers)){
723                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
724                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
725             }
726         }
727         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
728         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
729     }
730 }
731
732 my $syndetics_elements;
733
734 if ( C4::Context->preference("SyndeticsEnabled") ) {
735     $template->param("SyndeticsEnabled" => 1);
736     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
737         eval {
738             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
739             for my $element (values %$syndetics_elements) {
740                 $template->param("Syndetics$element"."Exists" => 1 );
741                 #warn "Exists: "."Syndetics$element"."Exists";
742         }
743     };
744     warn $@ if $@;
745 }
746
747 if ( C4::Context->preference("SyndeticsEnabled")
748         && C4::Context->preference("SyndeticsSummary")
749         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
750         eval {
751             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
752             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
753         };
754         warn $@ if $@;
755
756 }
757
758 if ( C4::Context->preference("SyndeticsEnabled")
759         && C4::Context->preference("SyndeticsTOC")
760         && exists($syndetics_elements->{'TOC'}) ) {
761         eval {
762     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
763     $template->param( SYNDETICS_TOC => $syndetics_toc );
764         };
765         warn $@ if $@;
766 }
767
768 if ( C4::Context->preference("SyndeticsEnabled")
769     && C4::Context->preference("SyndeticsExcerpt")
770     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
771     eval {
772     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
773     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
774     };
775         warn $@ if $@;
776 }
777
778 if ( C4::Context->preference("SyndeticsEnabled")
779     && C4::Context->preference("SyndeticsReviews")) {
780     eval {
781     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
782     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
783     };
784         warn $@ if $@;
785 }
786
787 if ( C4::Context->preference("SyndeticsEnabled")
788     && C4::Context->preference("SyndeticsAuthorNotes")
789         && exists($syndetics_elements->{'ANOTES'}) ) {
790     eval {
791     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
792     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
793     };
794     warn $@ if $@;
795 }
796
797 # LibraryThingForLibraries ID Code and Tabbed View Option
798 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
799
800 $template->param(LibraryThingForLibrariesID =>
801 C4::Context->preference('LibraryThingForLibrariesID') ); 
802 $template->param(LibraryThingForLibrariesTabbedView =>
803 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
804
805
806 # Novelist Select
807 if( C4::Context->preference('NovelistSelectEnabled') ) 
808
809 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
810 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
811 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
812
813
814
815 # Babelthèque
816 if ( C4::Context->preference("Babeltheque") ) {
817     $template->param( 
818         Babeltheque => 1,
819     );
820 }
821
822 # Shelf Browser Stuff
823 if (C4::Context->preference("OPACShelfBrowser")) {
824     # pick the first itemnumber unless one was selected by the user
825     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
826     if (defined($starting_itemnumber)) {
827         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
828         my $nearby = GetNearbyItems($starting_itemnumber,3);
829
830         $template->param(
831             starting_homebranch => $nearby->{starting_homebranch}->{description},
832             starting_location => $nearby->{starting_location}->{description},
833             starting_ccode => $nearby->{starting_ccode}->{description},
834             starting_itemnumber => $nearby->{starting_itemnumber},
835             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
836             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
837             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
838             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
839             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
840             NEXT_SHELF_BROWSE => $nearby->{next},
841         );
842     }
843 }
844
845 if (C4::Context->preference("BakerTaylorEnabled")) {
846         $template->param(
847                 BakerTaylorEnabled  => 1,
848                 BakerTaylorImageURL => &image_url(),
849                 BakerTaylorLinkURL  => &link_url(),
850                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
851         );
852         my ($bt_user, $bt_pass);
853         if ($isbn and
854                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
855                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
856         {
857                 $template->param(
858                 BakerTaylorContentURL   =>
859                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
860                                 $bt_user,$bt_pass,$isbn)
861                 );
862         }
863 }
864
865 my $tag_quantity;
866 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
867         $template->param(
868                 TagsEnabled => 1,
869                 TagsShowOnDetail => $tag_quantity,
870                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
871         );
872         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
873                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
874 }
875
876 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
877     # These values are going to be read by Javascript, at least in the case
878     # of the google covers
879     $template->param(covernewwindow => 'true');
880 } else {
881     $template->param(covernewwindow => 'false');
882 }
883
884 #Search for title in links
885 my $marccontrolnumber   = GetMarcControlnumber   ($record, $marcflavour);
886
887 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
888     $dat->{author} ? $search_for_title =~ s/{AUTHOR}/$dat->{author}/g : $search_for_title =~ s/{AUTHOR}//g;
889     $dat->{title} =~ s/\/+$//; # remove trailing slash
890     $dat->{title} =~ s/\s+$//; # remove trailing space
891     $dat->{title} ? $search_for_title =~ s/{TITLE}/$dat->{title}/g : $search_for_title =~ s/{TITLE}//g;
892     $isbn ? $search_for_title =~ s/{ISBN}/$isbn/g : $search_for_title =~ s/{ISBN}//g;
893     $marccontrolnumber ? $search_for_title =~ s/{CONTROLNUMBER}/$marccontrolnumber/g : $search_for_title =~ s/{CONTROLNUMBER}//g;
894     $search_for_title =~ s/{BIBLIONUMBER}/$biblionumber/g;
895  $template->param('OPACSearchForTitleIn' => $search_for_title);
896 }
897
898 # We try to select the best default tab to show, according to what
899 # the user wants, and what's available for display
900 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
901 my $defaulttab = 
902     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
903         ? 'subscriptions' :
904     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
905         ? 'serialcollection' :
906     $opac_serial_default eq 'holdings' && $dat->{'count'} > 0
907         ? 'holdings' :
908     $subscriptionsnumber
909         ? 'subscriptions' :
910     @serialcollections > 0 
911         ? 'serialcollection' : 'subscription';
912 $template->param('defaulttab' => $defaulttab);
913
914 output_html_with_http_headers $query, $cookie, $template->output;