Bug 19301: (QA follow-up) Add POD, use statements and correct typo
[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
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                     $pasarParams .= '&amp;' if ($j);
204                     $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value));
205                     $j++;
206                 }
207             }
208         }
209         return $pasarParams;
210     }#rebuildBuscParam
211
212     # Search given the current values from the busc param
213     sub searchAgain
214     {
215         my ($arrParamsBusc, $offset, $results_per_page) = @_;
216
217         my $expanded_facet = $arrParamsBusc->{'expand'};
218         my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
219         my @servers;
220         @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
221         @servers = ("biblioserver") unless (@servers);
222
223         my ($default_sort_by, @sort_by);
224         $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
225         @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
226         $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
227         my ($error, $results_hashref, $facets);
228         eval {
229             ($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'});
230         };
231         my $hits;
232         my @newresults;
233         for (my $i=0;$i<@servers;$i++) {
234             my $server = $servers[$i];
235             $hits = $results_hashref->{$server}->{"hits"};
236             @newresults = searchResults('opac', '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
237         }
238         return \@newresults;
239     }#searchAgain
240
241     # Build the current list of biblionumbers in this search
242     sub buildListBiblios
243     {
244         my ($newresultsRef, $results_per_page) = @_;
245
246         my $listBiblios = '';
247         my $j = 0;
248         foreach (@$newresultsRef) {
249             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
250             $listBiblios .= $bibnum . ',';
251             $j++;
252             last if ($j == $results_per_page);
253         }
254         chop $listBiblios if ($listBiblios =~ /,$/);
255         return $listBiblios;
256     }#buildListBiblios
257
258     my $busc = $session->param("busc");
259     my @arrBusc = split(/\&(?:amp;)?/, $busc);
260     my ($key, $value);
261     my %arrParamsBusc = ();
262     for (@arrBusc) {
263         ($key, $value) = split(/=/, $_, 2);
264         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
265             $arrParamsBusc{$key} = uri_unescape($value);
266         } else {
267             unless (exists($arrParamsBusc{$key})) {
268                 $arrParamsBusc{$key} = [];
269             }
270             push @{$arrParamsBusc{$key}}, uri_unescape($value);
271         }
272     }
273     my $searchAgain = 0;
274     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
275     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
276     $arrParamsBusc{'count'} = $results_per_page;
277     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
278     # The value OPACnumSearchResults has changed and the search has to be rebuild
279     if ($count != $results_per_page) {
280         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
281             my $indexBiblio = 0;
282             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
283             for (@arrBibliosAux) {
284                 last if ($_ == $biblionumber);
285                 $indexBiblio++;
286             }
287             $indexBiblio += $offset;
288             $offset = int($indexBiblio / $count) * $count;
289             $arrParamsBusc{'offset'} = $offset;
290         }
291         $arrParamsBusc{'count'} = $count;
292         $results_per_page = $count;
293         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
294         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
295         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
296         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
297         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
298         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
299         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
300         $session->param("busc" => $newbusc);
301         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
302     } else {
303         my $modifyListBiblios = 0;
304         # We come from a previous click
305         if (exists($arrParamsBusc{'previous'})) {
306             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
307             delete $arrParamsBusc{'previous'};
308         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
309             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
310             delete $arrParamsBusc{'next'};
311         }
312         if ($modifyListBiblios) {
313             if (exists($arrParamsBusc{'newlistBiblios'})) {
314                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
315                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
316                 my @arrAux = split(',', $listBibliosAux);
317                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
318                 if ($modifyListBiblios == 1) {
319                     $arrParamsBusc{'next'} = $arrAux[0];
320                     $paging{'next'}->{biblionumber} = $arrAux[0];
321                 }else {
322                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
323                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
324                 }
325             } else {
326                 delete $arrParamsBusc{'listBiblios'};
327             }
328             my $offsetAux = $arrParamsBusc{'offset'};
329             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
330             $arrParamsBusc{'offsetSearch'} = $offsetAux;
331             $offset = $arrParamsBusc{'offset'};
332             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
333             $session->param("busc" => $newbusc);
334             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
335         }
336     }
337     my $buscParam = '';
338     my $j = 0;
339     # Rebuild the query for the button "back to results"
340     for (@arrBusc) {
341         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
342             $buscParam .= '&amp;' unless ($j == 0);
343             $buscParam .= $_; # string already URI encoded
344             $j++;
345         }
346     }
347     $template->param('busc' => $buscParam);
348     my $offsetSearch;
349     my @arrBiblios;
350     # We are inside the list of biblios and we don't have to search
351     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
352         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
353         if (@arrBiblios) {
354             # We are at the first item of the list
355             if ($arrBiblios[0] == $biblionumber) {
356                 if (@arrBiblios > 1) {
357                     for (my $j = 1; $j < @arrBiblios; $j++) {
358                         next unless ($arrBiblios[$j]);
359                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
360                         last;
361                     }
362                 }
363                 # search again if we are not at the first searching list
364                 if ($offset && !$arrParamsBusc{'previous'}) {
365                     $searchAgain = 1;
366                     $offsetSearch = $offset - $results_per_page;
367                 }
368             # we are at the last item of the list
369             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
370                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
371                     next unless ($arrBiblios[$j]);
372                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
373                     last;
374                 }
375                 if (!$offset) {
376                     # search again if we are at the first list and there is more results
377                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
378                 } else {
379                     # search again if we aren't at the first list and there is more results
380                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
381                 }
382                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
383             } else {
384                 for (my $j = 1; $j < $#arrBiblios; $j++) {
385                     if ($arrBiblios[$j] == $biblionumber) {
386                         for (my $z = $j - 1; $z >= 0; $z--) {
387                             next unless ($arrBiblios[$z]);
388                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
389                             last;
390                         }
391                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
392                             next unless ($arrBiblios[$z]);
393                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
394                             last;
395                         }
396                         last;
397                     }
398                 }
399             }
400         }
401         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
402     }
403     if ($searchAgain) {
404         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
405         my @newresults = @$newresultsRef;
406         # build the new listBiblios
407         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
408         unless (exists($arrParamsBusc{'listBiblios'})) {
409             $arrParamsBusc{'listBiblios'} = $listBiblios;
410             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
411         } else {
412             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
413         }
414         # From the new list we build again the next and previous result
415         if (@arrBiblios) {
416             if ($arrBiblios[0] == $biblionumber) {
417                 for (my $j = $#newresults; $j >= 0; $j--) {
418                     next unless ($newresults[$j]);
419                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
420                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
421                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
422                    last;
423                 }
424             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
425                 for (my $j = 0; $j < @newresults; $j++) {
426                     next unless ($newresults[$j]);
427                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
428                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
429                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
430                     last;
431                 }
432             }
433         }
434         # build new busc param
435         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
436         $session->param("busc" => $newbusc);
437     }
438     my ($numberBiblioPaging, $dataBiblioPaging);
439     # Previous biblio
440     $numberBiblioPaging = $paging{'previous'}->{biblionumber};
441     if ($numberBiblioPaging) {
442         $template->param( 'previousBiblionumber' => $numberBiblioPaging );
443         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
444         $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
445     }
446     # Next biblio
447     $numberBiblioPaging = $paging{'next'}->{biblionumber};
448     if ($numberBiblioPaging) {
449         $template->param( 'nextBiblionumber' => $numberBiblioPaging );
450         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
451         $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
452     }
453     # Partial list of biblio results
454     my @listResults;
455     for (my $j = 0; $j < @arrBiblios; $j++) {
456         next unless ($arrBiblios[$j]);
457         $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber);
458         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]};
459     }
460     $template->param('listResults' => \@listResults) if (@listResults);
461     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
462 }
463 }
464
465 $template->param(
466     OPACShowCheckoutName => C4::Context->preference("OPACShowCheckoutName"),
467 );
468
469 # adding items linked via host biblios
470
471 my $analyticfield = '773';
472 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
473     $analyticfield = '773';
474 } elsif ($marcflavour eq 'UNIMARC') {
475     $analyticfield = '461';
476 }
477 foreach my $hostfield ( $record->field($analyticfield)) {
478     my $hostbiblionumber = $hostfield->subfield("0");
479     my $linkeditemnumber = $hostfield->subfield("9");
480     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
481     foreach my $hostitemInfo (@hostitemInfos){
482         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
483             push(@all_items, $hostitemInfo);
484         }
485     }
486 }
487
488 my @items;
489
490 # Are there items to hide?
491 my $hideitems;
492 $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
493
494 # Hide items
495 if ($hideitems) {
496     for my $itm (@all_items) {
497         if  ( C4::Context->preference('hidelostitems') ) {
498             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
499         } else {
500             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
501     }
502 }
503 } else {
504     # Or not
505     @items = @all_items;
506 }
507
508 my $branch = '';
509 if (C4::Context->userenv){
510     $branch = C4::Context->userenv->{branch};
511 }
512 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
513     if (
514         ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
515         ||
516         C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
517     ) {
518         my $branchcode;
519         if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
520             $branchcode = $branch;
521         }
522         elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
523             $branchcode = $ENV{'BRANCHCODE'};
524         }
525
526         my @our_items;
527         my @other_items;
528
529         foreach my $item ( @items ) {
530            if ( $item->{branchcode} eq $branchcode ) {
531                $item->{'this_branch'} = 1;
532                push( @our_items, $item );
533            } else {
534                push( @other_items, $item );
535            }
536         }
537
538         @items = ( @our_items, @other_items );
539     }
540 }
541
542 my $dat = &GetBiblioData($biblionumber);
543 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
544     {
545         frameworkcode => $dat->{'frameworkcode'},
546         interface     => 'opac',
547     } );
548
549 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
550 # imageurl:
551 my $itemtype = $dat->{'itemtype'};
552 if ( $itemtype ) {
553     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
554     $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
555 }
556
557 my $shelflocations =
558   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
559 my $collections =
560   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
561 my $copynumbers =
562   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
563
564 #coping with subscriptions
565 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
566 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
567
568 my @subs;
569 $dat->{'serial'}=1 if $subscriptionsnumber;
570 foreach my $subscription (@subscriptions) {
571     my $serials_to_display;
572     my %cell;
573     $cell{subscriptionid}    = $subscription->{subscriptionid};
574     $cell{subscriptionnotes} = $subscription->{notes};
575     $cell{missinglist}       = $subscription->{missinglist};
576     $cell{opacnote}          = $subscription->{opacnote};
577     $cell{histstartdate}     = $subscription->{histstartdate};
578     $cell{histenddate}       = $subscription->{histenddate};
579     $cell{branchcode}        = $subscription->{branchcode};
580     $cell{callnumber}        = $subscription->{callnumber};
581     $cell{closed}            = $subscription->{closed};
582     $cell{letter}            = $subscription->{letter};
583     $cell{biblionumber}      = $subscription->{biblionumber};
584     #get the three latest serials.
585     $serials_to_display = $subscription->{opacdisplaycount};
586     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
587         $cell{opacdisplaycount} = $serials_to_display;
588     $cell{latestserials} =
589       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
590     if ( $borrowernumber ) {
591         my $sub = getalert($borrowernumber,'issue',$subscription->{subscriptionid});
592         if (@$sub[0]) {
593             $cell{hasalert} = 1;
594         }
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} );
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("http://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;