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