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