Merge remote-tracking branch 'origin/new/bug_6858'
[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 (%item_reserves, %priority);
490 my ($show_holds_count, $show_priority);
491 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
492     m/holds/o and $show_holds_count = 1;
493     m/priority/ and $show_priority = 1;
494 }
495 my $has_hold;
496 if ( $show_holds_count || $show_priority) {
497     my ($reserve_count,$reserves) = GetReservesFromBiblionumber($biblionumber);
498     $template->param( holds_count  => $reserve_count ) if $show_holds_count;
499     foreach (@$reserves) {
500         $item_reserves{ $_->{itemnumber} }++ if $_->{itemnumber};
501         if ($show_priority && $_->{borrowernumber} == $borrowernumber) {
502             $has_hold = 1;
503             $_->{itemnumber}
504                 ? ($priority{ $_->{itemnumber} } = $_->{priority})
505                 : ($template->param( priority => $_->{priority} ));
506         }
507     }
508 }
509 $template->param( show_priority => $has_hold ) ;
510
511 my $norequests = 1;
512 my $branches = GetBranches();
513 my %itemfields;
514 for my $itm (@items) {
515     $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
516     $itm->{priority} = $priority{ $itm->{itemnumber} };
517     $norequests = 0
518        if ( (not $itm->{'wthdrawn'} )
519          && (not $itm->{'itemlost'} )
520          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
521                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
522          && ($itm->{'itemnumber'} ) );
523
524     if ( defined $itm->{'publictype'} ) {
525         # I can't actually find any case in which this is defined. --amoore 2008-12-09
526         $itm->{ $itm->{'publictype'} } = 1;
527     }
528
529     # get collection code description, too
530     if ( my $ccode = $itm->{'ccode'} ) {
531         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
532     }
533     if ( defined $itm->{'location'} ) {
534         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
535     }
536     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
537         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
538         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
539     }
540     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
541         $itemfields{$_} = 1 if ($itm->{$_});
542     }
543
544      # walk through the item-level authorised values and populate some images
545      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
546      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
547
548      if ( $itm->{'itemlost'} ) {
549          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
550          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
551          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
552      }
553      my ($reserve_status) = C4::Reserves::CheckReserves($itm->{itemnumber});
554       if( $reserve_status eq "Waiting"){ $itm->{'waiting'} = 1; }
555       if( $reserve_status eq "Reserved"){ $itm->{'onhold'} = 1; }
556     
557      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
558      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
559         $itm->{transfertwhen} = $transfertwhen;
560         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
561         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
562      }
563 }
564
565 ## get notes and subjects from MARC record
566 my $dbh              = C4::Context->dbh;
567 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
568 my $marcisbnsarray   = GetMarcISBN    ($record,$marcflavour);
569 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
570 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
571 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
572 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
573 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
574 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
575
576     $template->param(
577                      MARCNOTES               => $marcnotesarray,
578                      MARCSUBJCTS             => $marcsubjctsarray,
579                      MARCAUTHORS             => $marcauthorsarray,
580                      MARCSERIES              => $marcseriesarray,
581                      MARCURLS                => $marcurlsarray,
582                      MARCHOSTS               => $marchostsarray,
583                      norequests              => $norequests,
584                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
585                      itemdata_ccode          => $itemfields{ccode},
586                      itemdata_enumchron      => $itemfields{enumchron},
587                      itemdata_uri            => $itemfields{uri},
588                      itemdata_copynumber     => $itemfields{copynumber},
589                      itemdata_itemnotes          => $itemfields{itemnotes},
590                      authorised_value_images => $biblio_authorised_value_images,
591                      subtitle                => $subtitle,
592                      OpacStarRatings         => C4::Context->preference("OpacStarRatings"),
593     );
594
595 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
596     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
597     my $subfields = substr $fieldspec, 3;
598     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
599     my @alternateholdingsinfo = ();
600     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
601
602     for my $field (@holdingsfields) {
603         my %holding = ( holding => '' );
604         my $havesubfield = 0;
605         for my $subfield ($field->subfields()) {
606             if ((index $subfields, $$subfield[0]) >= 0) {
607                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
608                 $holding{'holding'} .= $$subfield[1];
609                 $havesubfield++;
610             }
611         }
612         if ($havesubfield) {
613             push(@alternateholdingsinfo, \%holding);
614         }
615     }
616
617     $template->param(
618         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
619         );
620 }
621
622 foreach ( keys %{$dat} ) {
623     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
624 }
625
626 # some useful variables for enhanced content;
627 # in each case, we're grabbing the first value we find in
628 # the record and normalizing it
629 my $upc = GetNormalizedUPC($record,$marcflavour);
630 my $ean = GetNormalizedEAN($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;