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