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