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