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