Updated the release notes
[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             @newresults = searchResults('opac', '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
157         }
158         return \@newresults;
159     }#searchAgain
160
161     # Build the current list of biblionumbers in this search
162     sub buildListBiblios
163     {
164         my ($newresultsRef, $results_per_page) = @_;
165
166         my $listBiblios = '';
167         my $j = 0;
168         foreach (@$newresultsRef) {
169             my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
170             $listBiblios .= $bibnum . ',';
171             $j++;
172             last if ($j == $results_per_page);
173         }
174         chop $listBiblios if ($listBiblios =~ /,$/);
175         return $listBiblios;
176     }#buildListBiblios
177
178     my $busc = $session->param("busc");
179     my @arrBusc = split(/\&(?:amp;)?/, $busc);
180     my ($key, $value);
181     my %arrParamsBusc = ();
182     for (@arrBusc) {
183         ($key, $value) = split(/=/, $_, 2);
184         if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
185             $arrParamsBusc{$key} = $value;
186         } else {
187             unless (exists($arrParamsBusc{$key})) {
188                 $arrParamsBusc{$key} = [];
189             }
190             push @{$arrParamsBusc{$key}}, $value;
191         }
192     }
193     my $searchAgain = 0;
194     my $count = C4::Context->preference('OPACnumSearchResults') || 20;
195     my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
196     $arrParamsBusc{'count'} = $results_per_page;
197     my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
198     # The value OPACnumSearchResults has changed and the search has to be rebuild
199     if ($count != $results_per_page) {
200         if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
201             my $indexBiblio = 0;
202             my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
203             for (@arrBibliosAux) {
204                 last if ($_ == $biblionumber);
205                 $indexBiblio++;
206             }
207             $indexBiblio += $offset;
208             $offset = int($indexBiblio / $count) * $count;
209             $arrParamsBusc{'offset'} = $offset;
210         }
211         $arrParamsBusc{'count'} = $count;
212         $results_per_page = $count;
213         my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page);
214         $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
215         delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
216         delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
217         delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
218         delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
219         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
220         $session->param("busc" => $newbusc);
221         @arrBusc = split(/\&(?:amp;)?/, $newbusc);
222     } else {
223         my $modifyListBiblios = 0;
224         # We come from a previous click
225         if (exists($arrParamsBusc{'previous'})) {
226             $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
227             delete $arrParamsBusc{'previous'};
228         } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
229             $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
230             delete $arrParamsBusc{'next'};
231         }
232         if ($modifyListBiblios) {
233             if (exists($arrParamsBusc{'newlistBiblios'})) {
234                 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
235                 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
236                 my @arrAux = split(',', $listBibliosAux);
237                 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
238                 if ($modifyListBiblios == 1) {
239                     $arrParamsBusc{'next'} = $arrAux[0];
240                     $paging{'next'}->{biblionumber} = $arrAux[0];
241                 }else {
242                     $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
243                     $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
244                 }
245             } else {
246                 delete $arrParamsBusc{'listBiblios'};
247             }
248             my $offsetAux = $arrParamsBusc{'offset'};
249             $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
250             $arrParamsBusc{'offsetSearch'} = $offsetAux;
251             $offset = $arrParamsBusc{'offset'};
252             my $newbusc = rebuildBuscParam(\%arrParamsBusc);
253             $session->param("busc" => $newbusc);
254             @arrBusc = split(/\&(?:amp;)?/, $newbusc);
255         }
256     }
257     my $buscParam = '';
258     my $j = 0;
259     # Rebuild the query for the button "back to results"
260     for (@arrBusc) {
261         unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
262             $buscParam .= '&amp;' unless ($j == 0);
263             $buscParam .= $_;
264             $j++;
265         }
266     }
267     $template->param('busc' => $buscParam);
268     my $offsetSearch;
269     my @arrBiblios;
270     # We are inside the list of biblios and we don't have to search
271     if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
272         @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
273         if (@arrBiblios) {
274             # We are at the first item of the list
275             if ($arrBiblios[0] == $biblionumber) {
276                 if (@arrBiblios > 1) {
277                     for (my $j = 1; $j < @arrBiblios; $j++) {
278                         next unless ($arrBiblios[$j]);
279                         $paging{'next'}->{biblionumber} = $arrBiblios[$j];
280                         last;
281                     }
282                 }
283                 # search again if we are not at the first searching list
284                 if ($offset && !$arrParamsBusc{'previous'}) {
285                     $searchAgain = 1;
286                     $offsetSearch = $offset - $results_per_page;
287                 }
288             # we are at the last item of the list
289             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
290                 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
291                     next unless ($arrBiblios[$j]);
292                     $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
293                     last;
294                 }
295                 if (!$offset) {
296                     # search again if we are at the first list and there is more results
297                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
298                 } else {
299                     # search again if we aren't at the first list and there is more results
300                     $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
301                 }
302                 $offsetSearch = $offset + $results_per_page if ($searchAgain);
303             } else {
304                 for (my $j = 1; $j < $#arrBiblios; $j++) {
305                     if ($arrBiblios[$j] == $biblionumber) {
306                         for (my $z = $j - 1; $z >= 0; $z--) {
307                             next unless ($arrBiblios[$z]);
308                             $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
309                             last;
310                         }
311                         for (my $z = $j + 1; $z < @arrBiblios; $z++) {
312                             next unless ($arrBiblios[$z]);
313                             $paging{'next'}->{biblionumber} = $arrBiblios[$z];
314                             last;
315                         }
316                         last;
317                     }
318                 }
319             }
320         }
321         $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
322     }
323     if ($searchAgain) {
324         my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page);
325         my @newresults = @$newresultsRef;
326         # build the new listBiblios
327         my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
328         unless (exists($arrParamsBusc{'listBiblios'})) {
329             $arrParamsBusc{'listBiblios'} = $listBiblios;
330             @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
331         } else {
332             $arrParamsBusc{'newlistBiblios'} = $listBiblios;
333         }
334         # From the new list we build again the next and previous result
335         if (@arrBiblios) {
336             if ($arrBiblios[0] == $biblionumber) {
337                 for (my $j = $#newresults; $j >= 0; $j--) {
338                     next unless ($newresults[$j]);
339                     $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
340                     $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
341                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
342                    last;
343                 }
344             } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
345                 for (my $j = 0; $j < @newresults; $j++) {
346                     next unless ($newresults[$j]);
347                     $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
348                     $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
349                     $arrParamsBusc{'offsetSearch'} = $offsetSearch;
350                     last;
351                 }
352             }
353         }
354         # build new busc param
355         my $newbusc = rebuildBuscParam(\%arrParamsBusc);
356         $session->param("busc" => $newbusc);
357     }
358     my ($previous, $next, $dataBiblioPaging);
359     # Previous biblio
360     if ($paging{'previous'}->{biblionumber}) {
361         $previous = 'opac-detail.pl?biblionumber=' . $paging{'previous'}->{biblionumber};
362         $dataBiblioPaging = GetBiblioData($paging{'previous'}->{biblionumber});
363         $template->param('previousTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
364     }
365     # Next biblio
366     if ($paging{'next'}->{biblionumber}) {
367         $next = 'opac-detail.pl?biblionumber=' . $paging{'next'}->{biblionumber};
368         $dataBiblioPaging = GetBiblioData($paging{'next'}->{biblionumber});
369         $template->param('nextTitle' => $dataBiblioPaging->{'title'}) if ($dataBiblioPaging);
370     }
371     $template->param('previous' => $previous, 'next' => $next);
372     # Partial list of biblio results
373     my @listResults;
374     for (my $j = 0; $j < @arrBiblios; $j++) {
375         next unless ($arrBiblios[$j]);
376         $dataBiblioPaging = GetBiblioData($arrBiblios[$j]) if ($arrBiblios[$j] != $biblionumber);
377         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]};
378     }
379     $template->param('listResults' => \@listResults) if (@listResults);
380     $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
381 }
382 }
383
384
385
386 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
387 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
388
389
390
391 $template->param('OPACShowCheckoutName' => C4::Context->preference("OPACShowCheckoutName") ); 
392 # change back when ive fixed request.pl
393 my @all_items = GetItemsInfo( $biblionumber );
394
395 # adding items linked via host biblios
396 my $marcflavour  = C4::Context->preference("marcflavour");
397
398 my $analyticfield = '773';
399 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
400     $analyticfield = '773';
401 } elsif ($marcflavour eq 'UNIMARC') {
402     $analyticfield = '461';
403 }
404 foreach my $hostfield ( $record->field($analyticfield)) {
405     my $hostbiblionumber = $hostfield->subfield("0");
406     my $linkeditemnumber = $hostfield->subfield("9");
407     my @hostitemInfos = GetItemsInfo($hostbiblionumber);
408     foreach my $hostitemInfo (@hostitemInfos){
409         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
410             push(@all_items, $hostitemInfo);
411         }
412     }
413 }
414
415 my @items;
416
417 # Getting items to be hidden
418 my @hiddenitems = GetHiddenItemnumbers(@all_items);
419
420 # Are there items to hide?
421 my $hideitems = 1 if C4::Context->preference('hidelostitems') or scalar(@hiddenitems) > 0;
422
423 # Hide items
424 if ($hideitems) {
425     for my $itm (@all_items) {
426         if  ( C4::Context->preference('hidelostitems') ) {
427             push @items, $itm unless $itm->{itemlost} or any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
428         } else {
429             push @items, $itm unless any { $itm->{'itemnumber'} eq $_ } @hiddenitems;
430     }
431 }
432 } else {
433     # Or not
434     @items = @all_items;
435 }
436
437 my $dat = &GetBiblioData($biblionumber);
438
439 my $itemtypes = GetItemTypes();
440 # imageurl:
441 my $itemtype = $dat->{'itemtype'};
442 if ( $itemtype ) {
443     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
444     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
445 }
446 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'}, 'opac');
447 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'}, 'opac');
448
449 #coping with subscriptions
450 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
451 my @subscriptions       = GetSubscriptions( undef, undef, $biblionumber );
452
453 my @subs;
454 $dat->{'serial'}=1 if $subscriptionsnumber;
455 foreach my $subscription (@subscriptions) {
456     my $serials_to_display;
457     my %cell;
458     $cell{subscriptionid}    = $subscription->{subscriptionid};
459     $cell{subscriptionnotes} = $subscription->{notes};
460     $cell{missinglist}       = $subscription->{missinglist};
461     $cell{opacnote}          = $subscription->{opacnote};
462     $cell{histstartdate}     = $subscription->{histstartdate};
463     $cell{histenddate}       = $subscription->{histenddate};
464     $cell{branchcode}        = $subscription->{branchcode};
465     $cell{branchname}        = GetBranchName($subscription->{branchcode});
466     $cell{hasalert}          = $subscription->{hasalert};
467     #get the three latest serials.
468     $serials_to_display = $subscription->{opacdisplaycount};
469     $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
470         $cell{opacdisplaycount} = $serials_to_display;
471     $cell{latestserials} =
472       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
473     push @subs, \%cell;
474 }
475
476 $dat->{'count'} = scalar(@items);
477
478 # If there is a lot of items, and the user has not decided
479 # to view them all yet, we first warn him
480 # TODO: The limit of 50 could be a syspref
481 my $viewallitems = $query->param('viewallitems');
482 if ($dat->{'count'} >= 50 && !$viewallitems) {
483     $template->param('lotsofitems' => 1);
484 }
485
486 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
487
488 my $norequests = 1;
489 my $branches = GetBranches();
490 my %itemfields;
491 for my $itm (@items) {
492     $norequests = 0
493        if ( (not $itm->{'wthdrawn'} )
494          && (not $itm->{'itemlost'} )
495          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
496                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
497          && ($itm->{'itemnumber'} ) );
498
499     if ( defined $itm->{'publictype'} ) {
500         # I can't actually find any case in which this is defined. --amoore 2008-12-09
501         $itm->{ $itm->{'publictype'} } = 1;
502     }
503
504     # get collection code description, too
505     if ( my $ccode = $itm->{'ccode'} ) {
506         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
507     }
508     if ( defined $itm->{'location'} ) {
509         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
510     }
511     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
512         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
513         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
514     }
515     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
516         $itemfields{$_} = 1 if ($itm->{$_});
517     }
518
519      # walk through the item-level authorised values and populate some images
520      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
521      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
522
523      if ( $itm->{'itemlost'} ) {
524          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
525          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
526          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
527      }
528      my ($reserve_status) = C4::Reserves::CheckReserves($itm->{itemnumber});
529       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
530       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
531     
532      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
533      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
534         $itm->{transfertwhen} = $transfertwhen;
535         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
536         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
537      }
538 }
539
540 ## get notes and subjects from MARC record
541 my $dbh              = C4::Context->dbh;
542 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
543 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
544 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
545 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
546 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
547 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
548 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
549 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
550
551     $template->param(
552                      MARCNOTES               => $marcnotesarray,
553                      MARCSUBJCTS             => $marcsubjctsarray,
554                      MARCAUTHORS             => $marcauthorsarray,
555                      MARCSERIES              => $marcseriesarray,
556                      MARCURLS                => $marcurlsarray,
557                      MARCISBNS               => $marcisbnsarray,
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
655     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
656                 $_->{your_comment} = 1;
657                 $loggedincommenter = 1;
658         }
659 }
660
661
662 if(C4::Context->preference("ISBD")) {
663         $template->param(ISBD => 1);
664 }
665
666 $template->param(
667     ITEM_RESULTS        => \@items,
668     subscriptionsnumber => $subscriptionsnumber,
669     biblionumber        => $biblionumber,
670     subscriptions       => \@subs,
671     subscriptionsnumber => $subscriptionsnumber,
672     reviews             => $reviews,
673     loggedincommenter   => $loggedincommenter
674 );
675
676 # Lists
677
678 if (C4::Context->preference("virtualshelves") ) {
679    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
680 }
681
682
683 # XISBN Stuff
684 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
685     eval {
686         $template->param(
687             XISBNS => get_xisbns($isbn)
688         );
689     };
690     if ($@) { warn "XISBN Failed $@"; }
691 }
692
693 # Serial Collection
694 my @sc_fields = $record->field(955);
695 my @serialcollections = ();
696
697 foreach my $sc_field (@sc_fields) {
698     my %row_data;
699
700     $row_data{text}    = $sc_field->subfield('r');
701     $row_data{branch}  = $sc_field->subfield('9');
702
703     if ($row_data{text} && $row_data{branch}) { 
704         push (@serialcollections, \%row_data);
705     }
706 }
707
708 if (scalar(@serialcollections) > 0) {
709     $template->param(
710         serialcollection  => 1,
711         serialcollections => \@serialcollections);
712 }
713
714 # Local cover Images stuff
715 if (C4::Context->preference("OPACLocalCoverImages")){
716                 $template->param(OPACLocalCoverImages => 1);
717 }
718
719 # Amazon.com Stuff
720 if ( C4::Context->preference("OPACAmazonEnabled") ) {
721     $template->param( AmazonTld => get_amazon_tld() );
722     my $amazon_reviews  = C4::Context->preference("OPACAmazonReviews");
723     my $amazon_similars = C4::Context->preference("OPACAmazonSimilarItems");
724     my @services;
725     if ( $amazon_reviews ) {
726         push( @services, 'EditorialReview', 'Reviews' );
727     }
728     if ( $amazon_similars ) {
729         push( @services, 'Similarities' );
730     }
731     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
732     my $similar_products_exist;
733     if ( $amazon_reviews ) {
734         my $item = $amazon_details->{Items}->{Item}->[0];
735         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
736         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
737         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
738         $template->param( amazon_average_rating    => $average_rating * 20);
739         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
740         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
741     }
742     if ( $amazon_similars ) {
743         my $item = $amazon_details->{Items}->{Item}->[0];
744         my @similar_products;
745         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
746             # do we have any of these isbns in our collection?
747             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
748             # verify that there is at least one similar item
749             if (scalar(@$similar_biblionumbers)){
750                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
751                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
752             }
753         }
754         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
755         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
756     }
757 }
758
759 my $syndetics_elements;
760
761 if ( C4::Context->preference("SyndeticsEnabled") ) {
762     $template->param("SyndeticsEnabled" => 1);
763     $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
764         eval {
765             $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
766             for my $element (values %$syndetics_elements) {
767                 $template->param("Syndetics$element"."Exists" => 1 );
768                 #warn "Exists: "."Syndetics$element"."Exists";
769         }
770     };
771     warn $@ if $@;
772 }
773
774 if ( C4::Context->preference("SyndeticsEnabled")
775         && C4::Context->preference("SyndeticsSummary")
776         && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
777         eval {
778             my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
779             $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
780         };
781         warn $@ if $@;
782
783 }
784
785 if ( C4::Context->preference("SyndeticsEnabled")
786         && C4::Context->preference("SyndeticsTOC")
787         && exists($syndetics_elements->{'TOC'}) ) {
788         eval {
789     my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
790     $template->param( SYNDETICS_TOC => $syndetics_toc );
791         };
792         warn $@ if $@;
793 }
794
795 if ( C4::Context->preference("SyndeticsEnabled")
796     && C4::Context->preference("SyndeticsExcerpt")
797     && exists($syndetics_elements->{'DBCHAPTER'}) ) {
798     eval {
799     my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
800     $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
801     };
802         warn $@ if $@;
803 }
804
805 if ( C4::Context->preference("SyndeticsEnabled")
806     && C4::Context->preference("SyndeticsReviews")) {
807     eval {
808     my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
809     $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
810     };
811         warn $@ if $@;
812 }
813
814 if ( C4::Context->preference("SyndeticsEnabled")
815     && C4::Context->preference("SyndeticsAuthorNotes")
816         && exists($syndetics_elements->{'ANOTES'}) ) {
817     eval {
818     my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
819     $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
820     };
821     warn $@ if $@;
822 }
823
824 # LibraryThingForLibraries ID Code and Tabbed View Option
825 if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) 
826
827 $template->param(LibraryThingForLibrariesID =>
828 C4::Context->preference('LibraryThingForLibrariesID') ); 
829 $template->param(LibraryThingForLibrariesTabbedView =>
830 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
831
832
833 # Novelist Select
834 if( C4::Context->preference('NovelistSelectEnabled') ) 
835
836 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); 
837 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); 
838 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); 
839
840
841
842 # Babelthèque
843 if ( C4::Context->preference("Babeltheque") ) {
844     $template->param( 
845         Babeltheque => 1,
846         Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
847     );
848 }
849
850 # Social Networks
851 if ( C4::Context->preference( "SocialNetworks" ) ) {
852     $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
853     $template->param( SocialNetworks => 1 );
854 }
855
856 # Shelf Browser Stuff
857 if (C4::Context->preference("OPACShelfBrowser")) {
858     # pick the first itemnumber unless one was selected by the user
859     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
860     if (defined($starting_itemnumber)) {
861         $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
862         my $nearby = GetNearbyItems($starting_itemnumber,3);
863
864         $template->param(
865             starting_homebranch => $nearby->{starting_homebranch}->{description},
866             starting_location => $nearby->{starting_location}->{description},
867             starting_ccode => $nearby->{starting_ccode}->{description},
868             starting_itemnumber => $nearby->{starting_itemnumber},
869             shelfbrowser_prev_itemnumber => $nearby->{prev_itemnumber},
870             shelfbrowser_next_itemnumber => $nearby->{next_itemnumber},
871             shelfbrowser_prev_biblionumber => $nearby->{prev_biblionumber},
872             shelfbrowser_next_biblionumber => $nearby->{next_biblionumber},
873             PREVIOUS_SHELF_BROWSE => $nearby->{prev},
874             NEXT_SHELF_BROWSE => $nearby->{next},
875         );
876     }
877 }
878
879 if (C4::Context->preference("BakerTaylorEnabled")) {
880         $template->param(
881                 BakerTaylorEnabled  => 1,
882                 BakerTaylorImageURL => &image_url(),
883                 BakerTaylorLinkURL  => &link_url(),
884                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
885         );
886         my ($bt_user, $bt_pass);
887         if ($isbn and
888                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
889                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
890         {
891                 $template->param(
892                 BakerTaylorContentURL   =>
893                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
894                                 $bt_user,$bt_pass,$isbn)
895                 );
896         }
897 }
898
899 my $tag_quantity;
900 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
901         $template->param(
902                 TagsEnabled => 1,
903                 TagsShowOnDetail => $tag_quantity,
904                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
905         );
906         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
907                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
908 }
909
910 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
911     # These values are going to be read by Javascript, at least in the case
912     # of the google covers
913     $template->param(covernewwindow => 'true');
914 } else {
915     $template->param(covernewwindow => 'false');
916 }
917
918 #Export options
919 my $OpacExportOptions=C4::Context->preference("OpacExportOptions");
920 my @export_options = split(/\|/,$OpacExportOptions);
921 $template->{VARS}->{'export_options'} = \@export_options;
922
923 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
924     my $rating = GetRating( $biblionumber, $borrowernumber );
925     $template->param(
926         rating_value   => $rating->{'rating_value'},
927         rating_total   => $rating->{'rating_total'},
928         rating_avg     => $rating->{'rating_avg'},
929         rating_avg_int => $rating->{'rating_avg_int'},
930         borrowernumber => $borrowernumber
931     );
932 }
933
934 #Search for title in links
935 my $marccontrolnumber   = GetMarcControlnumber ($record, $marcflavour);
936 my $marcissns = GetMarcISSN ( $record, $marcflavour );
937 my $issn = $marcissns->[0] || '';
938
939 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
940     $dat->{author} ? $search_for_title =~ s/{AUTHOR}/$dat->{author}/g : $search_for_title =~ s/{AUTHOR}//g;
941     $dat->{title} =~ s/\/+$//; # remove trailing slash
942     $dat->{title} =~ s/\s+$//; # remove trailing space
943     $dat->{title} ? $search_for_title =~ s/{TITLE}/$dat->{title}/g : $search_for_title =~ s/{TITLE}//g;
944     $isbn ? $search_for_title =~ s/{ISBN}/$isbn/g : $search_for_title =~ s/{ISBN}//g;
945     $issn ? $search_for_title =~ s/{ISSN}/$issn/g : $search_for_title =~ s/{ISSN}//g;
946     $marccontrolnumber ? $search_for_title =~ s/{CONTROLNUMBER}/$marccontrolnumber/g : $search_for_title =~ s/{CONTROLNUMBER}//g;
947     $search_for_title =~ s/{BIBLIONUMBER}/$biblionumber/g;
948     $template->param('OPACSearchForTitleIn' => $search_for_title);
949 }
950
951 # We try to select the best default tab to show, according to what
952 # the user wants, and what's available for display
953 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
954 my $defaulttab = 
955     $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
956         ? 'subscriptions' :
957     $opac_serial_default eq 'serialcollection' && @serialcollections > 0
958         ? 'serialcollection' :
959     $opac_serial_default eq 'holdings' && $dat->{'count'} > 0
960         ? 'holdings' :
961     $subscriptionsnumber
962         ? 'subscriptions' :
963     @serialcollections > 0 
964         ? 'serialcollection' : 'subscription';
965 $template->param('defaulttab' => $defaulttab);
966
967 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
968     my @images = ListImagesForBiblio($biblionumber);
969     $template->{VARS}->{localimages} = \@images;
970 }
971
972 output_html_with_http_headers $query, $cookie, $template->output;