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