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