Bug 14385: Extend OpacHiddenItems to allow specifying exempt borrower categories
[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 = new CGI;
72 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
73     {
74         template_name   => "opac-detail.tt",
75         query           => $query,
76         type            => "opac",
77         authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
78     }
79 );
80
81 my $biblionumber = $query->param('biblionumber') || $query->param('bib') || 0;
82 $biblionumber = int($biblionumber);
83
84 my @all_items = GetItemsInfo($biblionumber);
85 my @hiddenitems;
86 if ( scalar @all_items >= 1 ) {
87     my $borcat;
88     if ( C4::Context->preference('OpacHiddenItemsExceptions') ) {
89
90         # we need to fetch the borrower info here, so we can pass the category
91         my $borrower = GetMember( borrowernumber => $borrowernumber );
92         $borcat = $borrower->{categorycode};
93     }
94
95     push @hiddenitems,
96       GetHiddenItemnumbers( { items => \@all_items, borcat => $borcat } );
97
98     if (scalar @hiddenitems == scalar @all_items ) {
99         print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
100         exit;
101     }
102 }
103
104 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
105 if ( ! $record ) {
106     print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
107     exit;
108 }
109
110 my $biblio = Koha::Biblios->find( $biblionumber );
111 my $framework = &GetFrameworkCode( $biblionumber );
112 my $record_processor = Koha::RecordProcessor->new({
113     filters => 'ViewPolicy',
114     options => {
115         interface => 'opac',
116         frameworkcode => $framework
117     }
118 });
119 $record_processor->process($record);
120
121 # redirect if opacsuppression is enabled and biblio is suppressed
122 if (C4::Context->preference('OpacSuppression')) {
123     # FIXME hardcoded; the suppression flag ought to be materialized
124     # as a column on biblio or the like
125     my $opacsuppressionfield = '942';
126     my $opacsuppressionfieldvalue = $record->field($opacsuppressionfield);
127     # redirect to opac-blocked info page or 404?
128     my $opacsuppressionredirect;
129     if ( C4::Context->preference("OpacSuppressionRedirect") ) {
130         $opacsuppressionredirect = "/cgi-bin/koha/opac-blocked.pl";
131     } else {
132         $opacsuppressionredirect = "/cgi-bin/koha/errors/404.pl";
133     }
134     if ( $opacsuppressionfieldvalue &&
135          $opacsuppressionfieldvalue->subfield("n") &&
136          $opacsuppressionfieldvalue->subfield("n") == 1) {
137         # if OPAC suppression by IP address
138         if (C4::Context->preference('OpacSuppressionByIPRange')) {
139             my $IPAddress = $ENV{'REMOTE_ADDR'};
140             my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
141             if ($IPAddress !~ /^$IPRange/)  {
142                 print $query->redirect($opacsuppressionredirect);
143                 exit;
144             }
145         } else {
146             print $query->redirect($opacsuppressionredirect);
147             exit;
148         }
149     }
150 }
151
152 $template->param( biblio => $biblio );
153
154 # get biblionumbers stored in the cart
155 my @cart_list;
156
157 if($query->cookie("bib_list")){
158     my $cart_list = $query->cookie("bib_list");
159     @cart_list = split(/\//, $cart_list);
160     if ( grep {$_ eq $biblionumber} @cart_list) {
161         $template->param( incart => 1 );
162     }
163 }
164
165
166 SetUTF8Flag($record);
167 my $marcflavour      = C4::Context->preference("marcflavour");
168 my $ean = GetNormalizedEAN( $record, $marcflavour );
169
170 # XSLT processing of some stuff
171 my $xslfile = C4::Context->preference('OPACXSLTDetailsDisplay');
172 my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
173 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
174
175 if ( $xslfile ) {
176     $template->param(
177         XSLTBloc => XSLTParse4Display(
178                         $biblionumber, $record, "OPACXSLTDetailsDisplay",
179                         1, undef, $sysxml, $xslfile, $lang
180                     )
181     );
182 }
183
184 my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults");
185
186 # We look for the busc param to build the simple paging from the search
187 if ($OpacBrowseResults) {
188 my $session = get_session($query->cookie("CGISESSID"));
189 my %paging = (previous => {}, next => {});
190 if ($session->param('busc')) {
191     use C4::Search;
192     use URI::Escape;
193
194     # Rebuild the string to store on session
195     # param value is URI encoded and params separator is HTML encode (&amp;)
196     sub rebuildBuscParam
197     {
198         my $arrParamsBusc = shift;
199
200         my $pasarParams = '';
201         my $j = 0;
202         for (keys %$arrParamsBusc) {
203             if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
204                 if (defined($arrParamsBusc->{$_})) {
205                     $pasarParams .= '&amp;' if ($j);
206                     $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} ));
207                     $j++;
208                 }
209             } else {
210                 for my $value (@{$arrParamsBusc->{$_}}) {
211                     next if !defined($value);
212                     $pasarParams .= '&amp;' if ($j);
213                     $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value));
214                     $j++;
215                 }
216             }
217         }
218         return $pasarParams;
219     }#rebuildBuscParam
220
221     # Search given the current values from the busc param
222     sub searchAgain
223     {
224         my ($arrParamsBusc, $offset, $results_per_page) = @_;
225
226         my $expanded_facet = $arrParamsBusc->{'expand'};
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,$expanded_facet,undef,$itemtypes,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'});
239         };
240         my $hits;
241         my @newresults;
242         for (my $i=0;$i<@servers;$i++) {
243             my $server = $servers[$i];
244             $hits = $results_hashref->{$server}->{"hits"};
245             @newresults = searchResults({ 'interface' => 'opac' }, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
246         }
247         return \@newresults;
248     }#searchAgain
249
250     # Build the current list of biblionumbers in this search
251     sub buildListBiblios
252     {
253         my ($newresultsRef, $results_per_page) = @_;
254
255         my $listBiblios = '';
256         my $j = 0;
257         foreach (@$newresultsRef) {
258             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
259             $listBiblios .= $bibnum . ',';
260             $j++;
261             last if ($j == $results_per_page);
262         }
263         chop $listBiblios if ($listBiblios =~ /,$/);
264         return $listBiblios;
265     }#buildListBiblios
266
267     my $busc = $session->param("busc");
268     my @arrBusc = split(/\&(?:amp;)?/, $busc);
269     my ($key, $value);
270     my %arrParamsBusc = ();
271     for (@arrBusc) {
272         ($key, $value) = split(/=/, $_, 2);
273         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
274             $arrParamsBusc{$key} = uri_unescape($value);
275         } else {
276             unless (exists($arrParamsBusc{$key})) {
277                 $arrParamsBusc{$key} = [];
278             }
279             push @{$arrParamsBusc{$key}}, uri_unescape($value);
280         }
281     }
282     my $searchAgain = 0;
283     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
284     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
285     $arrParamsBusc{'count'} = $results_per_page;
286     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
287     # The value OPACnumSearchResults has changed and the search has to be rebuild
288     if ($count != $results_per_page) {
289         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
290             my $indexBiblio = 0;
291             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
292             for (@arrBibliosAux) {
293                 last if ($_ == $biblionumber);
294                 $indexBiblio++;
295             }
296             $indexBiblio += $offset;
297             $offset = int($indexBiblio / $count) * $count;
298             $arrParamsBusc{'offset'} = $offset;
299         }
300         $arrParamsBusc{'count'} = $count;
301         $results_per_page = $count;
302         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
303         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
304         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
305         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
306         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
307         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
308         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
309         $session->param("busc" => $newbusc);
310         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
311     } else {
312         my $modifyListBiblios = 0;
313         # We come from a previous click
314         if (exists($arrParamsBusc{'previous'})) {
315             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
316             delete $arrParamsBusc{'previous'};
317         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
318             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
319             delete $arrParamsBusc{'next'};
320         }
321         if ($modifyListBiblios) {
322             if (exists($arrParamsBusc{'newlistBiblios'})) {
323                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
324                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
325                 my @arrAux = split(',', $listBibliosAux);
326                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
327                 if ($modifyListBiblios == 1) {
328                     $arrParamsBusc{'next'} = $arrAux[0];
329                     $paging{'next'}->{biblionumber} = $arrAux[0];
330                 }else {
331                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
332                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
333                 }
334             } else {
335                 delete $arrParamsBusc{'listBiblios'};
336             }
337             my $offsetAux = $arrParamsBusc{'offset'};
338             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
339             $arrParamsBusc{'offsetSearch'} = $offsetAux;
340             $offset = $arrParamsBusc{'offset'};
341             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
342             $session->param("busc" => $newbusc);
343             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
344         }
345     }
346     my $buscParam = '';
347     my $j = 0;
348     # Rebuild the query for the button "back to results"
349     for (@arrBusc) {
350         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
351             $buscParam .= '&amp;' unless ($j == 0);
352             $buscParam .= $_; # string already URI encoded
353             $j++;
354         }
355     }
356     $template->param('busc' => $buscParam);
357     my $offsetSearch;
358     my @arrBiblios;
359     # We are inside the list of biblios and we don't have to search
360     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
361         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
362         if (@arrBiblios) {
363             # We are at the first item of the list
364             if ($arrBiblios[0] == $biblionumber) {
365                 if (@arrBiblios > 1) {
366                     for (my $j = 1; $j < @arrBiblios; $j++) {
367                         next unless ($arrBiblios[$j]);
368                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
369                         last;
370                     }
371                 }
372                 # search again if we are not at the first searching list
373                 if ($offset && !$arrParamsBusc{'previous'}) {
374                     $searchAgain = 1;
375                     $offsetSearch = $offset - $results_per_page;
376                 }
377             # we are at the last item of the list
378             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
379                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
380                     next unless ($arrBiblios[$j]);
381                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
382                     last;
383                 }
384                 if (!$offset) {
385                     # search again if we are at the first list and there is more results
386                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
387                 } else {
388                     # search again if we aren't at the first list and there is more results
389                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
390                 }
391                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
392             } else {
393                 for (my $j = 1; $j < $#arrBiblios; $j++) {
394                     if ($arrBiblios[$j] == $biblionumber) {
395                         for (my $z = $j - 1; $z >= 0; $z--) {
396                             next unless ($arrBiblios[$z]);
397                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
398                             last;
399                         }
400                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
401                             next unless ($arrBiblios[$z]);
402                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
403                             last;
404                         }
405                         last;
406                     }
407                 }
408             }
409         }
410         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
411     }
412     if ($searchAgain) {
413         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
414         my @newresults = @$newresultsRef;
415         # build the new listBiblios
416         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
417         unless (exists($arrParamsBusc{'listBiblios'})) {
418             $arrParamsBusc{'listBiblios'} = $listBiblios;
419             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
420         } else {
421             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
422         }
423         # From the new list we build again the next and previous result
424         if (@arrBiblios) {
425             if ($arrBiblios[0] == $biblionumber) {
426                 for (my $j = $#newresults; $j >= 0; $j--) {
427                     next unless ($newresults[$j]);
428                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
429                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
430                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
431                    last;
432                 }
433             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
434                 for (my $j = 0; $j < @newresults; $j++) {
435                     next unless ($newresults[$j]);
436                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
437                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
438                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
439                     last;
440                 }
441             }
442         }
443         # build new busc param
444         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
445         $session->param("busc" => $newbusc);
446     }
447     my ($numberBiblioPaging, $dataBiblioPaging);
448     # Previous biblio
449     $numberBiblioPaging = $paging{'previous'}->{biblionumber};
450     if ($numberBiblioPaging) {
451         $template->param( 'previousBiblionumber' => $numberBiblioPaging );
452         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
453         $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
454     }
455     # Next biblio
456     $numberBiblioPaging = $paging{'next'}->{biblionumber};
457     if ($numberBiblioPaging) {
458         $template->param( 'nextBiblionumber' => $numberBiblioPaging );
459         $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
460         $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
461     }
462     # Partial list of biblio results
463     my @listResults;
464     for (my $j = 0; $j < @arrBiblios; $j++) {
465         next unless ($arrBiblios[$j]);
466         $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber);
467         push @listResults, {index => $j + 1 + $offset, biblionumber => $arrBiblios[$j], title => ($arrBiblios[$j] == $biblionumber)?'':$dataBiblioPaging->title, author => ($arrBiblios[$j] != $biblionumber && $dataBiblioPaging->author)?$dataBiblioPaging->author:'', url => ($arrBiblios[$j] == $biblionumber)?'':'opac-detail.pl?biblionumber=' . $arrBiblios[$j]};
468     }
469     $template->param('listResults' => \@listResults) if (@listResults);
470     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
471     $template->param( 'offset' => $offset );
472 }
473 }
474
475 $template->param(
476     OPACShowCheckoutName => C4::Context->preference("OPACShowCheckoutName"),
477 );
478
479 # adding items linked via host biblios
480
481 my $analyticfield = '773';
482 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
483     $analyticfield = '773';
484 } elsif ($marcflavour eq 'UNIMARC') {
485     $analyticfield = '461';
486 }
487 foreach my $hostfield ( $record->field($analyticfield)) {
488     my $hostbiblionumber = $hostfield->subfield("0");
489     my $linkeditemnumber = $hostfield->subfield("9");
490     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
491     foreach my $hostitemInfo (@hostitemInfos){
492         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
493             push(@all_items, $hostitemInfo);
494         }
495     }
496 }
497
498 my @items;
499
500 # Are there items to hide?
501 my $hideitems;
502 $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
503
504 # Hide items
505 if ($hideitems) {
506     for my $itm (@all_items) {
507         if  ( C4::Context->preference('hidelostitems') ) {
508             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
509         } else {
510             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
511     }
512 }
513 } else {
514     # Or not
515     @items = @all_items;
516 }
517
518 my $branch = '';
519 if (C4::Context->userenv){
520     $branch = C4::Context->userenv->{branch};
521 }
522 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
523     if (
524         ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
525         ||
526         C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
527     ) {
528         my $branchcode;
529         if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
530             $branchcode = $branch;
531         }
532         elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
533             $branchcode = $ENV{'BRANCHCODE'};
534         }
535
536         my @our_items;
537         my @other_items;
538
539         foreach my $item ( @items ) {
540            if ( $item->{branchcode} eq $branchcode ) {
541                $item->{'this_branch'} = 1;
542                push( @our_items, $item );
543            } else {
544                push( @other_items, $item );
545            }
546         }
547
548         @items = ( @our_items, @other_items );
549     }
550 }
551
552 my $dat = &GetBiblioData($biblionumber);
553 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
554     {
555         frameworkcode => $dat->{'frameworkcode'},
556         interface     => 'opac',
557     } );
558
559 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
560 # imageurl:
561 my $itemtype = $dat->{'itemtype'};
562 if ( $itemtype ) {
563     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
564     $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
565 }
566
567 my $shelflocations =
568   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
569 my $collections =
570   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
571 my $copynumbers =
572   { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
573
574 #coping with subscriptions
575 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
576 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
577
578 my @subs;
579 $dat->{'serial'}=1 if $subscriptionsnumber;
580 foreach my $subscription (@subscriptions) {
581     my $serials_to_display;
582     my %cell;
583     $cell{subscriptionid}    = $subscription->{subscriptionid};
584     $cell{subscriptionnotes} = $subscription->{notes};
585     $cell{missinglist}       = $subscription->{missinglist};
586     $cell{opacnote}          = $subscription->{opacnote};
587     $cell{histstartdate}     = $subscription->{histstartdate};
588     $cell{histenddate}       = $subscription->{histenddate};
589     $cell{branchcode}        = $subscription->{branchcode};
590     $cell{callnumber}        = $subscription->{callnumber};
591     $cell{closed}            = $subscription->{closed};
592     $cell{letter}            = $subscription->{letter};
593     $cell{biblionumber}      = $subscription->{biblionumber};
594     #get the three latest serials.
595     $serials_to_display = $subscription->{opacdisplaycount};
596     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
597         $cell{opacdisplaycount} = $serials_to_display;
598     $cell{latestserials} =
599       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
600     if ( $borrowernumber ) {
601         my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} );
602         my $subscriber = $subscription_object->subscribers->find( $borrowernumber );
603         $cell{hasalert} = 1 if $subscriber;
604     }
605     push @subs, \%cell;
606 }
607
608 $dat->{'count'} = scalar(@items);
609
610
611 my (%item_reserves, %priority);
612 my ($show_holds_count, $show_priority);
613 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
614     m/holds/o and $show_holds_count = 1;
615     m/priority/ and $show_priority = 1;
616 }
617 my $has_hold;
618 if ( $show_holds_count || $show_priority) {
619     my $holds = $biblio->holds;
620     $template->param( holds_count  => $holds->count );
621     while ( my $hold = $holds->next ) {
622         $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber;
623         if ($show_priority && $hold->borrowernumber == $borrowernumber) {
624             $has_hold = 1;
625             $hold->itemnumber
626                 ? ($priority{ $hold->itemnumber } = $hold->priority)
627                 : ($template->param( priority => $hold->priority ));
628         }
629     }
630 }
631 $template->param( show_priority => $has_hold ) ;
632
633 my $norequests = 1;
634 my %itemfields;
635 my (@itemloop, @otheritemloop);
636 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
637 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
638     $template->param(SeparateHoldings => 1);
639 }
640 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
641 my $viewallitems = $query->param('viewallitems');
642 my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50;
643
644 # Get items on order
645 my ( @itemnumbers_on_order );
646 if ( C4::Context->preference('OPACAcquisitionDetails' ) ) {
647     my $orders = C4::Acquisition::SearchOrders({
648         biblionumber => $biblionumber,
649         ordered => 1,
650     });
651     my $total_quantity = 0;
652     for my $order ( @$orders ) {
653         my $basket = Koha::Acquisition::Orders->find( $order->{ordernumber} )->basket;
654         if ( $basket->effective_create_items eq 'ordering' ) {
655             for my $itemnumber ( C4::Acquisition::GetItemnumbersFromOrder( $order->{ordernumber} ) ) {
656                 push @itemnumbers_on_order, $itemnumber;
657             }
658         }
659         $total_quantity += $order->{quantity};
660     }
661     $template->{VARS}->{acquisition_details} = {
662         total_quantity => $total_quantity,
663     };
664 }
665
666 my $allow_onshelf_holds;
667 if ( not $viewallitems and @items > $max_items_to_display ) {
668     $template->param(
669         too_many_items => 1,
670         items_count => scalar( @items ),
671     );
672 } else {
673   my $patron = Koha::Patrons->find( $borrowernumber );
674   for my $itm (@items) {
675     my $item = Koha::Items->find( $itm->{itemnumber} );
676     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
677     $itm->{priority} = $priority{ $itm->{itemnumber} };
678     $norequests = 0
679       if $norequests
680         && !$itm->{'withdrawn'}
681         && !$itm->{'itemlost'}
682         && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'})
683         && !$itemtypes->{$itm->{'itype'}}->{notforloan}
684         && $itm->{'itemnumber'};
685
686     $allow_onshelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } )
687       unless $allow_onshelf_holds;
688
689     # get collection code description, too
690     my $ccode = $itm->{'ccode'};
691     $itm->{'ccode'} = $collections->{$ccode} if defined($ccode) && $collections && exists( $collections->{$ccode} );
692     my $copynumber = $itm->{'copynumber'};
693     $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
694     if ( defined $itm->{'location'} ) {
695         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
696     }
697     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
698         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
699         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{translated_description};
700     }
701     foreach (qw(ccode enumchron copynumber itemnotes location_description uri)) {
702         $itemfields{$_} = 1 if ($itm->{$_});
703     }
704
705      my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
706       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
707       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
708     
709      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
710      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
711         $itm->{transfertwhen} = $transfertwhen;
712         $itm->{transfertfrom} = $transfertfrom;
713         $itm->{transfertto}   = $transfertto;
714      }
715     
716     if ( C4::Context->preference('OPACAcquisitionDetails') ) {
717         $itm->{on_order} = 1
718           if grep /^$itm->{itemnumber}$/, @itemnumbers_on_order;
719     }
720
721     my $itembranch = $itm->{$separatebranch};
722     if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
723         if ($itembranch and $itembranch eq $currentbranch) {
724             push @itemloop, $itm;
725         } else {
726             push @otheritemloop, $itm;
727         }
728     } else {
729         push @itemloop, $itm;
730     }
731   }
732 }
733
734 if( $allow_onshelf_holds || CountItemsIssued($biblionumber) || $biblio->has_items_waiting_or_intransit ) {
735     $template->param( ReservableItems => 1 );
736 }
737
738 # Display only one tab if one items list is empty
739 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
740     $template->param(SeparateHoldings => 0);
741     if (scalar(@itemloop) == 0) {
742         @itemloop = @otheritemloop;
743     }
744 }
745
746 ## get notes and subjects from MARC record
747 if (!C4::Context->preference("OPACXSLTDetailsDisplay") ) {
748     my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
749     my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
750     my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
751     my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
752     my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
753     my $marchostsarray   = GetMarcHosts($record,$marcflavour);
754
755     $template->param(
756         MARCSUBJCTS => $marcsubjctsarray,
757         MARCAUTHORS => $marcauthorsarray,
758         MARCSERIES  => $marcseriesarray,
759         MARCURLS    => $marcurlsarray,
760         MARCISBNS   => $marcisbnsarray,
761         MARCHOSTS   => $marchostsarray,
762     );
763 }
764
765 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
766 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
767
768 if( C4::Context->preference('ArticleRequests') ) {
769     my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef;
770     my $itemtype = Koha::ItemTypes->find($biblio->itemtype);
771     my $artreqpossible = $patron
772         ? $biblio->can_article_request( $patron )
773         : $itemtype
774         ? $itemtype->may_article_request
775         : q{};
776     $template->param( artreqpossible => $artreqpossible );
777 }
778
779     $template->param(
780                      MARCNOTES               => $marcnotesarray,
781                      norequests              => $norequests,
782                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
783                      itemdata_ccode          => $itemfields{ccode},
784                      itemdata_enumchron      => $itemfields{enumchron},
785                      itemdata_uri            => $itemfields{uri},
786                      itemdata_copynumber     => $itemfields{copynumber},
787                      itemdata_itemnotes      => $itemfields{itemnotes},
788                      itemdata_location       => $itemfields{location_description},
789                      subtitle                => $subtitle,
790                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
791     );
792
793 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
794     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
795     my $subfields = substr $fieldspec, 3;
796     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
797     my @alternateholdingsinfo = ();
798     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
799
800     for my $field (@holdingsfields) {
801         my %holding = ( holding => '' );
802         my $havesubfield = 0;
803         for my $subfield ($field->subfields()) {
804             if ((index $subfields, $$subfield[0]) >= 0) {
805                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
806                 $holding{'holding'} .= $$subfield[1];
807                 $havesubfield++;
808             }
809         }
810         if ($havesubfield) {
811             push(@alternateholdingsinfo, \%holding);
812         }
813     }
814
815     $template->param(
816         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
817         );
818 }
819
820 # FIXME: The template uses this hash directly. Need to filter.
821 foreach ( keys %{$dat} ) {
822     next if ( $HideMARC->{$_} );
823     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
824 }
825
826 # some useful variables for enhanced content;
827 # in each case, we're grabbing the first value we find in
828 # the record and normalizing it
829 my $upc = GetNormalizedUPC($record,$marcflavour);
830 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
831 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
832 my $content_identifier_exists;
833 if ( $isbn or $ean or $oclc or $upc ) {
834     $content_identifier_exists = 1;
835 }
836 $template->param(
837         normalized_upc => $upc,
838         normalized_ean => $ean,
839         normalized_oclc => $oclc,
840         normalized_isbn => $isbn,
841         content_identifier_exists =>  $content_identifier_exists,
842 );
843
844 # COinS format FIXME: for books Only
845 $template->param(
846     ocoins => GetCOinSBiblio($record),
847 );
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 $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 ( $patron ) {
875             $review->{patron} = $patron;
876             if ( $libravatar_enabled and $patron->email ) {
877                 $review->{avatarurl} = libravatar_url( email => $patron->email, https => $ENV{HTTPS} );
878             }
879
880             if ( $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)
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;