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