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