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