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