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