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