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