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