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