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