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