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