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