Bug 29697: Special case - opac not needed
[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( GetHiddenItemnumbers 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 @hiddenitems;
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         push @hiddenitems,
132           GetHiddenItemnumbers( { items => \@all_items, borcat => $patron ? $patron->categorycode : undef } );
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             'category'  => ($patron) ? $patron->categorycode : q{}
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 my $hideitems;
522 $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
523
524 # Hide items
525 if ($hideitems) {
526     for my $itm (@all_items) {
527         if  ( C4::Context->preference('hidelostitems') ) {
528             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
529         } else {
530             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
531     }
532 }
533 } else {
534     # Or not
535     @items = @all_items;
536 }
537
538 my $dat = &GetBiblioData($biblionumber);
539 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
540     {
541         frameworkcode => $dat->{'frameworkcode'},
542         interface     => 'opac',
543     } );
544
545 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
546 # imageurl:
547 my $itemtype = $dat->{'itemtype'};
548 if ( $itemtype ) {
549     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
550     $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
551 }
552
553 my $shelflocations =
554   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
555 my $collections =
556   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
557 my $copynumbers =
558   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
559
560 #coping with subscriptions
561 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
562 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
563
564 my @subs;
565 $dat->{'serial'}=1 if $subscriptionsnumber;
566 foreach my $subscription (@subscriptions) {
567     my $serials_to_display;
568     my %cell;
569     $cell{subscriptionid}    = $subscription->{subscriptionid};
570     $cell{subscriptionnotes} = $subscription->{notes};
571     $cell{missinglist}       = $subscription->{missinglist};
572     $cell{opacnote}          = $subscription->{opacnote};
573     $cell{histstartdate}     = $subscription->{histstartdate};
574     $cell{histenddate}       = $subscription->{histenddate};
575     $cell{branchcode}        = $subscription->{branchcode};
576     $cell{callnumber}        = $subscription->{callnumber};
577     $cell{location}          = $subscription->{location};
578     $cell{closed}            = $subscription->{closed};
579     $cell{letter}            = $subscription->{letter};
580     $cell{biblionumber}      = $subscription->{biblionumber};
581     #get the three latest serials.
582     $serials_to_display = $subscription->{opacdisplaycount};
583     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
584         $cell{opacdisplaycount} = $serials_to_display;
585     $cell{latestserials} =
586       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
587     if ( $borrowernumber ) {
588         my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} );
589         my $subscriber = $subscription_object->subscribers->find( $borrowernumber );
590         $cell{hasalert} = 1 if $subscriber;
591     }
592     push @subs, \%cell;
593 }
594
595 $dat->{'count'} = scalar(@items);
596
597
598 my (%item_reserves, %priority);
599 my ($show_holds_count, $show_priority);
600 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
601     m/holds/o and $show_holds_count = 1;
602     m/priority/ and $show_priority = 1;
603 }
604 my $has_hold;
605 if ( $show_holds_count || $show_priority) {
606     my $holds = $biblio->holds;
607     $template->param( holds_count  => $holds->count );
608     while ( my $hold = $holds->next ) {
609         $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber;
610         if ($show_priority && $hold->borrowernumber == $borrowernumber) {
611             $has_hold = 1;
612             $hold->itemnumber
613                 ? ($priority{ $hold->itemnumber } = $hold->priority)
614                 : ($template->param( priority => $hold->priority ));
615         }
616     }
617 }
618 $template->param( show_priority => $has_hold ) ;
619
620 my %itemfields;
621 my (@itemloop, @otheritemloop);
622 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
623 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
624     $template->param(SeparateHoldings => 1);
625 }
626 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
627 my $viewallitems = $query->param('viewallitems');
628 my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50;
629
630 # Get component parts details
631 my $showcomp = C4::Context->preference('ShowComponentRecords');
632 my ( $parts, $show_analytics );
633 if ( $showcomp eq 'both' || $showcomp eq 'opac' ) {
634     if ( my $components = $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) ) {
635         $show_analytics = 1 if @{$components}; # just show link when having results
636         for my $part ( @{$components} ) {
637             $part = C4::Search::new_record_from_zebra( 'biblioserver', $part );
638             my $id = Koha::SearchEngine::Search::extract_biblionumber( $part );
639
640             push @{$parts},
641               XSLTParse4Display(
642                 {
643                     biblionumber => $id,
644                     record       => $part,
645                     xsl_syspref  => 'OPACXSLTResultsDisplay',
646                     fix_amps     => 1,
647                 }
648               );
649         }
650         $template->param( ComponentParts => $parts );
651         my ( $comp_query, $comp_sort ) = $biblio->get_components_query;
652         my $cpq = $comp_query . "&sort_by=" . $comp_sort;
653         $template->param( ComponentPartsQuery => $cpq );
654     }
655 } else { # check if we should show analytics anyway
656     $show_analytics = 1 if @{$biblio->get_marc_components(1)}; # count matters here, results does not
657 }
658
659 # XSLT processing of some stuff
660 my $variables = {};
661 my @plugin_responses = Koha::Plugins->call(
662     'opac_detail_xslt_variables',
663     {
664         biblio_id => $biblionumber,
665         lang      => C4::Languages::getlanguage(),
666         patron_id => $borrowernumber,
667     },
668 );
669 for my $plugin_variables ( @plugin_responses ) {
670     $variables = { %$variables, %$plugin_variables };
671 }
672 $variables->{anonymous_session} = $borrowernumber ? 0 : 1;
673 $variables->{show_analytics_link} = $show_analytics;
674 $template->param(
675     XSLTBloc => XSLTParse4Display({
676         biblionumber   => $biblionumber,
677         record         => $record,
678         xsl_syspref    => 'OPACXSLTDetailsDisplay',
679         fix_amps       => 1,
680         xslt_variables => $variables,
681     }),
682 );
683
684 # Get items on order
685 my ( @itemnumbers_on_order );
686 if ( C4::Context->preference('OPACAcquisitionDetails' ) ) {
687     my $orders = C4::Acquisition::SearchOrders({
688         biblionumber => $biblionumber,
689         ordered => 1,
690     });
691     my $total_quantity = 0;
692     for my $order ( @$orders ) {
693         my $order = Koha::Acquisition::Orders->find( $order->{ordernumber} );
694         my $basket = $order->basket;
695         if ( $basket->effective_create_items eq 'ordering' ) {
696             @itemnumbers_on_order = $order->items->get_column('itemnumber');
697         }
698         $total_quantity += $order->quantity;
699     }
700     $template->{VARS}->{acquisition_details} = {
701         total_quantity => $total_quantity,
702     };
703 }
704
705 my $allow_onshelf_holds;
706 my ( $itemloop_has_images, $otheritemloop_has_images );
707 if ( not $viewallitems and @items > $max_items_to_display ) {
708     $template->param(
709         too_many_items => 1,
710         items_count => scalar( @items ),
711     );
712 } else {
713   for my $itm (@items) {
714     my $item = Koha::Items->find( $itm->{itemnumber} );
715     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
716     $itm->{priority} = $priority{ $itm->{itemnumber} };
717
718     $allow_onshelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } )
719       unless $allow_onshelf_holds;
720
721     # get collection code description, too
722     my $ccode = $itm->{'ccode'};
723     $itm->{'ccode'} = $collections->{$ccode} if defined($ccode) && $collections && exists( $collections->{$ccode} );
724     my $copynumber = $itm->{'copynumber'};
725     $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
726     if ( defined $itm->{'location'} ) {
727         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
728     }
729     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
730         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
731         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{translated_description};
732     }
733     foreach (qw(ccode materials enumchron copynumber itemnotes location_description uri)) {
734         $itemfields{$_} = 1 if ($itm->{$_});
735     }
736
737     my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
738     if ( $reserve_status eq "Waiting" )  { $itm->{'waiting'} = 1; }
739     if ( $reserve_status eq "Reserved" ) { $itm->{'onhold'}  = 1; }
740
741     if ( C4::Context->preference('UseRecalls') ) {
742         my $pending_recall_count = Koha::Recalls->search(
743             {
744                 item_id   => $itm->{itemnumber},
745                 status    => 'waiting',
746             }
747         )->count;
748         if ( $pending_recall_count ) { $itm->{has_pending_recall} = 1; }
749     }
750
751      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
752      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
753         $itm->{transfertwhen} = $transfertwhen;
754         $itm->{transfertfrom} = $transfertfrom;
755         $itm->{transfertto}   = $transfertto;
756      }
757
758     if ( C4::Context->preference('OPACAcquisitionDetails') ) {
759         $itm->{on_order} = 1
760           if grep { $_ eq $itm->{itemnumber} } @itemnumbers_on_order;
761     }
762
763     if ( C4::Context->preference("OPACLocalCoverImages") == 1 ) {
764         $itm->{cover_images} = $item->cover_images;
765     }
766
767     if ( $item->in_bundle ) {
768         my $host = $item->bundle_host;
769         $itm->{bundle_host} = $host;
770     }
771
772     my $itembranch = $itm->{$separatebranch};
773     if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
774         if ($itembranch and $itembranch eq $currentbranch) {
775             push @itemloop, $itm;
776             $itemloop_has_images++ if $item->cover_images->count;
777         } else {
778             push @otheritemloop, $itm;
779             $otheritemloop_has_images++ if $item->cover_images->count;
780         }
781     } else {
782         push @itemloop, $itm;
783         $itemloop_has_images++ if $item->cover_images->count;
784     }
785   }
786 }
787
788 if( $allow_onshelf_holds || CountItemsIssued($biblionumber) || $biblio->has_items_waiting_or_intransit ) {
789     $template->param( ReservableItems => 1 );
790 }
791
792 $template->param(
793     itemloop_has_images      => $itemloop_has_images,
794     otheritemloop_has_images => $otheritemloop_has_images,
795 );
796
797 # Display only one tab if one items list is empty
798 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
799     $template->param(SeparateHoldings => 0);
800     if (scalar(@itemloop) == 0) {
801         @itemloop = @otheritemloop;
802     }
803 }
804
805 my $marcnotesarray = $biblio->get_marc_notes({ opac => 1, record => $record });
806
807 if( C4::Context->preference('ArticleRequests') ) {
808     my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef;
809     my $itemtype = Koha::ItemTypes->find($biblio->itemtype);
810     my $artreqpossible = $patron
811         ? $biblio->can_article_request( $patron )
812         : $itemtype
813         ? $itemtype->may_article_request
814         : q{};
815     $template->param( artreqpossible => $artreqpossible );
816 }
817
818 my $norequests = ! $biblio->items->filter_by_for_hold->count;
819     $template->param(
820                      MARCNOTES               => $marcnotesarray,
821                      norequests              => $norequests,
822                      itemdata_ccode          => $itemfields{ccode},
823                      itemdata_materials      => $itemfields{materials},
824                      itemdata_enumchron      => $itemfields{enumchron},
825                      itemdata_uri            => $itemfields{uri},
826                      itemdata_copynumber     => $itemfields{copynumber},
827                      itemdata_itemnotes      => $itemfields{itemnotes},
828                      itemdata_location       => $itemfields{location_description},
829                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
830     );
831
832 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
833     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
834     my $subfields = substr $fieldspec, 3;
835     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
836     my @alternateholdingsinfo = ();
837     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
838
839     for my $field (@holdingsfields) {
840         my %holding = ( holding => '' );
841         my $havesubfield = 0;
842         for my $subfield ($field->subfields()) {
843             if ((index $subfields, $$subfield[0]) >= 0) {
844                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
845                 $holding{'holding'} .= $$subfield[1];
846                 $havesubfield++;
847             }
848         }
849         if ($havesubfield) {
850             push(@alternateholdingsinfo, \%holding);
851         }
852     }
853
854     $template->param(
855         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
856         );
857 }
858
859 # FIXME: The template uses this hash directly. Need to filter.
860 foreach ( keys %{$dat} ) {
861     next if ( $HideMARC->{$_} );
862     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
863 }
864
865 # some useful variables for enhanced content;
866 # in each case, we're grabbing the first value we find in
867 # the record and normalizing it
868 my $upc = GetNormalizedUPC($record,$marcflavour);
869 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
870 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
871 my $content_identifier_exists;
872 if ( $isbn or $ean or $oclc or $upc ) {
873     $content_identifier_exists = 1;
874 }
875 $template->param(
876         normalized_upc => $upc,
877         normalized_ean => $ean,
878         normalized_oclc => $oclc,
879         normalized_isbn => $isbn,
880         content_identifier_exists =>  $content_identifier_exists,
881 );
882
883 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
884 # COinS format FIXME: for books Only
885 my $coins = eval { $biblio->get_coins };
886 $template->param( ocoins => $coins );
887
888 my ( $loggedincommenter, $reviews );
889 if ( C4::Context->preference('OPACComments') ) {
890     $reviews = Koha::Reviews->search(
891         {
892             biblionumber => $biblionumber,
893             -or => { approved => 1, borrowernumber => $borrowernumber }
894         },
895         {
896             order_by => { -desc => 'datereviewed' }
897         }
898     )->unblessed;
899     my $libravatar_enabled = 0;
900     if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) {
901         eval {
902             require Libravatar::URL;
903             Libravatar::URL->import();
904         };
905         if ( !$@ ) {
906             $libravatar_enabled = 1;
907         }
908     }
909     for my $review (@$reviews) {
910         my $review_patron = Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar
911
912         # setting some borrower info into this hash
913         if ( $review_patron ) {
914             $review->{patron} = $review_patron;
915             if ( $libravatar_enabled and $review_patron->email ) {
916                 $review->{avatarurl} = libravatar_url( email => $review_patron->email, https => $ENV{HTTPS} );
917             }
918
919             if ( $review_patron->borrowernumber eq $borrowernumber ) {
920                 $loggedincommenter = 1;
921             }
922         }
923     }
924 }
925
926 if ( C4::Context->preference("OPACISBD") ) {
927     $template->param( ISBD => 1 );
928 }
929
930 $template->param(
931     itemloop            => \@itemloop,
932     otheritemloop       => \@otheritemloop,
933     biblionumber        => $biblionumber,
934     subscriptions       => \@subs,
935     subscriptionsnumber => $subscriptionsnumber,
936     reviews             => $reviews,
937     loggedincommenter   => $loggedincommenter
938 );
939
940 # Lists
941 if (C4::Context->preference("virtualshelves") ) {
942     my $shelves = Koha::Virtualshelves->search(
943         {
944             biblionumber => $biblionumber,
945             public       => 1,
946         },
947         {
948             join => 'virtualshelfcontents',
949         }
950     );
951     $template->param( shelves => $shelves );
952 }
953
954 # XISBN Stuff
955 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
956     eval {
957         $template->param(
958             XISBNS => scalar get_xisbns($isbn, $biblionumber)
959         );
960     };
961     if ($@) { warn "XISBN Failed $@"; }
962 }
963
964 # Serial Collection
965 my @sc_fields = $record->field(955);
966 my @lc_fields = $marcflavour eq 'UNIMARC'
967     ? $record->field(930)
968     : $record->field(852);
969 my @serialcollections = ();
970
971 foreach my $sc_field (@sc_fields) {
972     my %row_data;
973
974     $row_data{text}    = $sc_field->subfield('r');
975     $row_data{branch}  = $sc_field->subfield('9');
976     foreach my $lc_field (@lc_fields) {
977         $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
978             ? $lc_field->subfield('a') # 930$a
979             : $lc_field->subfield('h') # 852$h
980             if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
981     }
982
983     if ($row_data{text} && $row_data{branch}) { 
984         push (@serialcollections, \%row_data);
985     }
986 }
987
988 if (scalar(@serialcollections) > 0) {
989     $template->param(
990         serialcollection  => 1,
991         serialcollections => \@serialcollections);
992 }
993
994 # Local cover Images stuff
995 if (C4::Context->preference("OPACLocalCoverImages")){
996                 $template->param(OPACLocalCoverImages => 1);
997 }
998
999 # HTML5 Media
1000 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
1001     $template->param( C4::HTML5Media->gethtml5media($record));
1002 }
1003
1004 my $syndetics_elements;
1005
1006 if ( C4::Context->preference("SyndeticsEnabled") ) {
1007     $template->param("SyndeticsEnabled" => 1);
1008     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
1009         eval {
1010             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
1011             for my $element (values %$syndetics_elements) {
1012                 $template->param("Syndetics$element"."Exists" => 1 );
1013                 #warn "Exists: "."Syndetics$element"."Exists";
1014         }
1015     };
1016     warn $@ if $@;
1017 }
1018
1019 if ( C4::Context->preference("SyndeticsEnabled")
1020         && C4::Context->preference("SyndeticsSummary")
1021         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
1022         eval {
1023             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
1024             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
1025         };
1026         warn $@ if $@;
1027
1028 }
1029
1030 if ( C4::Context->preference("SyndeticsEnabled")
1031         && C4::Context->preference("SyndeticsTOC")
1032         && exists($syndetics_elements->{'TOC'}) ) {
1033         eval {
1034     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
1035     $template->param( SYNDETICS_TOC => $syndetics_toc );
1036         };
1037         warn $@ if $@;
1038 }
1039
1040 if ( C4::Context->preference("SyndeticsEnabled")
1041     && C4::Context->preference("SyndeticsExcerpt")
1042     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
1043     eval {
1044     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
1045     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
1046     };
1047         warn $@ if $@;
1048 }
1049
1050 if ( C4::Context->preference("SyndeticsEnabled")
1051     && C4::Context->preference("SyndeticsReviews")) {
1052     eval {
1053     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
1054     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
1055     };
1056         warn $@ if $@;
1057 }
1058
1059 if ( C4::Context->preference("SyndeticsEnabled")
1060     && C4::Context->preference("SyndeticsAuthorNotes")
1061         && exists($syndetics_elements->{'ANOTES'}) ) {
1062     eval {
1063     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
1064     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
1065     };
1066     warn $@ if $@;
1067 }
1068
1069 # LibraryThingForLibraries ID Code and Tabbed View Option
1070 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
1071
1072 $template->param(LibraryThingForLibrariesID =>
1073 C4::Context->preference('LibraryThingForLibrariesID') ); 
1074 $template->param(LibraryThingForLibrariesTabbedView =>
1075 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
1076
1077
1078 # Novelist Select
1079 if( C4::Context->preference('NovelistSelectEnabled') ) 
1080
1081 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
1082 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
1083 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
1084
1085
1086
1087 # Babelthèque
1088 if ( C4::Context->preference("Babeltheque") ) {
1089     $template->param( 
1090         Babeltheque => 1,
1091         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
1092     );
1093 }
1094
1095 # Social Networks
1096 if ( C4::Context->preference( "SocialNetworks" ) ) {
1097     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
1098     $template->param( SocialNetworks => 1 );
1099 }
1100
1101 # Shelf Browser Stuff
1102 if (C4::Context->preference("OPACShelfBrowser")) {
1103     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
1104     if (defined($starting_itemnumber)) {
1105         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
1106         my $nearby = GetNearbyItems($starting_itemnumber);
1107
1108         $template->param(
1109             starting_itemnumber => $starting_itemnumber,
1110             starting_homebranch => $nearby->{starting_homebranch}->{description},
1111             starting_location => $nearby->{starting_location}->{description},
1112             starting_ccode => $nearby->{starting_ccode}->{description},
1113             shelfbrowser_prev_item => $nearby->{prev_item},
1114             shelfbrowser_next_item => $nearby->{next_item},
1115             shelfbrowser_items => $nearby->{items},
1116         );
1117
1118         # in which tab shelf browser should open ?
1119         if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) {
1120             $template->param(shelfbrowser_tab => 'holdings');
1121         } else {
1122             $template->param(shelfbrowser_tab => 'otherholdings');
1123         }
1124     }
1125 }
1126
1127 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
1128
1129 if (C4::Context->preference("BakerTaylorEnabled")) {
1130         $template->param(
1131                 BakerTaylorEnabled  => 1,
1132                 BakerTaylorImageURL => &image_url(),
1133                 BakerTaylorLinkURL  => &link_url(),
1134                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
1135         );
1136         my ($bt_user, $bt_pass);
1137         if ($isbn and
1138                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
1139                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
1140         {
1141                 $template->param(
1142                 BakerTaylorContentURL   =>
1143         sprintf("https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
1144                                 $bt_user,$bt_pass,$isbn)
1145                 );
1146         }
1147 }
1148
1149 my $tag_quantity;
1150 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
1151         $template->param(
1152                 TagsEnabled => 1,
1153                 TagsShowOnDetail => $tag_quantity,
1154                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
1155         );
1156         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
1157                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
1158 }
1159
1160 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
1161     # These values are going to be read by Javascript, at least in the case
1162     # of the google covers
1163     $template->param(covernewwindow => 'true');
1164 } else {
1165     $template->param(covernewwindow => 'false');
1166 }
1167
1168 $template->param(borrowernumber => $borrowernumber);
1169
1170 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
1171     my $ratings = Koha::Ratings->search({ biblionumber => $biblionumber });
1172     my $my_rating = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
1173     $template->param(
1174         ratings => $ratings,
1175         my_rating => $my_rating,
1176     );
1177 }
1178
1179 #Search for title in links
1180 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
1181 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1182 my $issn = $marcissns->[0] || '';
1183
1184 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1185     $dat->{title} =~ s/\/+$//; # remove trailing slash
1186     $dat->{title} =~ s/\s+$//; # remove trailing space
1187     my $oclc_no = Koha::Util::MARC::oclc_number( $record );
1188     $search_for_title = parametrized_url(
1189         $search_for_title,
1190         {
1191             TITLE         => $dat->{title},
1192             AUTHOR        => $dat->{author},
1193             ISBN          => $isbn,
1194             ISSN          => $issn,
1195             CONTROLNUMBER => $marccontrolnumber,
1196             BIBLIONUMBER  => $biblionumber,
1197             OCLC_NO       => $oclc_no,
1198         }
1199     );
1200     $template->param('OPACSearchForTitleIn' => $search_for_title);
1201 }
1202
1203 #IDREF
1204 if ( C4::Context->preference("IDREF") ) {
1205     # If the record comes from the SUDOC
1206     if ( $record->field('009') ) {
1207         my $unimarc3 = $record->field("009")->data;
1208         if ( $unimarc3 =~ /^\d+$/ ) {
1209             $template->param(
1210                 IDREF => 1,
1211             );
1212         }
1213     }
1214 }
1215
1216 # We try to select the best default tab to show, according to what
1217 # the user wants, and what's available for display
1218 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1219 my $defaulttab = 
1220     $viewallitems
1221         ? 'holdings' :
1222     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1223         ? 'subscriptions' :
1224     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1225         ? 'serialcollection' :
1226     $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1227         ? 'holdings' :
1228     ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar (@itemloop) == 0 && $parts
1229         ? 'components' :
1230     scalar (@itemloop) == 0
1231         ? 'media' :
1232     $subscriptionsnumber
1233         ? 'subscriptions' :
1234     @serialcollections > 0 
1235         ? 'serialcollection' : 'subscriptions';
1236 $template->param('defaulttab' => $defaulttab);
1237
1238 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1239     $template->param( localimages => $biblio->cover_images );
1240 }
1241
1242 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1243
1244 if (C4::Context->preference('OpacHighlightedWords')) {
1245     $template->{VARS}->{query_desc} = $query->param('query_desc');
1246 }
1247 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1248
1249 if ( C4::Context->preference('UseCourseReserves') ) {
1250     foreach my $i ( @items ) {
1251         $i->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $i->{'itemnumber'} );
1252     }
1253 }
1254
1255 $template->param(
1256     'OpacLocationBranchToDisplay' => C4::Context->preference('OpacLocationBranchToDisplay'),
1257 );
1258
1259 output_html_with_http_headers $query, $cookie, $template->output;