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