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