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