Bug 9903 - Sort by date broken on patron detail page
[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 = C4::Context->userenv->{branch};
446 if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
447     if (
448         ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
449         ||
450         C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
451     ) {
452         my $branchname;
453         if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
454             $branchname = $branches->{$branch}->{'branchname'};
455         }
456         elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
457             $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
458         }
459
460         my @our_items;
461         my @other_items;
462
463         foreach my $item ( @items ) {
464            if ( $item->{'branchname'} eq $branchname ) {
465                $item->{'this_branch'} = 1;
466                push( @our_items, $item );
467            } else {
468                push( @other_items, $item );
469            }
470         }
471
472         @items = ( @our_items, @other_items );
473     }
474 }
475
476 my $dat = &GetBiblioData($biblionumber);
477
478 my $itemtypes = GetItemTypes();
479 # imageurl:
480 my $itemtype = $dat->{'itemtype'};
481 if ( $itemtype ) {
482     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
483     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
484 }
485 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'}, 'opac');
486 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'}, 'opac');
487 my $copynumbers = GetKohaAuthorisedValues('items.copynumber',$dat->{'frameworkcode'}, 'opac');
488
489 #coping with subscriptions
490 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
491 my @subscriptions       = GetSubscriptions($dat->{'title'}, $dat->{'issn'}, $ean, $biblionumber );
492
493 my @subs;
494 $dat->{'serial'}=1 if $subscriptionsnumber;
495 foreach my $subscription (@subscriptions) {
496     my $serials_to_display;
497     my %cell;
498     $cell{subscriptionid}    = $subscription->{subscriptionid};
499     $cell{subscriptionnotes} = $subscription->{notes};
500     $cell{missinglist}       = $subscription->{missinglist};
501     $cell{opacnote}          = $subscription->{opacnote};
502     $cell{histstartdate}     = $subscription->{histstartdate};
503     $cell{histenddate}       = $subscription->{histenddate};
504     $cell{branchcode}        = $subscription->{branchcode};
505     $cell{branchname}        = GetBranchName($subscription->{branchcode});
506     $cell{hasalert}          = $subscription->{hasalert};
507     $cell{callnumber}        = $subscription->{callnumber};
508     $cell{closed}            = $subscription->{closed};
509     #get the three latest serials.
510     $serials_to_display = $subscription->{opacdisplaycount};
511     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
512         $cell{opacdisplaycount} = $serials_to_display;
513     $cell{latestserials} =
514       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
515     push @subs, \%cell;
516 }
517
518 $dat->{'count'} = scalar(@items);
519
520
521 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
522
523 my (%item_reserves, %priority);
524 my ($show_holds_count, $show_priority);
525 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
526     m/holds/o and $show_holds_count = 1;
527     m/priority/ and $show_priority = 1;
528 }
529 my $has_hold;
530 if ( $show_holds_count || $show_priority) {
531     my ($reserve_count,$reserves) = GetReservesFromBiblionumber($biblionumber);
532     $template->param( holds_count  => $reserve_count ) if $show_holds_count;
533     foreach (@$reserves) {
534         $item_reserves{ $_->{itemnumber} }++ if $_->{itemnumber};
535         if ($show_priority && $_->{borrowernumber} == $borrowernumber) {
536             $has_hold = 1;
537             $_->{itemnumber}
538                 ? ($priority{ $_->{itemnumber} } = $_->{priority})
539                 : ($template->param( priority => $_->{priority} ));
540         }
541     }
542 }
543 $template->param( show_priority => $has_hold ) ;
544
545 my $norequests = 1;
546 my %itemfields;
547 my (@itemloop, @otheritemloop);
548 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
549 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
550     $template->param(SeparateHoldings => 1);
551 }
552 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
553 for my $itm (@items) {
554     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
555     $itm->{priority} = $priority{ $itm->{itemnumber} };
556     $norequests = 0
557        if ( (not $itm->{'wthdrawn'} )
558          && (not $itm->{'itemlost'} )
559          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
560                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
561          && ($itm->{'itemnumber'} ) );
562
563     # get collection code description, too
564     my $ccode = $itm->{'ccode'};
565     $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
566     my $copynumber = $itm->{'copynumber'};
567     $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
568     if ( defined $itm->{'location'} ) {
569         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
570     }
571     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
572         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
573         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
574     }
575     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
576         $itemfields{$_} = 1 if ($itm->{$_});
577     }
578
579      # walk through the item-level authorised values and populate some images
580      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
581      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
582
583      if ( $itm->{'itemlost'} ) {
584          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
585          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
586          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
587      }
588      my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
589       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
590       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
591     
592      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
593      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
594         $itm->{transfertwhen} = $transfertwhen;
595         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
596         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
597      }
598     my $itembranch = $itm->{$separatebranch};
599     if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
600         if ($itembranch and $itembranch eq $currentbranch) {
601             push @itemloop, $itm;
602         } else {
603             push @otheritemloop, $itm;
604         }
605     } else {
606         push @itemloop, $itm;
607     }
608 }
609
610 # Display only one tab if one items list is empty
611 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
612     $template->param(SeparateHoldings => 0);
613     if (scalar(@itemloop) == 0) {
614         @itemloop = @otheritemloop;
615     }
616 }
617
618 # If there is a lot of items, and the user has not decided
619 # to view them all yet, we first warn him
620 # TODO: The limit of 50 could be a syspref
621 my $viewallitems = $query->param('viewallitems');
622 if (scalar(@itemloop) >= 50 && !$viewallitems) {
623     $template->param('lotsofitems' => 1);
624 }
625
626 ## get notes and subjects from MARC record
627 my $dbh              = C4::Context->dbh;
628 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
629 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
630 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
631 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
632 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
633 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
634 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
635 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
636
637     $template->param(
638                      MARCNOTES               => $marcnotesarray,
639                      MARCSUBJCTS             => $marcsubjctsarray,
640                      MARCAUTHORS             => $marcauthorsarray,
641                      MARCSERIES              => $marcseriesarray,
642                      MARCURLS                => $marcurlsarray,
643                      MARCISBNS               => $marcisbnsarray,
644                      MARCHOSTS               => $marchostsarray,
645                      norequests              => $norequests,
646                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
647                      itemdata_ccode          => $itemfields{ccode},
648                      itemdata_enumchron      => $itemfields{enumchron},
649                      itemdata_uri            => $itemfields{uri},
650                      itemdata_copynumber     => $itemfields{copynumber},
651                      itemdata_itemnotes          => $itemfields{itemnotes},
652                      authorised_value_images => $biblio_authorised_value_images,
653                      subtitle                => $subtitle,
654                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
655     );
656
657 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
658     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
659     my $subfields = substr $fieldspec, 3;
660     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
661     my @alternateholdingsinfo = ();
662     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
663
664     for my $field (@holdingsfields) {
665         my %holding = ( holding => '' );
666         my $havesubfield = 0;
667         for my $subfield ($field->subfields()) {
668             if ((index $subfields, $$subfield[0]) >= 0) {
669                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
670                 $holding{'holding'} .= $$subfield[1];
671                 $havesubfield++;
672             }
673         }
674         if ($havesubfield) {
675             push(@alternateholdingsinfo, \%holding);
676         }
677     }
678
679     $template->param(
680         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
681         );
682 }
683
684 foreach ( keys %{$dat} ) {
685     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
686 }
687
688 # some useful variables for enhanced content;
689 # in each case, we're grabbing the first value we find in
690 # the record and normalizing it
691 my $upc = GetNormalizedUPC($record,$marcflavour);
692 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
693 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
694 my $content_identifier_exists;
695 if ( $isbn or $ean or $oclc or $upc ) {
696     $content_identifier_exists = 1;
697 }
698 $template->param(
699         normalized_upc => $upc,
700         normalized_ean => $ean,
701         normalized_oclc => $oclc,
702         normalized_isbn => $isbn,
703         content_identifier_exists =>  $content_identifier_exists,
704 );
705
706 # COinS format FIXME: for books Only
707 $template->param(
708     ocoins => GetCOinSBiblio($record),
709 );
710
711 my $libravatar_enabled = 0;
712 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) {
713     eval {
714         require Libravatar::URL;
715         Libravatar::URL->import();
716     };
717     if (!$@ ) {
718         $libravatar_enabled = 1;
719     }
720 }
721
722 my $reviews = getreviews( $biblionumber, 1 );
723 my $loggedincommenter;
724
725
726
727
728 foreach ( @$reviews ) {
729     my $borrowerData   = GetMember('borrowernumber' => $_->{borrowernumber});
730     # setting some borrower info into this hash
731     $_->{title}     = $borrowerData->{'title'};
732     $_->{surname}   = $borrowerData->{'surname'};
733     $_->{firstname} = $borrowerData->{'firstname'};
734     if ($libravatar_enabled and $borrowerData->{'email'}) {
735         $_->{avatarurl} = libravatar_url(email => $borrowerData->{'email'}, https => $ENV{HTTPS});
736     }
737     $_->{userid}    = $borrowerData->{'userid'};
738     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
739
740     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
741                 $_->{your_comment} = 1;
742                 $loggedincommenter = 1;
743         }
744 }
745
746
747 if(C4::Context->preference("ISBD")) {
748         $template->param(ISBD => 1);
749 }
750
751 $template->param(
752     itemloop            => \@itemloop,
753     otheritemloop       => \@otheritemloop,
754     subscriptionsnumber => $subscriptionsnumber,
755     biblionumber        => $biblionumber,
756     subscriptions       => \@subs,
757     subscriptionsnumber => $subscriptionsnumber,
758     reviews             => $reviews,
759     loggedincommenter   => $loggedincommenter
760 );
761
762 # Lists
763
764 if (C4::Context->preference("virtualshelves") ) {
765    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
766 }
767
768
769 # XISBN Stuff
770 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
771     eval {
772         $template->param(
773             XISBNS => get_xisbns($isbn)
774         );
775     };
776     if ($@) { warn "XISBN Failed $@"; }
777 }
778
779 # Serial Collection
780 my @sc_fields = $record->field(955);
781 my @lc_fields = $marcflavour eq 'UNIMARC'
782     ? $record->field(930)
783     : $record->field(852);
784 my @serialcollections = ();
785
786 foreach my $sc_field (@sc_fields) {
787     my %row_data;
788
789     $row_data{text}    = $sc_field->subfield('r');
790     $row_data{branch}  = $sc_field->subfield('9');
791     foreach my $lc_field (@lc_fields) {
792         $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
793             ? $lc_field->subfield('a') # 930$a
794             : $lc_field->subfield('h') # 852$h
795             if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
796     }
797
798     if ($row_data{text} && $row_data{branch}) { 
799         push (@serialcollections, \%row_data);
800     }
801 }
802
803 if (scalar(@serialcollections) > 0) {
804     $template->param(
805         serialcollection  => 1,
806         serialcollections => \@serialcollections);
807 }
808
809 # Local cover Images stuff
810 if (C4::Context->preference("OPACLocalCoverImages")){
811                 $template->param(OPACLocalCoverImages => 1);
812 }
813
814 # HTML5 Media
815 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
816     $template->param( C4::HTML5Media->gethtml5media($record));
817 }
818
819 my $syndetics_elements;
820
821 if ( C4::Context->preference("SyndeticsEnabled") ) {
822     $template->param("SyndeticsEnabled" => 1);
823     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
824         eval {
825             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
826             for my $element (values %$syndetics_elements) {
827                 $template->param("Syndetics$element"."Exists" => 1 );
828                 #warn "Exists: "."Syndetics$element"."Exists";
829         }
830     };
831     warn $@ if $@;
832 }
833
834 if ( C4::Context->preference("SyndeticsEnabled")
835         && C4::Context->preference("SyndeticsSummary")
836         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
837         eval {
838             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
839             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
840         };
841         warn $@ if $@;
842
843 }
844
845 if ( C4::Context->preference("SyndeticsEnabled")
846         && C4::Context->preference("SyndeticsTOC")
847         && exists($syndetics_elements->{'TOC'}) ) {
848         eval {
849     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
850     $template->param( SYNDETICS_TOC => $syndetics_toc );
851         };
852         warn $@ if $@;
853 }
854
855 if ( C4::Context->preference("SyndeticsEnabled")
856     && C4::Context->preference("SyndeticsExcerpt")
857     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
858     eval {
859     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
860     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
861     };
862         warn $@ if $@;
863 }
864
865 if ( C4::Context->preference("SyndeticsEnabled")
866     && C4::Context->preference("SyndeticsReviews")) {
867     eval {
868     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
869     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
870     };
871         warn $@ if $@;
872 }
873
874 if ( C4::Context->preference("SyndeticsEnabled")
875     && C4::Context->preference("SyndeticsAuthorNotes")
876         && exists($syndetics_elements->{'ANOTES'}) ) {
877     eval {
878     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
879     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
880     };
881     warn $@ if $@;
882 }
883
884 # LibraryThingForLibraries ID Code and Tabbed View Option
885 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
886
887 $template->param(LibraryThingForLibrariesID =>
888 C4::Context->preference('LibraryThingForLibrariesID') ); 
889 $template->param(LibraryThingForLibrariesTabbedView =>
890 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
891
892
893 # Novelist Select
894 if( C4::Context->preference('NovelistSelectEnabled') ) 
895
896 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
897 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
898 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
899
900
901
902 # Babelthèque
903 if ( C4::Context->preference("Babeltheque") ) {
904     $template->param( 
905         Babeltheque => 1,
906         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
907     );
908 }
909
910 # Social Networks
911 if ( C4::Context->preference( "SocialNetworks" ) ) {
912     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
913     $template->param( SocialNetworks => 1 );
914 }
915
916 # Shelf Browser Stuff
917 if (C4::Context->preference("OPACShelfBrowser")) {
918     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
919     if (defined($starting_itemnumber)) {
920         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
921         my $nearby = GetNearbyItems($starting_itemnumber,3);
922
923         $template->param(
924             starting_homebranch => $nearby->{starting_homebranch}->{description},
925             starting_location => $nearby->{starting_location}->{description},
926             starting_ccode => $nearby->{starting_ccode}->{description},
927             starting_itemnumber => $nearby->{starting_itemnumber},
928             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
929             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
930             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
931             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
932             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
933             NEXT_SHELF_BROWSE => $nearby->{next},
934         );
935
936         # in which tab shelf browser should open ?
937         if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) {
938             $template->param(shelfbrowser_tab => 'holdings');
939         } else {
940             $template->param(shelfbrowser_tab => 'otherholdings');
941         }
942     }
943 }
944
945 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
946
947 if (C4::Context->preference("BakerTaylorEnabled")) {
948         $template->param(
949                 BakerTaylorEnabled  => 1,
950                 BakerTaylorImageURL => &image_url(),
951                 BakerTaylorLinkURL  => &link_url(),
952                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
953         );
954         my ($bt_user, $bt_pass);
955         if ($isbn and
956                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
957                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
958         {
959                 $template->param(
960                 BakerTaylorContentURL   =>
961                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
962                                 $bt_user,$bt_pass,$isbn)
963                 );
964         }
965 }
966
967 my $tag_quantity;
968 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
969         $template->param(
970                 TagsEnabled => 1,
971                 TagsShowOnDetail => $tag_quantity,
972                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
973         );
974         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
975                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
976 }
977
978 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
979     # These values are going to be read by Javascript, at least in the case
980     # of the google covers
981     $template->param(covernewwindow => 'true');
982 } else {
983     $template->param(covernewwindow => 'false');
984 }
985
986 #Export options
987 my $OpacExportOptions=C4::Context->preference("OpacExportOptions");
988 my @export_options = split(/\|/,$OpacExportOptions);
989 $template->{VARS}->{'export_options'} = \@export_options;
990
991 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
992     my $rating = GetRating( $biblionumber, $borrowernumber );
993     $template->param(
994         rating_value   => $rating->{'rating_value'},
995         rating_total   => $rating->{'rating_total'},
996         rating_avg     => $rating->{'rating_avg'},
997         rating_avg_int => $rating->{'rating_avg_int'},
998         borrowernumber => $borrowernumber
999     );
1000 }
1001
1002 #Search for title in links
1003 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
1004 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1005 my $issn = $marcissns->[0] || '';
1006
1007 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1008     $dat->{title} =~ s/\/+$//; # remove trailing slash
1009     $dat->{title} =~ s/\s+$//; # remove trailing space
1010     $search_for_title = parametrized_url(
1011         $search_for_title,
1012         {
1013             TITLE         => $dat->{title},
1014             AUTHOR        => $dat->{author},
1015             ISBN          => $isbn,
1016             ISSN          => $issn,
1017             CONTROLNUMBER => $marccontrolnumber,
1018             BIBLIONUMBER  => $biblionumber,
1019         }
1020     );
1021     $template->param('OPACSearchForTitleIn' => $search_for_title);
1022 }
1023
1024 # We try to select the best default tab to show, according to what
1025 # the user wants, and what's available for display
1026 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1027 my $defaulttab = 
1028     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1029         ? 'subscriptions' :
1030     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1031         ? 'serialcollection' :
1032     $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1033         ? 'holdings' :
1034     $subscriptionsnumber
1035         ? 'subscriptions' :
1036     @serialcollections > 0 
1037         ? 'serialcollection' : 'subscriptions';
1038 $template->param('defaulttab' => $defaulttab);
1039
1040 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1041     my @images = ListImagesForBiblio($biblionumber);
1042     $template->{VARS}->{localimages} = \@images;
1043 }
1044
1045 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1046 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1047 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1048 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1049
1050 if (C4::Context->preference('OpacHighlightedWords')) {
1051     $template->{VARS}->{query_desc} = $query->param('query_desc');
1052 }
1053 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1054
1055 output_html_with_http_headers $query, $cookie, $template->output;