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