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