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