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