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