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