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