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