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