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