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