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