Bug 30844: Ensure that allow_nonref is enabled when using older versions of JSON
[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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 use Modern::Perl;
24
25 use CGI qw ( -utf8 );
26 use C4::Acquisition qw( SearchOrders );
27 use C4::Auth qw( get_template_and_user get_session );
28 use C4::Koha qw(
29     getitemtypeimagelocation
30     GetNormalizedEAN
31     GetNormalizedISBN
32     GetNormalizedOCLCNumber
33     GetNormalizedUPC
34 );
35 use C4::Search qw( new_record_from_zebra searchResults getRecords );
36 use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials );
37 use C4::Output qw( parametrized_url output_html_with_http_headers );
38 use C4::Biblio qw(
39     CountItemsIssued
40     GetBiblioData
41     GetMarcAuthors
42     GetMarcBiblio
43     GetMarcControlnumber
44     GetMarcISBN
45     GetMarcISSN
46     GetMarcSeries
47     GetMarcSubjects
48     GetMarcUrls
49 );
50 use C4::Items qw( GetHiddenItemnumbers GetItemsInfo );
51 use C4::Circulation qw( GetTransfers );
52 use C4::Tags qw( get_tags );
53 use C4::XISBN qw( get_xisbns );
54 use C4::External::Amazon qw( get_amazon_tld );
55 use C4::External::BakerTaylor qw( image_url link_url );
56 use C4::External::Syndetics qw(
57     get_syndetics_anotes
58     get_syndetics_excerpt
59     get_syndetics_index
60     get_syndetics_reviews
61     get_syndetics_summary
62     get_syndetics_toc
63 );
64 use C4::Members;
65 use C4::XSLT qw( XSLTParse4Display );
66 use C4::ShelfBrowser qw( GetNearbyItems );
67 use C4::Reserves qw( GetReserveStatus );
68 use C4::Charset qw( SetUTF8Flag );
69 use MARC::Field;
70 use List::MoreUtils qw( any );
71 use C4::HTML5Media;
72 use C4::CourseReserves qw( GetItemCourseReservesInfo );
73
74 use Koha::Biblios;
75 use Koha::RecordProcessor;
76 use Koha::AuthorisedValues;
77 use Koha::CirculationRules;
78 use Koha::Items;
79 use Koha::ItemTypes;
80 use Koha::Acquisition::Orders;
81 use Koha::Virtualshelves;
82 use Koha::Patrons;
83 use Koha::Plugins;
84 use Koha::Ratings;
85 use Koha::Reviews;
86 use Koha::SearchEngine::Search;
87 use Koha::SearchEngine::QueryBuilder;
88
89 use JSON qw( decode_json );
90
91 my $query = CGI->new();
92
93 my $biblionumber = $query->param('biblionumber') || $query->param('bib') || 0;
94 $biblionumber = int($biblionumber);
95
96 my $specific_item = $query->param('itemnumber') ? Koha::Items->find( scalar $query->param('itemnumber') ) : undef;
97 $biblionumber = $specific_item->biblionumber if $specific_item;
98
99 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
100     {
101         template_name   => "opac-detail.tt",
102         query           => $query,
103         type            => "opac",
104         authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
105     }
106 );
107
108 my @all_items = GetItemsInfo($biblionumber);
109 if( $specific_item ) {
110     @all_items = grep { $_->{itemnumber} == $query->param('itemnumber') } @all_items;
111     $template->param( specific_item => 1 );
112 }
113 my @hiddenitems;
114 my $patron = Koha::Patrons->find( $borrowernumber );
115
116 my $record = GetMarcBiblio({
117     biblionumber => $biblionumber,
118     opac         => 1 });
119 if ( ! $record ) {
120     print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
121     exit;
122 }
123
124 my $biblio = Koha::Biblios->find( $biblionumber );
125 unless ( $patron and $patron->category->override_hidden_items ) {
126     # only skip this check if there's a logged in user
127     # and its category overrides OpacHiddenItems
128     if ( $biblio->hidden_in_opac({ rules => C4::Context->yaml_preference('OpacHiddenItems') }) ) {
129         print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early
130         exit;
131     }
132     if ( scalar @all_items >= 1 ) {
133         push @hiddenitems,
134           GetHiddenItemnumbers( { items => \@all_items, borcat => $patron ? $patron->categorycode : undef } );
135     }
136 }
137
138 my $framework = $biblio ? $biblio->frameworkcode : q{};
139 my $record_processor = Koha::RecordProcessor->new({
140     filters => 'ViewPolicy',
141     options => {
142         interface => 'opac',
143         frameworkcode => $framework
144     }
145 });
146 $record_processor->process($record);
147
148 # redirect if opacsuppression is enabled and biblio is suppressed
149 if (C4::Context->preference('OpacSuppression')) {
150     # FIXME hardcoded; the suppression flag ought to be materialized
151     # as a column on biblio or the like
152     my $opacsuppressionfield = '942';
153     my $opacsuppressionfieldvalue = $record->field($opacsuppressionfield);
154     # redirect to opac-blocked info page or 404?
155     my $opacsuppressionredirect;
156     if ( C4::Context->preference("OpacSuppressionRedirect") ) {
157         $opacsuppressionredirect = "/cgi-bin/koha/opac-blocked.pl";
158     } else {
159         $opacsuppressionredirect = "/cgi-bin/koha/errors/404.pl";
160     }
161     if ( $opacsuppressionfieldvalue &&
162          $opacsuppressionfieldvalue->subfield("n") &&
163          $opacsuppressionfieldvalue->subfield("n") == 1) {
164         # if OPAC suppression by IP address
165         if (C4::Context->preference('OpacSuppressionByIPRange')) {
166             my $IPAddress = $ENV{'REMOTE_ADDR'};
167             my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
168             if ($IPAddress !~ /^$IPRange/)  {
169                 print $query->redirect($opacsuppressionredirect);
170                 exit;
171             }
172         } else {
173             print $query->redirect($opacsuppressionredirect);
174             exit;
175         }
176     }
177 }
178
179 $template->param(
180     biblio => $biblio
181 );
182
183 # get biblionumbers stored in the cart
184 my @cart_list;
185
186 if($query->cookie("bib_list")){
187     my $cart_list = $query->cookie("bib_list");
188     @cart_list = split(/\//, $cart_list);
189     if ( grep {$_ eq $biblionumber} @cart_list) {
190         $template->param( incart => 1 );
191     }
192 }
193
194
195 SetUTF8Flag($record);
196 my $marcflavour      = C4::Context->preference("marcflavour");
197 my $ean = GetNormalizedEAN( $record, $marcflavour );
198
199 my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults");
200
201 # We look for the busc param to build the simple paging from the search
202 if ($OpacBrowseResults) {
203 my $session = get_session($query->cookie("CGISESSID"));
204 my %paging = (previous => {}, next => {});
205 if ($session->param('busc')) {
206     use URI::Escape qw( uri_escape_utf8 uri_unescape );
207
208     # Rebuild the string to store on session
209     # param value is URI encoded and params separator is HTML encode (&amp;)
210     sub rebuildBuscParam
211     {
212         my $arrParamsBusc = shift;
213
214         my $pasarParams = '';
215         my $j = 0;
216         for (keys %$arrParamsBusc) {
217             if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
218                 if (defined($arrParamsBusc->{$_})) {
219                     $pasarParams .= '&amp;' if ($j);
220                     $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} ));
221                     $j++;
222                 }
223             } else {
224                 for my $value (@{$arrParamsBusc->{$_}}) {
225                     next if !defined($value);
226                     $pasarParams .= '&amp;' if ($j);
227                     $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value));
228                     $j++;
229                 }
230             }
231         }
232         return $pasarParams;
233     }#rebuildBuscParam
234
235     # Search given the current values from the busc param
236     sub searchAgain
237     {
238         my ($arrParamsBusc, $offset, $results_per_page, $patron) = @_;
239
240         my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
241         my @servers;
242         @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
243         @servers = ("biblioserver") unless (@servers);
244
245         my ($default_sort_by, @sort_by);
246         $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
247         @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
248         $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
249         my ($error, $results_hashref, $facets);
250         eval {
251             my $searcher = Koha::SearchEngine::Search->new(
252                 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
253             my $json = JSON->new->utf8->allow_nonref(1);
254             ($error, $results_hashref, $facets) = $searcher->search_compat($json->decode($arrParamsBusc->{'query'}),$arrParamsBusc->{'simple_query'},\@sort_by,\@servers,$results_per_page,$offset,undef,$itemtypes,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'});
255         };
256         my $hits;
257         my @newresults;
258         my $search_context = {
259             'interface' => 'opac',
260             'category'  => ($patron) ? $patron->categorycode : q{}
261         };
262         for (my $i=0;$i<@servers;$i++) {
263             my $server = $servers[$i];
264             $hits = $results_hashref->{$server}->{"hits"};
265             @newresults = searchResults( $search_context, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
266         }
267         return \@newresults;
268     }#searchAgain
269
270     # Build the current list of biblionumbers in this search
271     sub buildListBiblios
272     {
273         my ($newresultsRef, $results_per_page) = @_;
274
275         my $listBiblios = '';
276         my $j = 0;
277         foreach (@$newresultsRef) {
278             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
279             $listBiblios .= $bibnum . ',';
280             $j++;
281             last if ($j == $results_per_page);
282         }
283         chop $listBiblios if ($listBiblios =~ /,$/);
284         return $listBiblios;
285     }#buildListBiblios
286
287     my $busc = $session->param("busc");
288     my @arrBusc = split(/\&(?:amp;)?/, $busc);
289     my ($key, $value);
290     my %arrParamsBusc = ();
291     for (@arrBusc) {
292         ($key, $value) = split(/=/, $_, 2);
293         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
294             $arrParamsBusc{$key} = uri_unescape($value);
295         } else {
296             unless (exists($arrParamsBusc{$key})) {
297                 $arrParamsBusc{$key} = [];
298             }
299             push @{$arrParamsBusc{$key}}, uri_unescape($value);
300         }
301     }
302     my $searchAgain = 0;
303     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
304     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
305     $arrParamsBusc{'count'} = $results_per_page;
306     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
307     # The value OPACnumSearchResults has changed and the search has to be rebuild
308     if ($count != $results_per_page) {
309         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
310             my $indexBiblio = 0;
311             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
312             for (@arrBibliosAux) {
313                 last if ($_ == $biblionumber);
314                 $indexBiblio++;
315             }
316             $indexBiblio += $offset;
317             $offset = int($indexBiblio / $count) * $count;
318             $arrParamsBusc{'offset'} = $offset;
319         }
320         $arrParamsBusc{'count'} = $count;
321         $results_per_page = $count;
322         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page, $patron);
323         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
324         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
325         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
326         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
327         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
328         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
329         $session->param("busc" => $newbusc);
330         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
331     } else {
332         my $modifyListBiblios = 0;
333         # We come from a previous click
334         if (exists($arrParamsBusc{'previous'})) {
335             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
336             delete $arrParamsBusc{'previous'};
337         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
338             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
339             delete $arrParamsBusc{'next'};
340         }
341         if ($modifyListBiblios) {
342             if (exists($arrParamsBusc{'newlistBiblios'})) {
343                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
344                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
345                 my @arrAux = split(',', $listBibliosAux);
346                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
347                 if ($modifyListBiblios == 1) {
348                     $arrParamsBusc{'next'} = $arrAux[0];
349                     $paging{'next'}->{biblionumber} = $arrAux[0];
350                 }else {
351                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
352                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
353                 }
354             } else {
355                 delete $arrParamsBusc{'listBiblios'};
356             }
357             my $offsetAux = $arrParamsBusc{'offset'};
358             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
359             $arrParamsBusc{'offsetSearch'} = $offsetAux;
360             $offset = $arrParamsBusc{'offset'};
361             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
362             $session->param("busc" => $newbusc);
363             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
364         }
365     }
366     my $buscParam = '';
367     my $j = 0;
368     # Rebuild the query for the button "back to results"
369     for (@arrBusc) {
370         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
371             $buscParam .= '&amp;' unless ($j == 0);
372             $buscParam .= $_; # string already URI encoded
373             $j++;
374         }
375     }
376     $template->param('busc' => $buscParam);
377     my $offsetSearch;
378     my @arrBiblios;
379     # We are inside the list of biblios and we don't have to search
380     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
381         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
382         if (@arrBiblios) {
383             # We are at the first item of the list
384             if ($arrBiblios[0] == $biblionumber) {
385                 if (@arrBiblios > 1) {
386                     for (my $j = 1; $j < @arrBiblios; $j++) {
387                         next unless ($arrBiblios[$j]);
388                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
389                         last;
390                     }
391                 }
392                 # search again if we are not at the first searching list
393                 if ($offset && !$arrParamsBusc{'previous'}) {
394                     $searchAgain = 1;
395                     $offsetSearch = $offset - $results_per_page;
396                 }
397             # we are at the last item of the list
398             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
399                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
400                     next unless ($arrBiblios[$j]);
401                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
402                     last;
403                 }
404                 if (!$offset) {
405                     # search again if we are at the first list and there is more results
406                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
407                 } else {
408                     # search again if we aren't at the first list and there is more results
409                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
410                 }
411                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
412             } else {
413                 for (my $j = 1; $j < $#arrBiblios; $j++) {
414                     if ($arrBiblios[$j] == $biblionumber) {
415                         for (my $z = $j - 1; $z >= 0; $z--) {
416                             next unless ($arrBiblios[$z]);
417                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
418                             last;
419                         }
420                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
421                             next unless ($arrBiblios[$z]);
422                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
423                             last;
424                         }
425                         last;
426                     }
427                 }
428             }
429         }
430         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
431     }
432     if ($searchAgain) {
433         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page, $patron);
434         my @newresults = @$newresultsRef;
435         # build the new listBiblios
436         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
437         unless (exists($arrParamsBusc{'listBiblios'})) {
438             $arrParamsBusc{'listBiblios'} = $listBiblios;
439             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
440         } else {
441             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
442         }
443         # From the new list we build again the next and previous result
444         if (@arrBiblios) {
445             if ($arrBiblios[0] == $biblionumber) {
446                 for (my $j = $#newresults; $j >= 0; $j--) {
447                     next unless ($newresults[$j]);
448                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
449                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
450                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
451                    last;
452                 }
453             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
454                 for (my $j = 0; $j < @newresults; $j++) {
455                     next unless ($newresults[$j]);
456                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
457                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
458                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
459                     last;
460                 }
461             }
462         }
463         # build new busc param
464         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
465         $session->param("busc" => $newbusc);
466     }
467     my ($numberBiblioPaging, $dataBiblioPaging);
468     # Previous biblio
469     $numberBiblioPaging = $paging{'previous'}->{biblionumber};
470     if ($numberBiblioPaging) {
471         $template->param( 'previousBiblionumber' => $numberBiblioPaging );
472         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
473         $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
474     }
475     # Next biblio
476     $numberBiblioPaging = $paging{'next'}->{biblionumber};
477     if ($numberBiblioPaging) {
478         $template->param( 'nextBiblionumber' => $numberBiblioPaging );
479         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
480         $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
481     }
482     # Partial list of biblio results
483     my @listResults;
484     for (my $j = 0; $j < @arrBiblios; $j++) {
485         next unless ($arrBiblios[$j]);
486         $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber);
487         next unless $dataBiblioPaging;
488         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]};
489     }
490     $template->param('listResults' => \@listResults) if (@listResults);
491     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
492     $template->param( 'offset' => $offset );
493 }
494 }
495
496 $template->param(
497     OPACShowCheckoutName => C4::Context->preference("OPACShowCheckoutName"),
498 );
499
500 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
501     # adding items linked via host biblios
502     my $analyticfield = '773';
503     if ($marcflavour eq 'MARC21'){
504         $analyticfield = '773';
505     } elsif ($marcflavour eq 'UNIMARC') {
506         $analyticfield = '461';
507     }
508     foreach my $hostfield ( $record->field($analyticfield)) {
509         my $hostbiblionumber = $hostfield->subfield("0");
510         my $linkeditemnumber = $hostfield->subfield("9");
511         my @hostitemInfos = GetItemsInfo($hostbiblionumber);
512         foreach my $hostitemInfo (@hostitemInfos){
513             if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
514                 push(@all_items, $hostitemInfo);
515             }
516         }
517     }
518 }
519
520 my @items;
521
522 # Are there items to hide?
523 my $hideitems;
524 $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
525
526 # Hide items
527 if ($hideitems) {
528     for my $itm (@all_items) {
529         if  ( C4::Context->preference('hidelostitems') ) {
530             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
531         } else {
532             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
533     }
534 }
535 } else {
536     # Or not
537     @items = @all_items;
538 }
539
540 my $dat = &GetBiblioData($biblionumber);
541 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
542     {
543         frameworkcode => $dat->{'frameworkcode'},
544         interface     => 'opac',
545     } );
546
547 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
548 # imageurl:
549 my $itemtype = $dat->{'itemtype'};
550 if ( $itemtype ) {
551     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
552     $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
553 }
554
555 my $shelflocations =
556   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
557 my $collections =
558   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
559 my $copynumbers =
560   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
561
562 #coping with subscriptions
563 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
564 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
565
566 my @subs;
567 $dat->{'serial'}=1 if $subscriptionsnumber;
568 foreach my $subscription (@subscriptions) {
569     my $serials_to_display;
570     my %cell;
571     $cell{subscriptionid}    = $subscription->{subscriptionid};
572     $cell{subscriptionnotes} = $subscription->{notes};
573     $cell{missinglist}       = $subscription->{missinglist};
574     $cell{opacnote}          = $subscription->{opacnote};
575     $cell{histstartdate}     = $subscription->{histstartdate};
576     $cell{histenddate}       = $subscription->{histenddate};
577     $cell{branchcode}        = $subscription->{branchcode};
578     $cell{callnumber}        = $subscription->{callnumber};
579     $cell{location}          = $subscription->{location};
580     $cell{closed}            = $subscription->{closed};
581     $cell{letter}            = $subscription->{letter};
582     $cell{biblionumber}      = $subscription->{biblionumber};
583     #get the three latest serials.
584     $serials_to_display = $subscription->{opacdisplaycount};
585     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
586         $cell{opacdisplaycount} = $serials_to_display;
587     $cell{latestserials} =
588       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
589     if ( $borrowernumber ) {
590         my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} );
591         my $subscriber = $subscription_object->subscribers->find( $borrowernumber );
592         $cell{hasalert} = 1 if $subscriber;
593     }
594     push @subs, \%cell;
595 }
596
597 $dat->{'count'} = scalar(@items);
598
599
600 my (%item_reserves, %priority);
601 my ($show_holds_count, $show_priority);
602 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
603     m/holds/o and $show_holds_count = 1;
604     m/priority/ and $show_priority = 1;
605 }
606 my $has_hold;
607 if ( $show_holds_count || $show_priority) {
608     my $holds = $biblio->holds;
609     $template->param( holds_count  => $holds->count );
610     while ( my $hold = $holds->next ) {
611         $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber;
612         if ($show_priority && $hold->borrowernumber == $borrowernumber) {
613             $has_hold = 1;
614             $hold->itemnumber
615                 ? ($priority{ $hold->itemnumber } = $hold->priority)
616                 : ($template->param( priority => $hold->priority ));
617         }
618     }
619 }
620 $template->param( show_priority => $has_hold ) ;
621
622 my %itemfields;
623 my (@itemloop, @otheritemloop);
624 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
625 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
626     $template->param(SeparateHoldings => 1);
627 }
628 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
629 my $viewallitems = $query->param('viewallitems');
630 my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50;
631
632 # Get component parts details
633 my $showcomp = C4::Context->preference('ShowComponentRecords');
634 my ( $parts, $show_analytics );
635 if ( $showcomp eq 'both' || $showcomp eq 'opac' ) {
636     if ( my $components = $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) ) {
637         $show_analytics = 1 if @{$components}; # just show link when having results
638         for my $part ( @{$components} ) {
639             $part = C4::Search::new_record_from_zebra( 'biblioserver', $part );
640             my $id = Koha::SearchEngine::Search::extract_biblionumber( $part );
641
642             push @{$parts},
643               XSLTParse4Display(
644                 {
645                     biblionumber => $id,
646                     record       => $part,
647                     xsl_syspref  => 'OPACXSLTResultsDisplay',
648                     fix_amps     => 1,
649                 }
650               );
651         }
652         $template->param( ComponentParts => $parts );
653         $template->param( ComponentPartsQuery => $biblio->get_components_query );
654     }
655 } else { # check if we should show analytics anyway
656     $show_analytics = 1 if @{$biblio->get_marc_components(1)}; # count matters here, results does not
657 }
658
659 # XSLT processing of some stuff
660 my $variables = {};
661 my @plugin_responses = Koha::Plugins->call(
662     'opac_detail_xslt_variables',
663     {
664         biblio_id => $biblionumber,
665         lang      => C4::Languages::getlanguage(),
666         patron_id => $borrowernumber,
667     },
668 );
669 for my $plugin_variables ( @plugin_responses ) {
670     $variables = { %$variables, %$plugin_variables };
671 }
672 $variables->{anonymous_session} = $borrowernumber ? 0 : 1;
673 $variables->{show_analytics_link} = $show_analytics;
674 $template->param(
675     XSLTBloc => XSLTParse4Display({
676         biblionumber   => $biblionumber,
677         record         => $record,
678         xsl_syspref    => 'OPACXSLTDetailsDisplay',
679         fix_amps       => 1,
680         xslt_variables => $variables,
681     }),
682 );
683
684 # Get items on order
685 my ( @itemnumbers_on_order );
686 if ( C4::Context->preference('OPACAcquisitionDetails' ) ) {
687     my $orders = C4::Acquisition::SearchOrders({
688         biblionumber => $biblionumber,
689         ordered => 1,
690     });
691     my $total_quantity = 0;
692     for my $order ( @$orders ) {
693         my $order = Koha::Acquisition::Orders->find( $order->{ordernumber} );
694         my $basket = $order->basket;
695         if ( $basket->effective_create_items eq 'ordering' ) {
696             @itemnumbers_on_order = $order->items->get_column('itemnumber');
697         }
698         $total_quantity += $order->quantity;
699     }
700     $template->{VARS}->{acquisition_details} = {
701         total_quantity => $total_quantity,
702     };
703 }
704
705 my $allow_onshelf_holds;
706 my ( $itemloop_has_images, $otheritemloop_has_images );
707 if ( not $viewallitems and @items > $max_items_to_display ) {
708     $template->param(
709         too_many_items => 1,
710         items_count => scalar( @items ),
711     );
712 } else {
713   for my $itm (@items) {
714     my $item = Koha::Items->find( $itm->{itemnumber} );
715     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
716     $itm->{priority} = $priority{ $itm->{itemnumber} };
717
718     $allow_onshelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } )
719       unless $allow_onshelf_holds;
720
721     # get collection code description, too
722     my $ccode = $itm->{'ccode'};
723     $itm->{'ccode'} = $collections->{$ccode} if defined($ccode) && $collections && exists( $collections->{$ccode} );
724     my $copynumber = $itm->{'copynumber'};
725     $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
726     if ( defined $itm->{'location'} ) {
727         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
728     }
729     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
730         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
731         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{translated_description};
732     }
733     foreach (qw(ccode materials enumchron copynumber itemnotes location_description uri)) {
734         $itemfields{$_} = 1 if ($itm->{$_});
735     }
736
737      my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
738       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
739       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
740     
741      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
742      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
743         $itm->{transfertwhen} = $transfertwhen;
744         $itm->{transfertfrom} = $transfertfrom;
745         $itm->{transfertto}   = $transfertto;
746      }
747     
748     if ( C4::Context->preference('OPACAcquisitionDetails') ) {
749         $itm->{on_order} = 1
750           if grep { $_ eq $itm->{itemnumber} } @itemnumbers_on_order;
751     }
752
753     if ( C4::Context->preference("OPACLocalCoverImages") == 1 ) {
754         $itm->{cover_images} = $item->cover_images;
755     }
756
757     my $itembranch = $itm->{$separatebranch};
758     if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
759         if ($itembranch and $itembranch eq $currentbranch) {
760             push @itemloop, $itm;
761             $itemloop_has_images++ if $item->cover_images->count;
762         } else {
763             push @otheritemloop, $itm;
764             $otheritemloop_has_images++ if $item->cover_images->count;
765         }
766     } else {
767         push @itemloop, $itm;
768         $itemloop_has_images++ if $item->cover_images->count;
769     }
770   }
771 }
772
773 if( $allow_onshelf_holds || CountItemsIssued($biblionumber) || $biblio->has_items_waiting_or_intransit ) {
774     $template->param( ReservableItems => 1 );
775 }
776
777 $template->param(
778     itemloop_has_images      => $itemloop_has_images,
779     otheritemloop_has_images => $otheritemloop_has_images,
780 );
781
782 # Display only one tab if one items list is empty
783 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
784     $template->param(SeparateHoldings => 0);
785     if (scalar(@itemloop) == 0) {
786         @itemloop = @otheritemloop;
787     }
788 }
789
790 my $marcnotesarray = $biblio->get_marc_notes({ marcflavour => $marcflavour, opac => 1 });
791
792 if( C4::Context->preference('ArticleRequests') ) {
793     my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef;
794     my $itemtype = Koha::ItemTypes->find($biblio->itemtype);
795     my $artreqpossible = $patron
796         ? $biblio->can_article_request( $patron )
797         : $itemtype
798         ? $itemtype->may_article_request
799         : q{};
800     $template->param( artreqpossible => $artreqpossible );
801 }
802
803 my $norequests = ! $biblio->items->filter_by_for_hold->count;
804     $template->param(
805                      MARCNOTES               => $marcnotesarray,
806                      norequests              => $norequests,
807                      itemdata_ccode          => $itemfields{ccode},
808                      itemdata_materials      => $itemfields{materials},
809                      itemdata_enumchron      => $itemfields{enumchron},
810                      itemdata_uri            => $itemfields{uri},
811                      itemdata_copynumber     => $itemfields{copynumber},
812                      itemdata_itemnotes      => $itemfields{itemnotes},
813                      itemdata_location       => $itemfields{location_description},
814                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
815     );
816
817 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
818     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
819     my $subfields = substr $fieldspec, 3;
820     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
821     my @alternateholdingsinfo = ();
822     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
823
824     for my $field (@holdingsfields) {
825         my %holding = ( holding => '' );
826         my $havesubfield = 0;
827         for my $subfield ($field->subfields()) {
828             if ((index $subfields, $$subfield[0]) >= 0) {
829                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
830                 $holding{'holding'} .= $$subfield[1];
831                 $havesubfield++;
832             }
833         }
834         if ($havesubfield) {
835             push(@alternateholdingsinfo, \%holding);
836         }
837     }
838
839     $template->param(
840         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
841         );
842 }
843
844 # FIXME: The template uses this hash directly. Need to filter.
845 foreach ( keys %{$dat} ) {
846     next if ( $HideMARC->{$_} );
847     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
848 }
849
850 # some useful variables for enhanced content;
851 # in each case, we're grabbing the first value we find in
852 # the record and normalizing it
853 my $upc = GetNormalizedUPC($record,$marcflavour);
854 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
855 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
856 my $content_identifier_exists;
857 if ( $isbn or $ean or $oclc or $upc ) {
858     $content_identifier_exists = 1;
859 }
860 $template->param(
861         normalized_upc => $upc,
862         normalized_ean => $ean,
863         normalized_oclc => $oclc,
864         normalized_isbn => $isbn,
865         content_identifier_exists =>  $content_identifier_exists,
866 );
867
868 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
869 # COinS format FIXME: for books Only
870 my $coins = eval { $biblio->get_coins };
871 $template->param( ocoins => $coins );
872
873 my ( $loggedincommenter, $reviews );
874 if ( C4::Context->preference('OPACComments') ) {
875     $reviews = Koha::Reviews->search(
876         {
877             biblionumber => $biblionumber,
878             -or => { approved => 1, borrowernumber => $borrowernumber }
879         },
880         {
881             order_by => { -desc => 'datereviewed' }
882         }
883     )->unblessed;
884     my $libravatar_enabled = 0;
885     if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) {
886         eval {
887             require Libravatar::URL;
888             Libravatar::URL->import();
889         };
890         if ( !$@ ) {
891             $libravatar_enabled = 1;
892         }
893     }
894     for my $review (@$reviews) {
895         my $review_patron = Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar
896
897         # setting some borrower info into this hash
898         if ( $review_patron ) {
899             $review->{patron} = $review_patron;
900             if ( $libravatar_enabled and $review_patron->email ) {
901                 $review->{avatarurl} = libravatar_url( email => $review_patron->email, https => $ENV{HTTPS} );
902             }
903
904             if ( $review_patron->borrowernumber eq $borrowernumber ) {
905                 $loggedincommenter = 1;
906             }
907         }
908     }
909 }
910
911 if ( C4::Context->preference("OPACISBD") ) {
912     $template->param( ISBD => 1 );
913 }
914
915 $template->param(
916     itemloop            => \@itemloop,
917     otheritemloop       => \@otheritemloop,
918     biblionumber        => $biblionumber,
919     subscriptions       => \@subs,
920     subscriptionsnumber => $subscriptionsnumber,
921     reviews             => $reviews,
922     loggedincommenter   => $loggedincommenter
923 );
924
925 # Lists
926 if (C4::Context->preference("virtualshelves") ) {
927     my $shelves = Koha::Virtualshelves->search(
928         {
929             biblionumber => $biblionumber,
930             public       => 1,
931         },
932         {
933             join => 'virtualshelfcontents',
934         }
935     );
936     $template->param( shelves => $shelves );
937 }
938
939 # XISBN Stuff
940 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
941     eval {
942         $template->param(
943             XISBNS => scalar get_xisbns($isbn, $biblionumber)
944         );
945     };
946     if ($@) { warn "XISBN Failed $@"; }
947 }
948
949 # Serial Collection
950 my @sc_fields = $record->field(955);
951 my @lc_fields = $marcflavour eq 'UNIMARC'
952     ? $record->field(930)
953     : $record->field(852);
954 my @serialcollections = ();
955
956 foreach my $sc_field (@sc_fields) {
957     my %row_data;
958
959     $row_data{text}    = $sc_field->subfield('r');
960     $row_data{branch}  = $sc_field->subfield('9');
961     foreach my $lc_field (@lc_fields) {
962         $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
963             ? $lc_field->subfield('a') # 930$a
964             : $lc_field->subfield('h') # 852$h
965             if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
966     }
967
968     if ($row_data{text} && $row_data{branch}) { 
969         push (@serialcollections, \%row_data);
970     }
971 }
972
973 if (scalar(@serialcollections) > 0) {
974     $template->param(
975         serialcollection  => 1,
976         serialcollections => \@serialcollections);
977 }
978
979 # Local cover Images stuff
980 if (C4::Context->preference("OPACLocalCoverImages")){
981                 $template->param(OPACLocalCoverImages => 1);
982 }
983
984 # HTML5 Media
985 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
986     $template->param( C4::HTML5Media->gethtml5media($record));
987 }
988
989 my $syndetics_elements;
990
991 if ( C4::Context->preference("SyndeticsEnabled") ) {
992     $template->param("SyndeticsEnabled" => 1);
993     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
994         eval {
995             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
996             for my $element (values %$syndetics_elements) {
997                 $template->param("Syndetics$element"."Exists" => 1 );
998                 #warn "Exists: "."Syndetics$element"."Exists";
999         }
1000     };
1001     warn $@ if $@;
1002 }
1003
1004 if ( C4::Context->preference("SyndeticsEnabled")
1005         && C4::Context->preference("SyndeticsSummary")
1006         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
1007         eval {
1008             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
1009             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
1010         };
1011         warn $@ if $@;
1012
1013 }
1014
1015 if ( C4::Context->preference("SyndeticsEnabled")
1016         && C4::Context->preference("SyndeticsTOC")
1017         && exists($syndetics_elements->{'TOC'}) ) {
1018         eval {
1019     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
1020     $template->param( SYNDETICS_TOC => $syndetics_toc );
1021         };
1022         warn $@ if $@;
1023 }
1024
1025 if ( C4::Context->preference("SyndeticsEnabled")
1026     && C4::Context->preference("SyndeticsExcerpt")
1027     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
1028     eval {
1029     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
1030     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
1031     };
1032         warn $@ if $@;
1033 }
1034
1035 if ( C4::Context->preference("SyndeticsEnabled")
1036     && C4::Context->preference("SyndeticsReviews")) {
1037     eval {
1038     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
1039     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
1040     };
1041         warn $@ if $@;
1042 }
1043
1044 if ( C4::Context->preference("SyndeticsEnabled")
1045     && C4::Context->preference("SyndeticsAuthorNotes")
1046         && exists($syndetics_elements->{'ANOTES'}) ) {
1047     eval {
1048     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
1049     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
1050     };
1051     warn $@ if $@;
1052 }
1053
1054 # LibraryThingForLibraries ID Code and Tabbed View Option
1055 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
1056
1057 $template->param(LibraryThingForLibrariesID =>
1058 C4::Context->preference('LibraryThingForLibrariesID') ); 
1059 $template->param(LibraryThingForLibrariesTabbedView =>
1060 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
1061
1062
1063 # Novelist Select
1064 if( C4::Context->preference('NovelistSelectEnabled') ) 
1065
1066 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
1067 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
1068 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
1069
1070
1071
1072 # Babelthèque
1073 if ( C4::Context->preference("Babeltheque") ) {
1074     $template->param( 
1075         Babeltheque => 1,
1076         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
1077     );
1078 }
1079
1080 # Social Networks
1081 if ( C4::Context->preference( "SocialNetworks" ) ) {
1082     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
1083     $template->param( SocialNetworks => 1 );
1084 }
1085
1086 # Shelf Browser Stuff
1087 if (C4::Context->preference("OPACShelfBrowser")) {
1088     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
1089     if (defined($starting_itemnumber)) {
1090         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
1091         my $nearby = GetNearbyItems($starting_itemnumber);
1092
1093         $template->param(
1094             starting_itemnumber => $starting_itemnumber,
1095             starting_homebranch => $nearby->{starting_homebranch}->{description},
1096             starting_location => $nearby->{starting_location}->{description},
1097             starting_ccode => $nearby->{starting_ccode}->{description},
1098             shelfbrowser_prev_item => $nearby->{prev_item},
1099             shelfbrowser_next_item => $nearby->{next_item},
1100             shelfbrowser_items => $nearby->{items},
1101         );
1102
1103         # in which tab shelf browser should open ?
1104         if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) {
1105             $template->param(shelfbrowser_tab => 'holdings');
1106         } else {
1107             $template->param(shelfbrowser_tab => 'otherholdings');
1108         }
1109     }
1110 }
1111
1112 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
1113
1114 if (C4::Context->preference("BakerTaylorEnabled")) {
1115         $template->param(
1116                 BakerTaylorEnabled  => 1,
1117                 BakerTaylorImageURL => &image_url(),
1118                 BakerTaylorLinkURL  => &link_url(),
1119                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
1120         );
1121         my ($bt_user, $bt_pass);
1122         if ($isbn and
1123                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
1124                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
1125         {
1126                 $template->param(
1127                 BakerTaylorContentURL   =>
1128         sprintf("https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
1129                                 $bt_user,$bt_pass,$isbn)
1130                 );
1131         }
1132 }
1133
1134 my $tag_quantity;
1135 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
1136         $template->param(
1137                 TagsEnabled => 1,
1138                 TagsShowOnDetail => $tag_quantity,
1139                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
1140         );
1141         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
1142                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
1143 }
1144
1145 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
1146     # These values are going to be read by Javascript, at least in the case
1147     # of the google covers
1148     $template->param(covernewwindow => 'true');
1149 } else {
1150     $template->param(covernewwindow => 'false');
1151 }
1152
1153 $template->param(borrowernumber => $borrowernumber);
1154
1155 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
1156     my $ratings = Koha::Ratings->search({ biblionumber => $biblionumber });
1157     my $my_rating = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
1158     $template->param(
1159         ratings => $ratings,
1160         my_rating => $my_rating,
1161     );
1162 }
1163
1164 #Search for title in links
1165 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
1166 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1167 my $issn = $marcissns->[0] || '';
1168
1169 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1170     $dat->{title} =~ s/\/+$//; # remove trailing slash
1171     $dat->{title} =~ s/\s+$//; # remove trailing space
1172     $search_for_title = parametrized_url(
1173         $search_for_title,
1174         {
1175             TITLE         => $dat->{title},
1176             AUTHOR        => $dat->{author},
1177             ISBN          => $isbn,
1178             ISSN          => $issn,
1179             CONTROLNUMBER => $marccontrolnumber,
1180             BIBLIONUMBER  => $biblionumber,
1181         }
1182     );
1183     $template->param('OPACSearchForTitleIn' => $search_for_title);
1184 }
1185
1186 #IDREF
1187 if ( C4::Context->preference("IDREF") ) {
1188     # If the record comes from the SUDOC
1189     if ( $record->field('009') ) {
1190         my $unimarc3 = $record->field("009")->data;
1191         if ( $unimarc3 =~ /^\d+$/ ) {
1192             $template->param(
1193                 IDREF => 1,
1194             );
1195         }
1196     }
1197 }
1198
1199 # We try to select the best default tab to show, according to what
1200 # the user wants, and what's available for display
1201 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1202 my $defaulttab = 
1203     $viewallitems
1204         ? 'holdings' :
1205     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1206         ? 'subscriptions' :
1207     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1208         ? 'serialcollection' :
1209     $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1210         ? 'holdings' :
1211     ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar (@itemloop) == 0 && $parts
1212         ? 'components' :
1213     scalar (@itemloop) == 0
1214         ? 'media' :
1215     $subscriptionsnumber
1216         ? 'subscriptions' :
1217     @serialcollections > 0 
1218         ? 'serialcollection' : 'subscriptions';
1219 $template->param('defaulttab' => $defaulttab);
1220
1221 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1222     $template->param( localimages => $biblio->cover_images );
1223 }
1224
1225 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1226
1227 if (C4::Context->preference('OpacHighlightedWords')) {
1228     $template->{VARS}->{query_desc} = $query->param('query_desc');
1229 }
1230 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1231
1232 if ( C4::Context->preference('UseCourseReserves') ) {
1233     foreach my $i ( @items ) {
1234         $i->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $i->{'itemnumber'} );
1235     }
1236 }
1237
1238 $template->param(
1239     'OpacLocationBranchToDisplay' => C4::Context->preference('OpacLocationBranchToDisplay'),
1240 );
1241
1242 output_html_with_http_headers $query, $cookie, $template->output;