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