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