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