Bug 10704: make OPAC highlighting work across previous/next travel
[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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22
23 use strict;
24 use warnings;
25
26 use CGI;
27 use C4::Auth qw(:DEFAULT get_session);
28 use C4::Branch;
29 use C4::Koha;
30 use C4::Serials;    #uses getsubscriptionfrom biblionumber
31 use C4::Output;
32 use C4::Biblio;
33 use C4::Items;
34 use C4::Circulation;
35 use C4::Tags qw(get_tags);
36 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
37 use C4::External::Amazon;
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::Review;
40 use C4::Ratings;
41 use C4::Members;
42 use C4::VirtualShelves;
43 use C4::XSLT;
44 use C4::ShelfBrowser;
45 use C4::Reserves;
46 use C4::Charset;
47 use MARC::Record;
48 use MARC::Field;
49 use List::MoreUtils qw/any none/;
50 use C4::Images;
51 use Koha::DateUtils;
52 use C4::HTML5Media;
53 use C4::CourseReserves qw(GetItemCourseReservesInfo);
54
55 BEGIN {
56         if (C4::Context->preference('BakerTaylorEnabled')) {
57                 require C4::External::BakerTaylor;
58                 import C4::External::BakerTaylor qw(&image_url &link_url);
59         }
60 }
61
62 my $query = new CGI;
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
64     {
65         template_name   => "opac-detail.tmpl",
66         query           => $query,
67         type            => "opac",
68         authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
69         flagsrequired   => { borrow => 1 },
70     }
71 );
72
73 my $biblionumber = $query->param('biblionumber') || $query->param('bib');
74 $biblionumber = int($biblionumber);
75
76 my $record       = GetMarcBiblio($biblionumber);
77 if ( ! $record ) {
78     print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
79     exit;
80 }
81 $template->param( biblionumber => $biblionumber );
82
83 # get biblionumbers stored in the cart
84 my @cart_list;
85
86 if($query->cookie("bib_list")){
87     my $cart_list = $query->cookie("bib_list");
88     @cart_list = split(/\//, $cart_list);
89     if ( grep {$_ eq $biblionumber} @cart_list) {
90         $template->param( incart => 1 );
91     }
92 }
93
94
95 SetUTF8Flag($record);
96 my $marcflavour      = C4::Context->preference("marcflavour");
97 my $ean = GetNormalizedEAN( $record, $marcflavour );
98
99 # XSLT processing of some stuff
100 if (C4::Context->preference("OPACXSLTDetailsDisplay") ) {
101     $template->param( 'XSLTBloc' => XSLTParse4Display($biblionumber, $record, "OPACXSLTDetailsDisplay" ) );
102 }
103
104 my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults");
105 $template->{VARS}->{'OpacBrowseResults'} = $OpacBrowseResults;
106
107 # We look for the busc param to build the simple paging from the search
108 if ($OpacBrowseResults) {
109 my $session = get_session($query->cookie("CGISESSID"));
110 my %paging = (previous => {}, next => {});
111 if ($session->param('busc')) {
112     use C4::Search;
113
114     # Rebuild the string to store on session
115     sub rebuildBuscParam
116     {
117         my $arrParamsBusc = shift;
118
119         my $pasarParams = '';
120         my $j = 0;
121         for (keys %$arrParamsBusc) {
122             if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
123                 if (defined($arrParamsBusc->{$_})) {
124                     $pasarParams .= '&' if ($j);
125                     $pasarParams .= $_ . '=' . $arrParamsBusc->{$_};
126                     $j++;
127                 }
128             } else {
129                 for my $value (@{$arrParamsBusc->{$_}}) {
130                     $pasarParams .= '&' if ($j);
131                     $pasarParams .= $_ . '=' . $value;
132                     $j++;
133                 }
134             }
135         }
136         return $pasarParams;
137     }#rebuildBuscParam
138
139     # Search given the current values from the busc param
140     sub searchAgain
141     {
142         my ($arrParamsBusc, $offset, $results_per_page) = @_;
143
144         my $expanded_facet = $arrParamsBusc->{'expand'};
145         my $branches = GetBranches();
146         my @servers;
147         @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
148         @servers = ("biblioserver") unless (@servers);
149
150         my ($default_sort_by, @sort_by);
151         $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
152         @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
153         $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
154         my ($error, $results_hashref, $facets);
155         eval {
156             ($error, $results_hashref, $facets) = getRecords($arrParamsBusc->{'query'},$arrParamsBusc->{'simple_query'},\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'});
157         };
158         my $hits;
159         my @newresults;
160         for (my $i=0;$i<@servers;$i++) {
161             my $server = $servers[$i];
162             $hits = $results_hashref->{$server}->{"hits"};
163             @newresults = searchResults('opac', '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
164         }
165         return \@newresults;
166     }#searchAgain
167
168     # Build the current list of biblionumbers in this search
169     sub buildListBiblios
170     {
171         my ($newresultsRef, $results_per_page) = @_;
172
173         my $listBiblios = '';
174         my $j = 0;
175         foreach (@$newresultsRef) {
176             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
177             $listBiblios .= $bibnum . ',';
178             $j++;
179             last if ($j == $results_per_page);
180         }
181         chop $listBiblios if ($listBiblios =~ /,$/);
182         return $listBiblios;
183     }#buildListBiblios
184
185     my $busc = $session->param("busc");
186     my @arrBusc = split(/\&(?:amp;)?/, $busc);
187     my ($key, $value);
188     my %arrParamsBusc = ();
189     for (@arrBusc) {
190         ($key, $value) = split(/=/, $_, 2);
191         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
192             $arrParamsBusc{$key} = $value;
193         } else {
194             unless (exists($arrParamsBusc{$key})) {
195                 $arrParamsBusc{$key} = [];
196             }
197             push @{$arrParamsBusc{$key}}, $value;
198         }
199     }
200     my $searchAgain = 0;
201     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
202     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
203     $arrParamsBusc{'count'} = $results_per_page;
204     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
205     # The value OPACnumSearchResults has changed and the search has to be rebuild
206     if ($count != $results_per_page) {
207         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
208             my $indexBiblio = 0;
209             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
210             for (@arrBibliosAux) {
211                 last if ($_ == $biblionumber);
212                 $indexBiblio++;
213             }
214             $indexBiblio += $offset;
215             $offset = int($indexBiblio / $count) * $count;
216             $arrParamsBusc{'offset'} = $offset;
217         }
218         $arrParamsBusc{'count'} = $count;
219         $results_per_page = $count;
220         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
221         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
222         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
223         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
224         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
225         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
226         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
227         $session->param("busc" => $newbusc);
228         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
229     } else {
230         my $modifyListBiblios = 0;
231         # We come from a previous click
232         if (exists($arrParamsBusc{'previous'})) {
233             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
234             delete $arrParamsBusc{'previous'};
235         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
236             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
237             delete $arrParamsBusc{'next'};
238         }
239         if ($modifyListBiblios) {
240             if (exists($arrParamsBusc{'newlistBiblios'})) {
241                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
242                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
243                 my @arrAux = split(',', $listBibliosAux);
244                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
245                 if ($modifyListBiblios == 1) {
246                     $arrParamsBusc{'next'} = $arrAux[0];
247                     $paging{'next'}->{biblionumber} = $arrAux[0];
248                 }else {
249                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
250                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
251                 }
252             } else {
253                 delete $arrParamsBusc{'listBiblios'};
254             }
255             my $offsetAux = $arrParamsBusc{'offset'};
256             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
257             $arrParamsBusc{'offsetSearch'} = $offsetAux;
258             $offset = $arrParamsBusc{'offset'};
259             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
260             $session->param("busc" => $newbusc);
261             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
262         }
263     }
264     my $buscParam = '';
265     my $j = 0;
266     # Rebuild the query for the button "back to results"
267     for (@arrBusc) {
268         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
269             $buscParam .= '&amp;' unless ($j == 0);
270             $buscParam .= $_;
271             $j++;
272         }
273     }
274     $template->param('busc' => $buscParam);
275     my $offsetSearch;
276     my @arrBiblios;
277     # We are inside the list of biblios and we don't have to search
278     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
279         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
280         if (@arrBiblios) {
281             # We are at the first item of the list
282             if ($arrBiblios[0] == $biblionumber) {
283                 if (@arrBiblios > 1) {
284                     for (my $j = 1; $j < @arrBiblios; $j++) {
285                         next unless ($arrBiblios[$j]);
286                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
287                         last;
288                     }
289                 }
290                 # search again if we are not at the first searching list
291                 if ($offset && !$arrParamsBusc{'previous'}) {
292                     $searchAgain = 1;
293                     $offsetSearch = $offset - $results_per_page;
294                 }
295             # we are at the last item of the list
296             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
297                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
298                     next unless ($arrBiblios[$j]);
299                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
300                     last;
301                 }
302                 if (!$offset) {
303                     # search again if we are at the first list and there is more results
304                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
305                 } else {
306                     # search again if we aren't at the first list and there is more results
307                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
308                 }
309                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
310             } else {
311                 for (my $j = 1; $j < $#arrBiblios; $j++) {
312                     if ($arrBiblios[$j] == $biblionumber) {
313                         for (my $z = $j - 1; $z >= 0; $z--) {
314                             next unless ($arrBiblios[$z]);
315                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
316                             last;
317                         }
318                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
319                             next unless ($arrBiblios[$z]);
320                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
321                             last;
322                         }
323                         last;
324                     }
325                 }
326             }
327         }
328         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
329     }
330     if ($searchAgain) {
331         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
332         my @newresults = @$newresultsRef;
333         # build the new listBiblios
334         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
335         unless (exists($arrParamsBusc{'listBiblios'})) {
336             $arrParamsBusc{'listBiblios'} = $listBiblios;
337             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
338         } else {
339             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
340         }
341         # From the new list we build again the next and previous result
342         if (@arrBiblios) {
343             if ($arrBiblios[0] == $biblionumber) {
344                 for (my $j = $#newresults; $j >= 0; $j--) {
345                     next unless ($newresults[$j]);
346                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
347                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
348                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
349                    last;
350                 }
351             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
352                 for (my $j = 0; $j < @newresults; $j++) {
353                     next unless ($newresults[$j]);
354                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
355                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
356                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
357                     last;
358                 }
359             }
360         }
361         # build new busc param
362         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
363         $session->param("busc" => $newbusc);
364     }
365     my ($previous, $next, $dataBiblioPaging);
366     # Previous biblio
367     if ($paging{'previous'}->{biblionumber}) {
368         $previous = 'opac-detail.pl?biblionumber=' . $paging{'previous'}->{biblionumber}  . '&query_desc=' . $query->param('query_desc');
369         $dataBiblioPaging = GetBiblioData($paging{'previous'}->{biblionumber});
370         $template->param('previousTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
371     }
372     # Next biblio
373     if ($paging{'next'}->{biblionumber}) {
374         $next = 'opac-detail.pl?biblionumber=' . $paging{'next'}->{biblionumber} . '&query_desc=' . $query->param('query_desc');
375         $dataBiblioPaging = GetBiblioData($paging{'next'}->{biblionumber});
376         $template->param('nextTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
377     }
378     $template->param('previous' => $previous, 'next' => $next);
379     # Partial list of biblio results
380     my @listResults;
381     for (my $j = 0; $j < @arrBiblios; $j++) {
382         next unless ($arrBiblios[$j]);
383         $dataBiblioPaging = GetBiblioData($arrBiblios[$j]) if ($arrBiblios[$j] != $biblionumber);
384         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]};
385     }
386     $template->param('listResults' => \@listResults) if (@listResults);
387     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
388 }
389 }
390
391
392
393 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
394 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
395
396
397
398 $template->param('OPACShowCheckoutName' => C4::Context->preference("OPACShowCheckoutName") );
399 $template->param('OPACShowBarcode' => C4::Context->preference("OPACShowBarcode") );
400 # change back when ive fixed request.pl
401 my @all_items = GetItemsInfo( $biblionumber );
402
403 # adding items linked via host biblios
404
405 my $analyticfield = '773';
406 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
407     $analyticfield = '773';
408 } elsif ($marcflavour eq 'UNIMARC') {
409     $analyticfield = '461';
410 }
411 foreach my $hostfield ( $record->field($analyticfield)) {
412     my $hostbiblionumber = $hostfield->subfield("0");
413     my $linkeditemnumber = $hostfield->subfield("9");
414     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
415     foreach my $hostitemInfo (@hostitemInfos){
416         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
417             push(@all_items, $hostitemInfo);
418         }
419     }
420 }
421
422 my @items;
423
424 # Getting items to be hidden
425 my @hiddenitems = GetHiddenItemnumbers(@all_items);
426
427 # Are there items to hide?
428 my $hideitems;
429 $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
430
431 # Hide items
432 if ($hideitems) {
433     for my $itm (@all_items) {
434         if  ( C4::Context->preference('hidelostitems') ) {
435             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
436         } else {
437             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
438     }
439 }
440 } else {
441     # Or not
442     @items = @all_items;
443 }
444
445 my $branches = GetBranches();
446 my $branch = '';
447 if (C4::Context->userenv){
448     $branch = C4::Context->userenv->{branch};
449 }
450 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
451     if (
452         ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
453         ||
454         C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
455     ) {
456         my $branchname;
457         if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
458             $branchname = $branches->{$branch}->{'branchname'};
459         }
460         elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
461             $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
462         }
463
464         my @our_items;
465         my @other_items;
466
467         foreach my $item ( @items ) {
468            if ( $item->{'branchname'} eq $branchname ) {
469                $item->{'this_branch'} = 1;
470                push( @our_items, $item );
471            } else {
472                push( @other_items, $item );
473            }
474         }
475
476         @items = ( @our_items, @other_items );
477     }
478 }
479
480 my $dat = &GetBiblioData($biblionumber);
481
482 my $itemtypes = GetItemTypes();
483 # imageurl:
484 my $itemtype = $dat->{'itemtype'};
485 if ( $itemtype ) {
486     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
487     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
488 }
489 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'}, 'opac');
490 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'}, 'opac');
491 my $copynumbers = GetKohaAuthorisedValues('items.copynumber',$dat->{'frameworkcode'}, 'opac');
492
493 #coping with subscriptions
494 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
495 my @subscriptions       = GetSubscriptions($dat->{'title'}, $dat->{'issn'}, $ean, $biblionumber );
496
497 my @subs;
498 $dat->{'serial'}=1 if $subscriptionsnumber;
499 foreach my $subscription (@subscriptions) {
500     my $serials_to_display;
501     my %cell;
502     $cell{subscriptionid}    = $subscription->{subscriptionid};
503     $cell{subscriptionnotes} = $subscription->{notes};
504     $cell{missinglist}       = $subscription->{missinglist};
505     $cell{opacnote}          = $subscription->{opacnote};
506     $cell{histstartdate}     = $subscription->{histstartdate};
507     $cell{histenddate}       = $subscription->{histenddate};
508     $cell{branchcode}        = $subscription->{branchcode};
509     $cell{branchname}        = GetBranchName($subscription->{branchcode});
510     $cell{hasalert}          = $subscription->{hasalert};
511     $cell{callnumber}        = $subscription->{callnumber};
512     $cell{closed}            = $subscription->{closed};
513     #get the three latest serials.
514     $serials_to_display = $subscription->{opacdisplaycount};
515     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
516         $cell{opacdisplaycount} = $serials_to_display;
517     $cell{latestserials} =
518       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
519     push @subs, \%cell;
520 }
521
522 $dat->{'count'} = scalar(@items);
523
524
525 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
526
527 my (%item_reserves, %priority);
528 my ($show_holds_count, $show_priority);
529 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
530     m/holds/o and $show_holds_count = 1;
531     m/priority/ and $show_priority = 1;
532 }
533 my $has_hold;
534 if ( $show_holds_count || $show_priority) {
535     my ($reserve_count,$reserves) = GetReservesFromBiblionumber($biblionumber);
536     $template->param( holds_count  => $reserve_count ) if $show_holds_count;
537     foreach (@$reserves) {
538         $item_reserves{ $_->{itemnumber} }++ if $_->{itemnumber};
539         if ($show_priority && $_->{borrowernumber} == $borrowernumber) {
540             $has_hold = 1;
541             $_->{itemnumber}
542                 ? ($priority{ $_->{itemnumber} } = $_->{priority})
543                 : ($template->param( priority => $_->{priority} ));
544         }
545     }
546 }
547 $template->param( show_priority => $has_hold ) ;
548
549 my $norequests = 1;
550 my %itemfields;
551 my (@itemloop, @otheritemloop);
552 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
553 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
554     $template->param(SeparateHoldings => 1);
555 }
556 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
557 for my $itm (@items) {
558     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
559     $itm->{priority} = $priority{ $itm->{itemnumber} };
560     $norequests = 0
561        if ( (not $itm->{'wthdrawn'} )
562          && (not $itm->{'itemlost'} )
563          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
564                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
565          && ($itm->{'itemnumber'} ) );
566
567     # get collection code description, too
568     my $ccode = $itm->{'ccode'};
569     $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
570     my $copynumber = $itm->{'copynumber'};
571     $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
572     if ( defined $itm->{'location'} ) {
573         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
574     }
575     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
576         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
577         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
578     }
579     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
580         $itemfields{$_} = 1 if ($itm->{$_});
581     }
582
583      # walk through the item-level authorised values and populate some images
584      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
585      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
586
587      if ( $itm->{'itemlost'} ) {
588          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
589          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
590          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
591      }
592      my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
593       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
594       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
595     
596      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
597      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
598         $itm->{transfertwhen} = $transfertwhen;
599         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
600         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
601      }
602     my $itembranch = $itm->{$separatebranch};
603     if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
604         if ($itembranch and $itembranch eq $currentbranch) {
605             push @itemloop, $itm;
606         } else {
607             push @otheritemloop, $itm;
608         }
609     } else {
610         push @itemloop, $itm;
611     }
612 }
613
614 # Display only one tab if one items list is empty
615 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
616     $template->param(SeparateHoldings => 0);
617     if (scalar(@itemloop) == 0) {
618         @itemloop = @otheritemloop;
619     }
620 }
621
622 # If there is a lot of items, and the user has not decided
623 # to view them all yet, we first warn him
624 # TODO: The limit of 50 could be a syspref
625 my $viewallitems = $query->param('viewallitems');
626 if (scalar(@itemloop) >= 50 && !$viewallitems) {
627     $template->param('lotsofitems' => 1);
628 }
629
630 ## get notes and subjects from MARC record
631 my $dbh              = C4::Context->dbh;
632 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
633 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
634 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
635 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
636 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
637 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
638 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
639 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
640
641     $template->param(
642                      MARCNOTES               => $marcnotesarray,
643                      MARCSUBJCTS             => $marcsubjctsarray,
644                      MARCAUTHORS             => $marcauthorsarray,
645                      MARCSERIES              => $marcseriesarray,
646                      MARCURLS                => $marcurlsarray,
647                      MARCISBNS               => $marcisbnsarray,
648                      MARCHOSTS               => $marchostsarray,
649                      norequests              => $norequests,
650                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
651                      itemdata_ccode          => $itemfields{ccode},
652                      itemdata_enumchron      => $itemfields{enumchron},
653                      itemdata_uri            => $itemfields{uri},
654                      itemdata_copynumber     => $itemfields{copynumber},
655                      itemdata_itemnotes          => $itemfields{itemnotes},
656                      authorised_value_images => $biblio_authorised_value_images,
657                      subtitle                => $subtitle,
658                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
659     );
660
661 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
662     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
663     my $subfields = substr $fieldspec, 3;
664     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
665     my @alternateholdingsinfo = ();
666     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
667
668     for my $field (@holdingsfields) {
669         my %holding = ( holding => '' );
670         my $havesubfield = 0;
671         for my $subfield ($field->subfields()) {
672             if ((index $subfields, $$subfield[0]) >= 0) {
673                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
674                 $holding{'holding'} .= $$subfield[1];
675                 $havesubfield++;
676             }
677         }
678         if ($havesubfield) {
679             push(@alternateholdingsinfo, \%holding);
680         }
681     }
682
683     $template->param(
684         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
685         );
686 }
687
688 foreach ( keys %{$dat} ) {
689     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
690 }
691
692 # some useful variables for enhanced content;
693 # in each case, we're grabbing the first value we find in
694 # the record and normalizing it
695 my $upc = GetNormalizedUPC($record,$marcflavour);
696 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
697 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
698 my $content_identifier_exists;
699 if ( $isbn or $ean or $oclc or $upc ) {
700     $content_identifier_exists = 1;
701 }
702 $template->param(
703         normalized_upc => $upc,
704         normalized_ean => $ean,
705         normalized_oclc => $oclc,
706         normalized_isbn => $isbn,
707         content_identifier_exists =>  $content_identifier_exists,
708 );
709
710 # COinS format FIXME: for books Only
711 $template->param(
712     ocoins => GetCOinSBiblio($record),
713 );
714
715 my $libravatar_enabled = 0;
716 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) {
717     eval {
718         require Libravatar::URL;
719         Libravatar::URL->import();
720     };
721     if (!$@ ) {
722         $libravatar_enabled = 1;
723     }
724 }
725
726 my $reviews = getreviews( $biblionumber, 1 );
727 my $loggedincommenter;
728
729
730
731
732 foreach ( @$reviews ) {
733     my $borrowerData   = GetMember('borrowernumber' => $_->{borrowernumber});
734     # setting some borrower info into this hash
735     $_->{title}     = $borrowerData->{'title'};
736     $_->{surname}   = $borrowerData->{'surname'};
737     $_->{firstname} = $borrowerData->{'firstname'};
738     if ($libravatar_enabled and $borrowerData->{'email'}) {
739         $_->{avatarurl} = libravatar_url(email => $borrowerData->{'email'}, https => $ENV{HTTPS});
740     }
741     $_->{userid}    = $borrowerData->{'userid'};
742     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
743
744     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
745                 $_->{your_comment} = 1;
746                 $loggedincommenter = 1;
747         }
748 }
749
750
751 if(C4::Context->preference("ISBD")) {
752         $template->param(ISBD => 1);
753 }
754
755 $template->param(
756     itemloop            => \@itemloop,
757     otheritemloop       => \@otheritemloop,
758     subscriptionsnumber => $subscriptionsnumber,
759     biblionumber        => $biblionumber,
760     subscriptions       => \@subs,
761     subscriptionsnumber => $subscriptionsnumber,
762     reviews             => $reviews,
763     loggedincommenter   => $loggedincommenter
764 );
765
766 # Lists
767
768 if (C4::Context->preference("virtualshelves") ) {
769    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
770 }
771
772
773 # XISBN Stuff
774 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
775     eval {
776         $template->param(
777             XISBNS => get_xisbns($isbn)
778         );
779     };
780     if ($@) { warn "XISBN Failed $@"; }
781 }
782
783 # Serial Collection
784 my @sc_fields = $record->field(955);
785 my @lc_fields = $marcflavour eq 'UNIMARC'
786     ? $record->field(930)
787     : $record->field(852);
788 my @serialcollections = ();
789
790 foreach my $sc_field (@sc_fields) {
791     my %row_data;
792
793     $row_data{text}    = $sc_field->subfield('r');
794     $row_data{branch}  = $sc_field->subfield('9');
795     foreach my $lc_field (@lc_fields) {
796         $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
797             ? $lc_field->subfield('a') # 930$a
798             : $lc_field->subfield('h') # 852$h
799             if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
800     }
801
802     if ($row_data{text} && $row_data{branch}) { 
803         push (@serialcollections, \%row_data);
804     }
805 }
806
807 if (scalar(@serialcollections) > 0) {
808     $template->param(
809         serialcollection  => 1,
810         serialcollections => \@serialcollections);
811 }
812
813 # Local cover Images stuff
814 if (C4::Context->preference("OPACLocalCoverImages")){
815                 $template->param(OPACLocalCoverImages => 1);
816 }
817
818 # HTML5 Media
819 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
820     $template->param( C4::HTML5Media->gethtml5media($record));
821 }
822
823 my $syndetics_elements;
824
825 if ( C4::Context->preference("SyndeticsEnabled") ) {
826     $template->param("SyndeticsEnabled" => 1);
827     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
828         eval {
829             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
830             for my $element (values %$syndetics_elements) {
831                 $template->param("Syndetics$element"."Exists" => 1 );
832                 #warn "Exists: "."Syndetics$element"."Exists";
833         }
834     };
835     warn $@ if $@;
836 }
837
838 if ( C4::Context->preference("SyndeticsEnabled")
839         && C4::Context->preference("SyndeticsSummary")
840         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
841         eval {
842             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
843             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
844         };
845         warn $@ if $@;
846
847 }
848
849 if ( C4::Context->preference("SyndeticsEnabled")
850         && C4::Context->preference("SyndeticsTOC")
851         && exists($syndetics_elements->{'TOC'}) ) {
852         eval {
853     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
854     $template->param( SYNDETICS_TOC => $syndetics_toc );
855         };
856         warn $@ if $@;
857 }
858
859 if ( C4::Context->preference("SyndeticsEnabled")
860     && C4::Context->preference("SyndeticsExcerpt")
861     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
862     eval {
863     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
864     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
865     };
866         warn $@ if $@;
867 }
868
869 if ( C4::Context->preference("SyndeticsEnabled")
870     && C4::Context->preference("SyndeticsReviews")) {
871     eval {
872     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
873     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
874     };
875         warn $@ if $@;
876 }
877
878 if ( C4::Context->preference("SyndeticsEnabled")
879     && C4::Context->preference("SyndeticsAuthorNotes")
880         && exists($syndetics_elements->{'ANOTES'}) ) {
881     eval {
882     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
883     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
884     };
885     warn $@ if $@;
886 }
887
888 # LibraryThingForLibraries ID Code and Tabbed View Option
889 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
890
891 $template->param(LibraryThingForLibrariesID =>
892 C4::Context->preference('LibraryThingForLibrariesID') ); 
893 $template->param(LibraryThingForLibrariesTabbedView =>
894 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
895
896
897 # Novelist Select
898 if( C4::Context->preference('NovelistSelectEnabled') ) 
899
900 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
901 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
902 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
903
904
905
906 # Babelthèque
907 if ( C4::Context->preference("Babeltheque") ) {
908     $template->param( 
909         Babeltheque => 1,
910         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
911     );
912 }
913
914 # Social Networks
915 if ( C4::Context->preference( "SocialNetworks" ) ) {
916     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
917     $template->param( SocialNetworks => 1 );
918 }
919
920 # Shelf Browser Stuff
921 if (C4::Context->preference("OPACShelfBrowser")) {
922     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
923     if (defined($starting_itemnumber)) {
924         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
925         my $nearby = GetNearbyItems($starting_itemnumber,3);
926
927         $template->param(
928             starting_homebranch => $nearby->{starting_homebranch}->{description},
929             starting_location => $nearby->{starting_location}->{description},
930             starting_ccode => $nearby->{starting_ccode}->{description},
931             starting_itemnumber => $nearby->{starting_itemnumber},
932             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
933             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
934             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
935             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
936             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
937             NEXT_SHELF_BROWSE => $nearby->{next},
938         );
939
940         # in which tab shelf browser should open ?
941         if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) {
942             $template->param(shelfbrowser_tab => 'holdings');
943         } else {
944             $template->param(shelfbrowser_tab => 'otherholdings');
945         }
946     }
947 }
948
949 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
950
951 if (C4::Context->preference("BakerTaylorEnabled")) {
952         $template->param(
953                 BakerTaylorEnabled  => 1,
954                 BakerTaylorImageURL => &image_url(),
955                 BakerTaylorLinkURL  => &link_url(),
956                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
957         );
958         my ($bt_user, $bt_pass);
959         if ($isbn and
960                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
961                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
962         {
963                 $template->param(
964                 BakerTaylorContentURL   =>
965                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
966                                 $bt_user,$bt_pass,$isbn)
967                 );
968         }
969 }
970
971 my $tag_quantity;
972 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
973         $template->param(
974                 TagsEnabled => 1,
975                 TagsShowOnDetail => $tag_quantity,
976                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
977         );
978         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
979                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
980 }
981
982 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
983     # These values are going to be read by Javascript, at least in the case
984     # of the google covers
985     $template->param(covernewwindow => 'true');
986 } else {
987     $template->param(covernewwindow => 'false');
988 }
989
990 #Export options
991 my $OpacExportOptions=C4::Context->preference("OpacExportOptions");
992 my @export_options = split(/\|/,$OpacExportOptions);
993 $template->{VARS}->{'export_options'} = \@export_options;
994
995 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
996     my $rating = GetRating( $biblionumber, $borrowernumber );
997     $template->param(
998         rating_value   => $rating->{'rating_value'},
999         rating_total   => $rating->{'rating_total'},
1000         rating_avg     => $rating->{'rating_avg'},
1001         rating_avg_int => $rating->{'rating_avg_int'},
1002         borrowernumber => $borrowernumber
1003     );
1004 }
1005
1006 #Search for title in links
1007 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
1008 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1009 my $issn = $marcissns->[0] || '';
1010
1011 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1012     $dat->{title} =~ s/\/+$//; # remove trailing slash
1013     $dat->{title} =~ s/\s+$//; # remove trailing space
1014     $search_for_title = parametrized_url(
1015         $search_for_title,
1016         {
1017             TITLE         => $dat->{title},
1018             AUTHOR        => $dat->{author},
1019             ISBN          => $isbn,
1020             ISSN          => $issn,
1021             CONTROLNUMBER => $marccontrolnumber,
1022             BIBLIONUMBER  => $biblionumber,
1023         }
1024     );
1025     $template->param('OPACSearchForTitleIn' => $search_for_title);
1026 }
1027
1028 # We try to select the best default tab to show, according to what
1029 # the user wants, and what's available for display
1030 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1031 my $defaulttab = 
1032     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1033         ? 'subscriptions' :
1034     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1035         ? 'serialcollection' :
1036     $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1037         ? 'holdings' :
1038     $subscriptionsnumber
1039         ? 'subscriptions' :
1040     @serialcollections > 0 
1041         ? 'serialcollection' : 'subscriptions';
1042 $template->param('defaulttab' => $defaulttab);
1043
1044 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1045     my @images = ListImagesForBiblio($biblionumber);
1046     $template->{VARS}->{localimages} = \@images;
1047 }
1048
1049 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1050 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1051 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1052 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1053
1054 if (C4::Context->preference('OpacHighlightedWords')) {
1055     $template->{VARS}->{query_desc} = $query->param('query_desc');
1056 }
1057 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1058
1059 if ( C4::Context->preference('UseCourseReserves') ) {
1060     foreach my $i ( @items ) {
1061         $i->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $i->{'itemnumber'} );
1062     }
1063 }
1064
1065 output_html_with_http_headers $query, $cookie, $template->output;