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