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