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