Merge remote-tracking branch 'origin/new/bug_6199'
[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
498     # get collection code description, too
499     if ( my $ccode = $itm->{'ccode'} ) {
500         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
501     }
502     if ( defined $itm->{'location'} ) {
503         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
504     }
505     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
506         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
507         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
508     }
509     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
510         $itemfields{$_} = 1 if ($itm->{$_});
511     }
512
513      # walk through the item-level authorised values and populate some images
514      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
515      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
516
517      if ( $itm->{'itemlost'} ) {
518          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
519          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
520          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
521      }
522      my ($reserve_status) = C4::Reserves::CheckReserves($itm->{itemnumber});
523       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
524       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
525     
526      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
527      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
528         $itm->{transfertwhen} = $transfertwhen;
529         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
530         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
531      }
532 }
533
534 ## get notes and subjects from MARC record
535 my $dbh              = C4::Context->dbh;
536 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
537 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
538 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
539 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
540 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
541 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
542 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
543 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
544
545     $template->param(
546                      MARCNOTES               => $marcnotesarray,
547                      MARCSUBJCTS             => $marcsubjctsarray,
548                      MARCAUTHORS             => $marcauthorsarray,
549                      MARCSERIES              => $marcseriesarray,
550                      MARCURLS                => $marcurlsarray,
551                      MARCHOSTS               => $marchostsarray,
552                      norequests              => $norequests,
553                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
554                      itemdata_ccode          => $itemfields{ccode},
555                      itemdata_enumchron      => $itemfields{enumchron},
556                      itemdata_uri            => $itemfields{uri},
557                      itemdata_copynumber     => $itemfields{copynumber},
558                      itemdata_itemnotes          => $itemfields{itemnotes},
559                      authorised_value_images => $biblio_authorised_value_images,
560                      subtitle                => $subtitle,
561     );
562
563 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
564     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
565     my $subfields = substr $fieldspec, 3;
566     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
567     my @alternateholdingsinfo = ();
568     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
569
570     for my $field (@holdingsfields) {
571         my %holding = ( holding => '' );
572         my $havesubfield = 0;
573         for my $subfield ($field->subfields()) {
574             if ((index $subfields, $$subfield[0]) >= 0) {
575                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
576                 $holding{'holding'} .= $$subfield[1];
577                 $havesubfield++;
578             }
579         }
580         if ($havesubfield) {
581             push(@alternateholdingsinfo, \%holding);
582         }
583     }
584
585     $template->param(
586         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
587         );
588 }
589
590 foreach ( keys %{$dat} ) {
591     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
592 }
593
594 # some useful variables for enhanced content;
595 # in each case, we're grabbing the first value we find in
596 # the record and normalizing it
597 my $upc = GetNormalizedUPC($record,$marcflavour);
598 my $ean = GetNormalizedEAN($record,$marcflavour);
599 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
600 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
601 my $content_identifier_exists;
602 if ( $isbn or $ean or $oclc or $upc ) {
603     $content_identifier_exists = 1;
604 }
605 $template->param(
606         normalized_upc => $upc,
607         normalized_ean => $ean,
608         normalized_oclc => $oclc,
609         normalized_isbn => $isbn,
610         content_identifier_exists =>  $content_identifier_exists,
611 );
612
613 # COinS format FIXME: for books Only
614 $template->param(
615     ocoins => GetCOinSBiblio($record),
616 );
617
618 my $libravatar_enabled = 0;
619 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) {
620     eval {
621         require Libravatar::URL;
622         Libravatar::URL->import();
623     };
624     if (!$@ ) {
625         $libravatar_enabled = 1;
626     }
627 }
628
629 my $reviews = getreviews( $biblionumber, 1 );
630 my $loggedincommenter;
631 foreach ( @$reviews ) {
632     my $borrowerData   = GetMember('borrowernumber' => $_->{borrowernumber});
633     # setting some borrower info into this hash
634     $_->{title}     = $borrowerData->{'title'};
635     $_->{surname}   = $borrowerData->{'surname'};
636     $_->{firstname} = $borrowerData->{'firstname'};
637     if ($libravatar_enabled and $borrowerData->{'email'}) {
638         $_->{avatarurl} = libravatar_url(email => $borrowerData->{'email'}, https => $ENV{HTTPS});
639     }
640     $_->{userid}    = $borrowerData->{'userid'};
641     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
642     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
643                 $_->{your_comment} = 1;
644                 $loggedincommenter = 1;
645         }
646 }
647
648
649 if(C4::Context->preference("ISBD")) {
650         $template->param(ISBD => 1);
651 }
652
653 $template->param(
654     ITEM_RESULTS        => \@items,
655     subscriptionsnumber => $subscriptionsnumber,
656     biblionumber        => $biblionumber,
657     subscriptions       => \@subs,
658     subscriptionsnumber => $subscriptionsnumber,
659     reviews             => $reviews,
660     loggedincommenter   => $loggedincommenter
661 );
662
663 # Lists
664
665 if (C4::Context->preference("virtualshelves") ) {
666    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
667 }
668
669
670 # XISBN Stuff
671 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
672     eval {
673         $template->param(
674             XISBNS => get_xisbns($isbn)
675         );
676     };
677     if ($@) { warn "XISBN Failed $@"; }
678 }
679
680 # Serial Collection
681 my @sc_fields = $record->field(955);
682 my @serialcollections = ();
683
684 foreach my $sc_field (@sc_fields) {
685     my %row_data;
686
687     $row_data{text}    = $sc_field->subfield('r');
688     $row_data{branch}  = $sc_field->subfield('9');
689
690     if ($row_data{text} && $row_data{branch}) { 
691         push (@serialcollections, \%row_data);
692     }
693 }
694
695 if (scalar(@serialcollections) > 0) {
696     $template->param(
697         serialcollection  => 1,
698         serialcollections => \@serialcollections);
699 }
700
701 # Local cover Images stuff
702 if (C4::Context->preference("OPACLocalCoverImages")){
703                 $template->param(OPACLocalCoverImages => 1);
704 }
705
706 # Amazon.com Stuff
707 if ( C4::Context->preference("OPACAmazonEnabled") ) {
708     $template->param( AmazonTld => get_amazon_tld() );
709     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
710     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
711     my @services;
712     if ( $amazon_reviews ) {
713         push( @services, 'EditorialReview', 'Reviews' );
714     }
715     if ( $amazon_similars ) {
716         push( @services, 'Similarities' );
717     }
718     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
719     my $similar_products_exist;
720     if ( $amazon_reviews ) {
721         my $item = $amazon_details->{Items}->{Item}->[0];
722         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
723         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
724         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
725         $template->param( amazon_average_rating    => $average_rating * 20);
726         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
727         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
728     }
729     if ( $amazon_similars ) {
730         my $item = $amazon_details->{Items}->{Item}->[0];
731         my @similar_products;
732         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
733             # do we have any of these isbns in our collection?
734             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
735             # verify that there is at least one similar item
736             if (scalar(@$similar_biblionumbers)){
737                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
738                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
739             }
740         }
741         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
742         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
743     }
744 }
745
746 my $syndetics_elements;
747
748 if ( C4::Context->preference("SyndeticsEnabled") ) {
749     $template->param("SyndeticsEnabled" => 1);
750     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
751         eval {
752             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
753             for my $element (values %$syndetics_elements) {
754                 $template->param("Syndetics$element"."Exists" => 1 );
755                 #warn "Exists: "."Syndetics$element"."Exists";
756         }
757     };
758     warn $@ if $@;
759 }
760
761 if ( C4::Context->preference("SyndeticsEnabled")
762         && C4::Context->preference("SyndeticsSummary")
763         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
764         eval {
765             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
766             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
767         };
768         warn $@ if $@;
769
770 }
771
772 if ( C4::Context->preference("SyndeticsEnabled")
773         && C4::Context->preference("SyndeticsTOC")
774         && exists($syndetics_elements->{'TOC'}) ) {
775         eval {
776     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
777     $template->param( SYNDETICS_TOC => $syndetics_toc );
778         };
779         warn $@ if $@;
780 }
781
782 if ( C4::Context->preference("SyndeticsEnabled")
783     && C4::Context->preference("SyndeticsExcerpt")
784     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
785     eval {
786     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
787     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
788     };
789         warn $@ if $@;
790 }
791
792 if ( C4::Context->preference("SyndeticsEnabled")
793     && C4::Context->preference("SyndeticsReviews")) {
794     eval {
795     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
796     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
797     };
798         warn $@ if $@;
799 }
800
801 if ( C4::Context->preference("SyndeticsEnabled")
802     && C4::Context->preference("SyndeticsAuthorNotes")
803         && exists($syndetics_elements->{'ANOTES'}) ) {
804     eval {
805     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
806     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
807     };
808     warn $@ if $@;
809 }
810
811 # LibraryThingForLibraries ID Code and Tabbed View Option
812 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
813
814 $template->param(LibraryThingForLibrariesID =>
815 C4::Context->preference('LibraryThingForLibrariesID') ); 
816 $template->param(LibraryThingForLibrariesTabbedView =>
817 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
818
819
820 # Novelist Select
821 if( C4::Context->preference('NovelistSelectEnabled') ) 
822
823 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
824 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
825 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
826
827
828
829 # Babelthèque
830 if ( C4::Context->preference("Babeltheque") ) {
831     $template->param( 
832         Babeltheque => 1,
833         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
834     );
835 }
836
837 # Social Networks
838 if ( C4::Context->preference( "SocialNetworks" ) ) {
839     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
840     $template->param( SocialNetworks => 1 );
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;