Bug 7743: Update opac-detail.pl to use KohaDates TT plugin
[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::XISBN qw(get_xisbns get_biblionumber_from_isbn);
36 use C4::External::Amazon;
37 use C4::External::Syndetics qw(get_syndetics_index get_syndetics_summary get_syndetics_toc get_syndetics_excerpt get_syndetics_reviews get_syndetics_anotes );
38 use C4::Review;
39 use C4::Members;
40 use C4::VirtualShelves;
41 use C4::XSLT;
42 use C4::ShelfBrowser;
43 use C4::Reserves;
44 use C4::Charset;
45 use MARC::Record;
46 use MARC::Field;
47 use List::MoreUtils qw/any none/;
48 use C4::Images;
49 use Koha::DateUtils;
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}     = $subscription->{histstartdate};
457     $cell{histenddate}       = $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_sqlduedatetime($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} = $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     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
645                 $_->{your_comment} = 1;
646                 $loggedincommenter = 1;
647         }
648 }
649
650
651 if(C4::Context->preference("ISBD")) {
652         $template->param(ISBD => 1);
653 }
654
655 $template->param(
656     ITEM_RESULTS        => \@items,
657     subscriptionsnumber => $subscriptionsnumber,
658     biblionumber        => $biblionumber,
659     subscriptions       => \@subs,
660     subscriptionsnumber => $subscriptionsnumber,
661     reviews             => $reviews,
662     loggedincommenter   => $loggedincommenter
663 );
664
665 # Lists
666
667 if (C4::Context->preference("virtualshelves") ) {
668    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
669 }
670
671
672 # XISBN Stuff
673 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
674     eval {
675         $template->param(
676             XISBNS => get_xisbns($isbn)
677         );
678     };
679     if ($@) { warn "XISBN Failed $@"; }
680 }
681
682 # Serial Collection
683 my @sc_fields = $record->field(955);
684 my @serialcollections = ();
685
686 foreach my $sc_field (@sc_fields) {
687     my %row_data;
688
689     $row_data{text}    = $sc_field->subfield('r');
690     $row_data{branch}  = $sc_field->subfield('9');
691
692     if ($row_data{text} && $row_data{branch}) { 
693         push (@serialcollections, \%row_data);
694     }
695 }
696
697 if (scalar(@serialcollections) > 0) {
698     $template->param(
699         serialcollection  => 1,
700         serialcollections => \@serialcollections);
701 }
702
703 # Local cover Images stuff
704 if (C4::Context->preference("OPACLocalCoverImages")){
705                 $template->param(OPACLocalCoverImages => 1);
706 }
707
708 # Amazon.com Stuff
709 if ( C4::Context->preference("OPACAmazonEnabled") ) {
710     $template->param( AmazonTld => get_amazon_tld() );
711     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
712     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
713     my @services;
714     if ( $amazon_reviews ) {
715         push( @services, 'EditorialReview', 'Reviews' );
716     }
717     if ( $amazon_similars ) {
718         push( @services, 'Similarities' );
719     }
720     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
721     my $similar_products_exist;
722     if ( $amazon_reviews ) {
723         my $item = $amazon_details->{Items}->{Item}->[0];
724         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
725         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
726         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
727         $template->param( amazon_average_rating    => $average_rating * 20);
728         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
729         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
730     }
731     if ( $amazon_similars ) {
732         my $item = $amazon_details->{Items}->{Item}->[0];
733         my @similar_products;
734         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
735             # do we have any of these isbns in our collection?
736             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
737             # verify that there is at least one similar item
738             if (scalar(@$similar_biblionumbers)){
739                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
740                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
741             }
742         }
743         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
744         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
745     }
746 }
747
748 my $syndetics_elements;
749
750 if ( C4::Context->preference("SyndeticsEnabled") ) {
751     $template->param("SyndeticsEnabled" => 1);
752     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
753         eval {
754             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
755             for my $element (values %$syndetics_elements) {
756                 $template->param("Syndetics$element"."Exists" => 1 );
757                 #warn "Exists: "."Syndetics$element"."Exists";
758         }
759     };
760     warn $@ if $@;
761 }
762
763 if ( C4::Context->preference("SyndeticsEnabled")
764         && C4::Context->preference("SyndeticsSummary")
765         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
766         eval {
767             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
768             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
769         };
770         warn $@ if $@;
771
772 }
773
774 if ( C4::Context->preference("SyndeticsEnabled")
775         && C4::Context->preference("SyndeticsTOC")
776         && exists($syndetics_elements->{'TOC'}) ) {
777         eval {
778     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
779     $template->param( SYNDETICS_TOC => $syndetics_toc );
780         };
781         warn $@ if $@;
782 }
783
784 if ( C4::Context->preference("SyndeticsEnabled")
785     && C4::Context->preference("SyndeticsExcerpt")
786     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
787     eval {
788     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
789     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
790     };
791         warn $@ if $@;
792 }
793
794 if ( C4::Context->preference("SyndeticsEnabled")
795     && C4::Context->preference("SyndeticsReviews")) {
796     eval {
797     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
798     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
799     };
800         warn $@ if $@;
801 }
802
803 if ( C4::Context->preference("SyndeticsEnabled")
804     && C4::Context->preference("SyndeticsAuthorNotes")
805         && exists($syndetics_elements->{'ANOTES'}) ) {
806     eval {
807     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
808     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
809     };
810     warn $@ if $@;
811 }
812
813 # LibraryThingForLibraries ID Code and Tabbed View Option
814 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
815
816 $template->param(LibraryThingForLibrariesID =>
817 C4::Context->preference('LibraryThingForLibrariesID') ); 
818 $template->param(LibraryThingForLibrariesTabbedView =>
819 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
820
821
822 # Novelist Select
823 if( C4::Context->preference('NovelistSelectEnabled') ) 
824
825 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
826 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
827 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
828
829
830
831 # Babelthèque
832 if ( C4::Context->preference("Babeltheque") ) {
833     $template->param( 
834         Babeltheque => 1,
835         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
836     );
837 }
838
839 # Social Networks
840 if ( C4::Context->preference( "SocialNetworks" ) ) {
841     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
842     $template->param( SocialNetworks => 1 );
843 }
844
845 # Shelf Browser Stuff
846 if (C4::Context->preference("OPACShelfBrowser")) {
847     # pick the first itemnumber unless one was selected by the user
848     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
849     if (defined($starting_itemnumber)) {
850         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
851         my $nearby = GetNearbyItems($starting_itemnumber,3);
852
853         $template->param(
854             starting_homebranch => $nearby->{starting_homebranch}->{description},
855             starting_location => $nearby->{starting_location}->{description},
856             starting_ccode => $nearby->{starting_ccode}->{description},
857             starting_itemnumber => $nearby->{starting_itemnumber},
858             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
859             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
860             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
861             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
862             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
863             NEXT_SHELF_BROWSE => $nearby->{next},
864         );
865     }
866 }
867
868 if (C4::Context->preference("BakerTaylorEnabled")) {
869         $template->param(
870                 BakerTaylorEnabled  => 1,
871                 BakerTaylorImageURL => &image_url(),
872                 BakerTaylorLinkURL  => &link_url(),
873                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
874         );
875         my ($bt_user, $bt_pass);
876         if ($isbn and
877                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
878                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
879         {
880                 $template->param(
881                 BakerTaylorContentURL   =>
882                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
883                                 $bt_user,$bt_pass,$isbn)
884                 );
885         }
886 }
887
888 my $tag_quantity;
889 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
890         $template->param(
891                 TagsEnabled => 1,
892                 TagsShowOnDetail => $tag_quantity,
893                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
894         );
895         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
896                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
897 }
898
899 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
900     # These values are going to be read by Javascript, at least in the case
901     # of the google covers
902     $template->param(covernewwindow => 'true');
903 } else {
904     $template->param(covernewwindow => 'false');
905 }
906
907 #Export options
908 my $OpacExportOptions=C4::Context->preference("OpacExportOptions");
909 my @export_options = split(/\|/,$OpacExportOptions);
910 $template->{VARS}->{'export_options'} = \@export_options;
911
912 #Search for title in links
913 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
914 my $marcissns = GetMarcISSN ( $record, $marcflavour );
915 my $issn = $marcissns->[0] || '';
916
917 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
918     $dat->{author} ? $search_for_title =~ s/{AUTHOR}/$dat->{author}/g : $search_for_title =~ s/{AUTHOR}//g;
919     $dat->{title} =~ s/\/+$//; # remove trailing slash
920     $dat->{title} =~ s/\s+$//; # remove trailing space
921     $dat->{title} ? $search_for_title =~ s/{TITLE}/$dat->{title}/g : $search_for_title =~ s/{TITLE}//g;
922     $isbn ? $search_for_title =~ s/{ISBN}/$isbn/g : $search_for_title =~ s/{ISBN}//g;
923     $issn ? $search_for_title =~ s/{ISSN}/$issn/g : $search_for_title =~ s/{ISSN}//g;
924     $marccontrolnumber ? $search_for_title =~ s/{CONTROLNUMBER}/$marccontrolnumber/g : $search_for_title =~ s/{CONTROLNUMBER}//g;
925     $search_for_title =~ s/{BIBLIONUMBER}/$biblionumber/g;
926     $template->param('OPACSearchForTitleIn' => $search_for_title);
927 }
928
929 # We try to select the best default tab to show, according to what
930 # the user wants, and what's available for display
931 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
932 my $defaulttab = 
933     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
934         ? 'subscriptions' :
935     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
936         ? 'serialcollection' :
937     $opac_serial_default eq 'holdings' && $dat->{'count'} > 0
938         ? 'holdings' :
939     $subscriptionsnumber
940         ? 'subscriptions' :
941     @serialcollections > 0 
942         ? 'serialcollection' : 'subscription';
943 $template->param('defaulttab' => $defaulttab);
944
945 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
946     my @images = ListImagesForBiblio($biblionumber);
947     $template->{VARS}->{localimages} = \@images;
948 }
949
950 output_html_with_http_headers $query, $cookie, $template->output;