3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Copyright 2011 KohaAloha, NZ
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26 use C4::Acquisition qw( SearchOrders );
27 use C4::Auth qw( get_template_and_user get_session );
29 getitemtypeimagelocation
32 GetNormalizedOCLCNumber
35 use C4::Search qw( new_record_from_zebra searchResults getRecords );
36 use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials );
37 use C4::Output qw( parametrized_url output_html_with_http_headers );
48 use C4::Items qw( GetItemsInfo );
49 use C4::Circulation qw( GetTransfers );
50 use C4::Tags qw( get_tags );
51 use C4::XISBN qw( get_xisbns );
52 use C4::External::Amazon qw( get_amazon_tld );
53 use C4::External::BakerTaylor qw( image_url link_url );
54 use C4::External::Syndetics qw(
63 use C4::XSLT qw( XSLTParse4Display );
64 use C4::ShelfBrowser qw( GetNearbyItems );
65 use C4::Reserves qw( GetReserveStatus );
66 use C4::Charset qw( SetUTF8Flag );
68 use List::MoreUtils qw( any );
70 use C4::CourseReserves qw( GetItemCourseReservesInfo );
73 use Koha::RecordProcessor;
74 use Koha::AuthorisedValues;
75 use Koha::CirculationRules;
78 use Koha::Acquisition::Orders;
79 use Koha::Virtualshelves;
85 use Koha::SearchEngine::Search;
86 use Koha::SearchEngine::QueryBuilder;
89 use JSON qw( decode_json );
91 my $query = CGI->new();
93 my $biblionumber = $query->param('biblionumber') || $query->param('bib') || 0;
94 $biblionumber = int($biblionumber);
96 my $specific_item = $query->param('itemnumber') ? Koha::Items->find( scalar $query->param('itemnumber') ) : undef;
97 $biblionumber = $specific_item->biblionumber if $specific_item;
99 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
101 template_name => "opac-detail.tt",
104 authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
108 my @all_items = GetItemsInfo($biblionumber);
109 if( $specific_item ) {
110 @all_items = grep { $_->{itemnumber} == $query->param('itemnumber') } @all_items;
111 $template->param( specific_item => 1 );
114 my $patron = Koha::Patrons->find( $borrowernumber );
116 my $biblio = Koha::Biblios->find( $biblionumber );
117 my $record = $biblio ? $biblio->metadata->record : undef;
118 unless ( $biblio && $record ) {
119 print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
123 unless ( $patron and $patron->category->override_hidden_items ) {
124 # only skip this check if there's a logged in user
125 # and its category overrides OpacHiddenItems
126 if ( $biblio->hidden_in_opac({ rules => C4::Context->yaml_preference('OpacHiddenItems') }) ) {
127 print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early
130 if ( scalar @all_items >= 1 ) {
131 @items_to_show = Koha::Items->search( { itemnumber => [ map { $_->{itemnumber} } @all_items ] } )
132 ->filter_by_visible_in_opac( { patron => $patron } )->as_list;
136 my $framework = $biblio ? $biblio->frameworkcode : q{};
137 my $record_processor = Koha::RecordProcessor->new({
138 filters => 'ViewPolicy',
141 frameworkcode => $framework
144 $record_processor->process($record);
146 # redirect if opacsuppression is enabled and biblio is suppressed
147 if (C4::Context->preference('OpacSuppression')) {
148 # FIXME hardcoded; the suppression flag ought to be materialized
149 # as a column on biblio or the like
150 my $opacsuppressionfield = '942';
151 my $opacsuppressionfieldvalue = $record->field($opacsuppressionfield);
152 # redirect to opac-blocked info page or 404?
153 my $opacsuppressionredirect;
154 if ( C4::Context->preference("OpacSuppressionRedirect") ) {
155 $opacsuppressionredirect = "/cgi-bin/koha/opac-blocked.pl";
157 $opacsuppressionredirect = "/cgi-bin/koha/errors/404.pl";
159 if ( $opacsuppressionfieldvalue &&
160 $opacsuppressionfieldvalue->subfield("n") &&
161 $opacsuppressionfieldvalue->subfield("n") == 1) {
162 # if OPAC suppression by IP address
163 if (C4::Context->preference('OpacSuppressionByIPRange')) {
164 my $IPAddress = $ENV{'REMOTE_ADDR'};
165 my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
166 if ($IPAddress !~ /^$IPRange/) {
167 print $query->redirect($opacsuppressionredirect);
171 print $query->redirect($opacsuppressionredirect);
181 # get biblionumbers stored in the cart
184 if($query->cookie("bib_list")){
185 my $cart_list = $query->cookie("bib_list");
186 @cart_list = split(/\//, $cart_list);
187 if ( grep {$_ eq $biblionumber} @cart_list) {
188 $template->param( incart => 1 );
193 SetUTF8Flag($record);
194 my $marcflavour = C4::Context->preference("marcflavour");
195 my $ean = GetNormalizedEAN( $record, $marcflavour );
197 my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults");
199 # We look for the busc param to build the simple paging from the search
200 if ($OpacBrowseResults) {
201 my $session = get_session($query->cookie("CGISESSID"));
202 my %paging = (previous => {}, next => {});
203 if ($session->param('busc')) {
204 use URI::Escape qw( uri_escape_utf8 uri_unescape );
206 # Rebuild the string to store on session
207 # param value is URI encoded and params separator is HTML encode (&)
210 my $arrParamsBusc = shift;
212 my $pasarParams = '';
214 for (keys %$arrParamsBusc) {
215 if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
216 if (defined($arrParamsBusc->{$_})) {
217 $pasarParams .= '&' if ($j);
218 $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} ));
222 for my $value (@{$arrParamsBusc->{$_}}) {
223 next if !defined($value);
224 $pasarParams .= '&' if ($j);
225 $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value));
233 # Search given the current values from the busc param
236 my ($arrParamsBusc, $offset, $results_per_page, $patron) = @_;
238 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
240 @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
241 @servers = ("biblioserver") unless (@servers);
243 my ($default_sort_by, @sort_by);
244 $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
245 @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
246 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
247 my ($error, $results_hashref, $facets);
249 my $searcher = Koha::SearchEngine::Search->new(
250 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
251 my $json = JSON->new->utf8->allow_nonref(1);
252 ($error, $results_hashref, $facets) = $searcher->search_compat($json->decode($arrParamsBusc->{'query'}),$arrParamsBusc->{'simple_query'},\@sort_by,\@servers,$results_per_page,$offset,undef,$itemtypes,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'});
256 my $search_context = {
260 for (my $i=0;$i<@servers;$i++) {
261 my $server = $servers[$i];
262 $hits = $results_hashref->{$server}->{"hits"};
263 @newresults = searchResults( $search_context, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
268 # Build the current list of biblionumbers in this search
271 my ($newresultsRef, $results_per_page) = @_;
273 my $listBiblios = '';
275 foreach (@$newresultsRef) {
276 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
277 $listBiblios .= $bibnum . ',';
279 last if ($j == $results_per_page);
281 chop $listBiblios if ($listBiblios =~ /,$/);
285 my $busc = $session->param("busc");
286 my @arrBusc = split(/\&(?:amp;)?/, $busc);
288 my %arrParamsBusc = ();
290 ($key, $value) = split(/=/, $_, 2);
291 if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
292 $arrParamsBusc{$key} = uri_unescape($value);
294 unless (exists($arrParamsBusc{$key})) {
295 $arrParamsBusc{$key} = [];
297 push @{$arrParamsBusc{$key}}, uri_unescape($value);
301 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
302 my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
303 $arrParamsBusc{'count'} = $results_per_page;
304 my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
305 # The value OPACnumSearchResults has changed and the search has to be rebuild
306 if ($count != $results_per_page) {
307 if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
309 my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
310 for (@arrBibliosAux) {
311 last if ($_ == $biblionumber);
314 $indexBiblio += $offset;
315 $offset = int($indexBiblio / $count) * $count;
316 $arrParamsBusc{'offset'} = $offset;
318 $arrParamsBusc{'count'} = $count;
319 $results_per_page = $count;
320 my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page, $patron);
321 $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
322 delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
323 delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
324 delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
325 delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
326 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
327 $session->param("busc" => $newbusc);
328 @arrBusc = split(/\&(?:amp;)?/, $newbusc);
330 my $modifyListBiblios = 0;
331 # We come from a previous click
332 if (exists($arrParamsBusc{'previous'})) {
333 $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
334 delete $arrParamsBusc{'previous'};
335 } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
336 $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
337 delete $arrParamsBusc{'next'};
339 if ($modifyListBiblios) {
340 if (exists($arrParamsBusc{'newlistBiblios'})) {
341 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
342 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
343 my @arrAux = split(',', $listBibliosAux);
344 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
345 if ($modifyListBiblios == 1) {
346 $arrParamsBusc{'next'} = $arrAux[0];
347 $paging{'next'}->{biblionumber} = $arrAux[0];
349 $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
350 $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
353 delete $arrParamsBusc{'listBiblios'};
355 my $offsetAux = $arrParamsBusc{'offset'};
356 $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
357 $arrParamsBusc{'offsetSearch'} = $offsetAux;
358 $offset = $arrParamsBusc{'offset'};
359 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
360 $session->param("busc" => $newbusc);
361 @arrBusc = split(/\&(?:amp;)?/, $newbusc);
366 # Rebuild the query for the button "back to results"
368 unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
369 $buscParam .= '&' unless ($j == 0);
370 $buscParam .= $_; # string already URI encoded
374 $template->param('busc' => $buscParam);
377 # We are inside the list of biblios and we don't have to search
378 if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
379 @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
381 # We are at the first item of the list
382 if ($arrBiblios[0] == $biblionumber) {
383 if (@arrBiblios > 1) {
384 for (my $j = 1; $j < @arrBiblios; $j++) {
385 next unless ($arrBiblios[$j]);
386 $paging{'next'}->{biblionumber} = $arrBiblios[$j];
390 # search again if we are not at the first searching list
391 if ($offset && !$arrParamsBusc{'previous'}) {
393 $offsetSearch = $offset - $results_per_page;
395 # we are at the last item of the list
396 } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
397 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
398 next unless ($arrBiblios[$j]);
399 $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
403 # search again if we are at the first list and there is more results
404 $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
406 # search again if we aren't at the first list and there is more results
407 $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
409 $offsetSearch = $offset + $results_per_page if ($searchAgain);
411 for (my $j = 1; $j < $#arrBiblios; $j++) {
412 if ($arrBiblios[$j] == $biblionumber) {
413 for (my $z = $j - 1; $z >= 0; $z--) {
414 next unless ($arrBiblios[$z]);
415 $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
418 for (my $z = $j + 1; $z < @arrBiblios; $z++) {
419 next unless ($arrBiblios[$z]);
420 $paging{'next'}->{biblionumber} = $arrBiblios[$z];
428 $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
431 my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page, $patron);
432 my @newresults = @$newresultsRef;
433 # build the new listBiblios
434 my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
435 unless (exists($arrParamsBusc{'listBiblios'})) {
436 $arrParamsBusc{'listBiblios'} = $listBiblios;
437 @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
439 $arrParamsBusc{'newlistBiblios'} = $listBiblios;
441 # From the new list we build again the next and previous result
443 if ($arrBiblios[0] == $biblionumber) {
444 for (my $j = $#newresults; $j >= 0; $j--) {
445 next unless ($newresults[$j]);
446 $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
447 $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
448 $arrParamsBusc{'offsetSearch'} = $offsetSearch;
451 } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
452 for (my $j = 0; $j < @newresults; $j++) {
453 next unless ($newresults[$j]);
454 $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
455 $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
456 $arrParamsBusc{'offsetSearch'} = $offsetSearch;
461 # build new busc param
462 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
463 $session->param("busc" => $newbusc);
465 my ($numberBiblioPaging, $dataBiblioPaging);
467 $numberBiblioPaging = $paging{'previous'}->{biblionumber};
468 if ($numberBiblioPaging) {
469 $template->param( 'previousBiblionumber' => $numberBiblioPaging );
470 $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
471 $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
474 $numberBiblioPaging = $paging{'next'}->{biblionumber};
475 if ($numberBiblioPaging) {
476 $template->param( 'nextBiblionumber' => $numberBiblioPaging );
477 $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
478 $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
480 # Partial list of biblio results
482 for (my $j = 0; $j < @arrBiblios; $j++) {
483 next unless ($arrBiblios[$j]);
484 $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber);
485 next unless $dataBiblioPaging;
486 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]};
488 $template->param('listResults' => \@listResults) if (@listResults);
489 $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
490 $template->param( 'offset' => $offset );
495 OPACShowCheckoutName => C4::Context->preference("OPACShowCheckoutName"),
498 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
499 # adding items linked via host biblios
500 my $analyticfield = '773';
501 if ($marcflavour eq 'MARC21'){
502 $analyticfield = '773';
503 } elsif ($marcflavour eq 'UNIMARC') {
504 $analyticfield = '461';
506 foreach my $hostfield ( $record->field($analyticfield)) {
507 my $hostbiblionumber = $hostfield->subfield("0");
508 my $linkeditemnumber = $hostfield->subfield("9");
509 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
510 foreach my $hostitemInfo (@hostitemInfos){
511 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
512 push(@all_items, $hostitemInfo);
520 # Are there items to hide?
522 if ( @items_to_show != @all_items ) {
523 for my $itm (@all_items) {
524 next unless any { $itm->{itemnumber} eq $_ } @items_to_show;
525 if ( C4::Context->preference('hidelostitems') ) {
526 push @items, $itm unless $itm->{itemlost};
537 my $dat = &GetBiblioData($biblionumber);
538 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
540 frameworkcode => $dat->{'frameworkcode'},
544 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
546 my $itemtype = $dat->{'itemtype'};
548 $dat->{'imageurl'} = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
549 $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
553 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
555 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
557 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
559 #coping with subscriptions
560 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
561 my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
564 $dat->{'serial'}=1 if $subscriptionsnumber;
565 foreach my $subscription (@subscriptions) {
566 my $serials_to_display;
568 $cell{subscriptionid} = $subscription->{subscriptionid};
569 $cell{subscriptionnotes} = $subscription->{notes};
570 $cell{missinglist} = $subscription->{missinglist};
571 $cell{opacnote} = $subscription->{opacnote};
572 $cell{histstartdate} = $subscription->{histstartdate};
573 $cell{histenddate} = $subscription->{histenddate};
574 $cell{branchcode} = $subscription->{branchcode};
575 $cell{callnumber} = $subscription->{callnumber};
576 $cell{location} = $subscription->{location};
577 $cell{closed} = $subscription->{closed};
578 $cell{letter} = $subscription->{letter};
579 $cell{biblionumber} = $subscription->{biblionumber};
580 #get the three latest serials.
581 $serials_to_display = $subscription->{opacdisplaycount};
582 $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
583 $cell{opacdisplaycount} = $serials_to_display;
584 $cell{latestserials} =
585 GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
586 if ( $borrowernumber ) {
587 my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} );
588 my $subscriber = $subscription_object->subscribers->find( $borrowernumber );
589 $cell{hasalert} = 1 if $subscriber;
594 $dat->{'count'} = scalar(@items);
597 my (%item_reserves, %priority);
598 my ($show_holds_count, $show_priority);
599 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
600 m/holds/o and $show_holds_count = 1;
601 m/priority/ and $show_priority = 1;
604 if ( $show_holds_count || $show_priority) {
605 my $holds = $biblio->holds;
606 $template->param( holds_count => $holds->count );
607 while ( my $hold = $holds->next ) {
608 $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber;
609 if ($show_priority && $hold->borrowernumber == $borrowernumber) {
612 ? ($priority{ $hold->itemnumber } = $hold->priority)
613 : ($template->param( priority => $hold->priority ));
617 $template->param( show_priority => $has_hold ) ;
620 my (@itemloop, @otheritemloop);
621 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
622 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
623 $template->param(SeparateHoldings => 1);
625 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
626 my $viewallitems = $query->param('viewallitems');
627 my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50;
629 # Get component parts details
630 my $showcomp = C4::Context->preference('ShowComponentRecords');
631 my ( $parts, $show_analytics );
632 if ( $showcomp eq 'both' || $showcomp eq 'opac' ) {
633 if ( my $components = $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) ) {
634 $show_analytics = 1 if @{$components}; # just show link when having results
635 for my $part ( @{$components} ) {
636 $part = C4::Search::new_record_from_zebra( 'biblioserver', $part );
637 my $id = Koha::SearchEngine::Search::extract_biblionumber( $part );
644 xsl_syspref => 'OPACXSLTResultsDisplay',
649 $template->param( ComponentParts => $parts );
650 my ( $comp_query, $comp_sort ) = $biblio->get_components_query;
651 my $cpq = $comp_query . "&sort_by=" . $comp_sort;
652 $template->param( ComponentPartsQuery => $cpq );
654 } else { # check if we should show analytics anyway
655 $show_analytics = 1 if @{$biblio->get_marc_components(1)}; # count matters here, results does not
658 # XSLT processing of some stuff
660 my @plugin_responses = Koha::Plugins->call(
661 'opac_detail_xslt_variables',
663 biblio_id => $biblionumber,
664 lang => C4::Languages::getlanguage(),
665 patron_id => $borrowernumber,
668 for my $plugin_variables ( @plugin_responses ) {
669 $variables = { %$variables, %$plugin_variables };
671 $variables->{anonymous_session} = $borrowernumber ? 0 : 1;
672 $variables->{show_analytics_link} = $show_analytics;
674 XSLTBloc => XSLTParse4Display({
675 biblionumber => $biblionumber,
677 xsl_syspref => 'OPACXSLTDetailsDisplay',
679 xslt_variables => $variables,
684 my ( @itemnumbers_on_order );
685 if ( C4::Context->preference('OPACAcquisitionDetails' ) ) {
686 my $orders = C4::Acquisition::SearchOrders({
687 biblionumber => $biblionumber,
690 my $total_quantity = 0;
691 for my $order ( @$orders ) {
692 my $order = Koha::Acquisition::Orders->find( $order->{ordernumber} );
693 my $basket = $order->basket;
694 if ( $basket->effective_create_items eq 'ordering' ) {
695 @itemnumbers_on_order = $order->items->get_column('itemnumber');
697 $total_quantity += $order->quantity;
699 $template->{VARS}->{acquisition_details} = {
700 total_quantity => $total_quantity,
704 my $allow_onshelf_holds;
705 my ( $itemloop_has_images, $otheritemloop_has_images );
706 if ( not $viewallitems and @items > $max_items_to_display ) {
709 items_count => scalar( @items ),
712 for my $itm (@items) {
713 my $item = Koha::Items->find( $itm->{itemnumber} );
714 $itm->{holds_count} = $item_reserves{ $itm->{itemnumber} };
715 $itm->{priority} = $priority{ $itm->{itemnumber} };
717 $allow_onshelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } )
718 unless $allow_onshelf_holds;
720 # get collection code description, too
721 my $ccode = $itm->{'ccode'};
722 $itm->{'ccode'} = $collections->{$ccode} if defined($ccode) && $collections && exists( $collections->{$ccode} );
723 my $copynumber = $itm->{'copynumber'};
724 $itm->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) );
725 if ( defined $itm->{'location'} ) {
726 $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
728 if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
729 $itm->{'imageurl'} = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
730 $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{translated_description};
732 foreach (qw(ccode materials enumchron copynumber itemnotes location_description uri)) {
733 $itemfields{$_} = 1 if ($itm->{$_});
736 my $reserve_status = C4::Reserves::GetReserveStatus($itm->{itemnumber});
737 if ( $reserve_status eq "Waiting" ) { $itm->{'waiting'} = 1; }
738 if ( $reserve_status eq "Reserved" ) { $itm->{'onhold'} = 1; }
740 if ( C4::Context->preference('UseRecalls') ) {
741 my $pending_recall_count = Koha::Recalls->search(
743 item_id => $itm->{itemnumber},
747 if ( $pending_recall_count ) { $itm->{has_pending_recall} = 1; }
750 my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
751 if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
752 $itm->{transfertwhen} = $transfertwhen;
753 $itm->{transfertfrom} = $transfertfrom;
754 $itm->{transfertto} = $transfertto;
757 if ( C4::Context->preference('OPACAcquisitionDetails') ) {
759 if grep { $_ eq $itm->{itemnumber} } @itemnumbers_on_order;
762 if ( C4::Context->preference("OPACLocalCoverImages") == 1 ) {
763 $itm->{cover_images} = $item->cover_images;
766 if ( $item->in_bundle ) {
767 my $host = $item->bundle_host;
768 $itm->{bundle_host} = $host;
771 my $itembranch = $itm->{$separatebranch};
772 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
773 if ($itembranch and $itembranch eq $currentbranch) {
774 push @itemloop, $itm;
775 $itemloop_has_images++ if $item->cover_images->count;
777 push @otheritemloop, $itm;
778 $otheritemloop_has_images++ if $item->cover_images->count;
781 push @itemloop, $itm;
782 $itemloop_has_images++ if $item->cover_images->count;
787 if( $allow_onshelf_holds || CountItemsIssued($biblionumber) || $biblio->has_items_waiting_or_intransit ) {
788 $template->param( ReservableItems => 1 );
792 itemloop_has_images => $itemloop_has_images,
793 otheritemloop_has_images => $otheritemloop_has_images,
796 # Display only one tab if one items list is empty
797 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
798 $template->param(SeparateHoldings => 0);
799 if (scalar(@itemloop) == 0) {
800 @itemloop = @otheritemloop;
804 my $marcnotesarray = $biblio->get_marc_notes({ opac => 1, record => $record });
806 if( C4::Context->preference('ArticleRequests') ) {
807 my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef;
808 my $itemtype = Koha::ItemTypes->find($biblio->itemtype);
809 my $artreqpossible = $patron
810 ? $biblio->can_article_request( $patron )
812 ? $itemtype->may_article_request
814 $template->param( artreqpossible => $artreqpossible );
817 my $norequests = ! $biblio->items->filter_by_for_hold->count;
819 MARCNOTES => $marcnotesarray,
820 norequests => $norequests,
821 itemdata_ccode => $itemfields{ccode},
822 itemdata_materials => $itemfields{materials},
823 itemdata_enumchron => $itemfields{enumchron},
824 itemdata_uri => $itemfields{uri},
825 itemdata_copynumber => $itemfields{copynumber},
826 itemdata_itemnotes => $itemfields{itemnotes},
827 itemdata_location => $itemfields{location_description},
828 OpacStarRatings => C4::Context->preference("OpacStarRatings"),
831 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
832 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
833 my $subfields = substr $fieldspec, 3;
834 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
835 my @alternateholdingsinfo = ();
836 my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
838 for my $field (@holdingsfields) {
839 my %holding = ( holding => '' );
840 my $havesubfield = 0;
841 for my $subfield ($field->subfields()) {
842 if ((index $subfields, $$subfield[0]) >= 0) {
843 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
844 $holding{'holding'} .= $$subfield[1];
849 push(@alternateholdingsinfo, \%holding);
854 ALTERNATEHOLDINGS => \@alternateholdingsinfo,
858 # FIXME: The template uses this hash directly. Need to filter.
859 foreach ( keys %{$dat} ) {
860 next if ( $HideMARC->{$_} );
861 $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
864 # some useful variables for enhanced content;
865 # in each case, we're grabbing the first value we find in
866 # the record and normalizing it
867 my $upc = GetNormalizedUPC($record,$marcflavour);
868 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
869 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
870 my $content_identifier_exists;
871 if ( $isbn or $ean or $oclc or $upc ) {
872 $content_identifier_exists = 1;
875 normalized_upc => $upc,
876 normalized_ean => $ean,
877 normalized_oclc => $oclc,
878 normalized_isbn => $isbn,
879 content_identifier_exists => $content_identifier_exists,
882 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
883 # COinS format FIXME: for books Only
884 my $coins = eval { $biblio->get_coins };
885 $template->param( ocoins => $coins );
887 my ( $loggedincommenter, $reviews );
888 if ( C4::Context->preference('OPACComments') ) {
889 $reviews = Koha::Reviews->search(
891 biblionumber => $biblionumber,
892 -or => { approved => 1, borrowernumber => $borrowernumber }
895 order_by => { -desc => 'datereviewed' }
898 my $libravatar_enabled = 0;
899 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) {
901 require Libravatar::URL;
902 Libravatar::URL->import();
905 $libravatar_enabled = 1;
908 for my $review (@$reviews) {
909 my $review_patron = Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar
911 # setting some borrower info into this hash
912 if ( $review_patron ) {
913 $review->{patron} = $review_patron;
914 if ( $libravatar_enabled and $review_patron->email ) {
915 $review->{avatarurl} = libravatar_url( email => $review_patron->email, https => $ENV{HTTPS} );
918 if ( $review_patron->borrowernumber eq $borrowernumber ) {
919 $loggedincommenter = 1;
925 if ( C4::Context->preference("OPACISBD") ) {
926 $template->param( ISBD => 1 );
930 itemloop => \@itemloop,
931 otheritemloop => \@otheritemloop,
932 biblionumber => $biblionumber,
933 subscriptions => \@subs,
934 subscriptionsnumber => $subscriptionsnumber,
936 loggedincommenter => $loggedincommenter
940 if (C4::Context->preference("virtualshelves") ) {
941 my $shelves = Koha::Virtualshelves->search(
943 biblionumber => $biblionumber,
947 join => 'virtualshelfcontents',
950 $template->param( shelves => $shelves );
954 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
957 XISBNS => scalar get_xisbns($isbn, $biblionumber)
960 if ($@) { warn "XISBN Failed $@"; }
964 my @sc_fields = $record->field(955);
965 my @lc_fields = $marcflavour eq 'UNIMARC'
966 ? $record->field(930)
967 : $record->field(852);
968 my @serialcollections = ();
970 foreach my $sc_field (@sc_fields) {
973 $row_data{text} = $sc_field->subfield('r');
974 $row_data{branch} = $sc_field->subfield('9');
975 foreach my $lc_field (@lc_fields) {
976 $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
977 ? $lc_field->subfield('a') # 930$a
978 : $lc_field->subfield('h') # 852$h
979 if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
982 if ($row_data{text} && $row_data{branch}) {
983 push (@serialcollections, \%row_data);
987 if (scalar(@serialcollections) > 0) {
989 serialcollection => 1,
990 serialcollections => \@serialcollections);
993 # Local cover Images stuff
994 if (C4::Context->preference("OPACLocalCoverImages")){
995 $template->param(OPACLocalCoverImages => 1);
999 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
1000 $template->param( C4::HTML5Media->gethtml5media($record));
1003 my $syndetics_elements;
1005 if ( C4::Context->preference("SyndeticsEnabled") ) {
1006 $template->param("SyndeticsEnabled" => 1);
1007 $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
1009 $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
1010 for my $element (values %$syndetics_elements) {
1011 $template->param("Syndetics$element"."Exists" => 1 );
1012 #warn "Exists: "."Syndetics$element"."Exists";
1018 if ( C4::Context->preference("SyndeticsEnabled")
1019 && C4::Context->preference("SyndeticsSummary")
1020 && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
1022 my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
1023 $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
1029 if ( C4::Context->preference("SyndeticsEnabled")
1030 && C4::Context->preference("SyndeticsTOC")
1031 && exists($syndetics_elements->{'TOC'}) ) {
1033 my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
1034 $template->param( SYNDETICS_TOC => $syndetics_toc );
1039 if ( C4::Context->preference("SyndeticsEnabled")
1040 && C4::Context->preference("SyndeticsExcerpt")
1041 && exists($syndetics_elements->{'DBCHAPTER'}) ) {
1043 my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
1044 $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
1049 if ( C4::Context->preference("SyndeticsEnabled")
1050 && C4::Context->preference("SyndeticsReviews")) {
1052 my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
1053 $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
1058 if ( C4::Context->preference("SyndeticsEnabled")
1059 && C4::Context->preference("SyndeticsAuthorNotes")
1060 && exists($syndetics_elements->{'ANOTES'}) ) {
1062 my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
1063 $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
1068 # LibraryThingForLibraries ID Code and Tabbed View Option
1069 if( C4::Context->preference('LibraryThingForLibrariesEnabled') )
1071 $template->param(LibraryThingForLibrariesID =>
1072 C4::Context->preference('LibraryThingForLibrariesID') );
1073 $template->param(LibraryThingForLibrariesTabbedView =>
1074 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
1078 if( C4::Context->preference('NovelistSelectEnabled') )
1080 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') );
1081 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') );
1082 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') );
1087 if ( C4::Context->preference("Babeltheque") ) {
1090 Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
1095 if ( C4::Context->preference( "SocialNetworks" ) ) {
1096 $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
1097 $template->param( SocialNetworks => 1 );
1100 # Shelf Browser Stuff
1101 if (C4::Context->preference("OPACShelfBrowser")) {
1102 my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
1103 if (defined($starting_itemnumber)) {
1104 $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
1105 my $nearby = GetNearbyItems($starting_itemnumber);
1108 starting_itemnumber => $starting_itemnumber,
1109 starting_homebranch => $nearby->{starting_homebranch}->{description},
1110 starting_location => $nearby->{starting_location}->{description},
1111 starting_ccode => $nearby->{starting_ccode}->{description},
1112 shelfbrowser_prev_item => $nearby->{prev_item},
1113 shelfbrowser_next_item => $nearby->{next_item},
1114 shelfbrowser_items => $nearby->{items},
1117 # in which tab shelf browser should open ?
1118 if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) {
1119 $template->param(shelfbrowser_tab => 'holdings');
1121 $template->param(shelfbrowser_tab => 'otherholdings');
1126 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
1128 if (C4::Context->preference("BakerTaylorEnabled")) {
1130 BakerTaylorEnabled => 1,
1131 BakerTaylorImageURL => &image_url(),
1132 BakerTaylorLinkURL => &link_url(),
1133 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
1135 my ($bt_user, $bt_pass);
1137 $bt_user = C4::Context->preference('BakerTaylorUsername') and
1138 $bt_pass = C4::Context->preference('BakerTaylorPassword') )
1141 BakerTaylorContentURL =>
1142 sprintf("https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
1143 $bt_user,$bt_pass,$isbn)
1149 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
1152 TagsShowOnDetail => $tag_quantity,
1153 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
1155 $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
1156 'sort'=>'-weight', limit=>$tag_quantity}));
1159 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
1160 # These values are going to be read by Javascript, at least in the case
1161 # of the google covers
1162 $template->param(covernewwindow => 'true');
1164 $template->param(covernewwindow => 'false');
1167 $template->param(borrowernumber => $borrowernumber);
1169 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
1170 my $ratings = Koha::Ratings->search({ biblionumber => $biblionumber });
1171 my $my_rating = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
1173 ratings => $ratings,
1174 my_rating => $my_rating,
1178 #Search for title in links
1179 my $marccontrolnumber = GetMarcControlnumber ($record, $marcflavour);
1180 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1181 my $issn = $marcissns->[0] || '';
1183 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1184 $dat->{title} =~ s/\/+$//; # remove trailing slash
1185 $dat->{title} =~ s/\s+$//; # remove trailing space
1186 my $oclc_no = Koha::Util::MARC::oclc_number( $record );
1187 $search_for_title = parametrized_url(
1190 TITLE => $dat->{title},
1191 AUTHOR => $dat->{author},
1194 CONTROLNUMBER => $marccontrolnumber,
1195 BIBLIONUMBER => $biblionumber,
1196 OCLC_NO => $oclc_no,
1199 $template->param('OPACSearchForTitleIn' => $search_for_title);
1203 if ( C4::Context->preference("IDREF") ) {
1204 # If the record comes from the SUDOC
1205 if ( $record->field('009') ) {
1206 my $unimarc3 = $record->field("009")->data;
1207 if ( $unimarc3 =~ /^\d+$/ ) {
1215 # We try to select the best default tab to show, according to what
1216 # the user wants, and what's available for display
1217 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1221 $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1223 $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1224 ? 'serialcollection' :
1225 $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1227 ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar (@itemloop) == 0 && $parts
1229 scalar (@itemloop) == 0
1231 $subscriptionsnumber
1233 @serialcollections > 0
1234 ? 'serialcollection' : 'subscriptions';
1235 $template->param('defaulttab' => $defaulttab);
1237 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1238 $template->param( localimages => $biblio->cover_images );
1241 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1243 if (C4::Context->preference('OpacHighlightedWords')) {
1244 $template->{VARS}->{query_desc} = $query->param('query_desc');
1246 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1248 if ( C4::Context->preference('UseCourseReserves') ) {
1249 foreach my $i ( @items ) {
1250 $i->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $i->{'itemnumber'} );
1255 'OpacLocationBranchToDisplay' => C4::Context->preference('OpacLocationBranchToDisplay'),
1258 if ( C4::Context->preference('OPACAuthorIdentifiers') ) {
1259 my @author_identifiers;
1260 for my $author ( @{ $biblio->get_marc_authors } ) {
1261 my $authid = $author->{authoritylink};
1262 my $authority = Koha::Authorities->find($authid);
1263 next unless $authority;
1264 my $identifiers = $authority->get_identifiers;
1265 next unless $identifiers && @$identifiers;
1268 grep { $_->{code} eq 'a' ? $_ : () }
1269 @{ $author->{MARCAUTHOR_SUBFIELDS_LOOP} };
1270 push @author_identifiers,
1271 { authid => $authid, name => $name, identifiers => $identifiers };
1273 $template->param( author_identifiers => \@author_identifiers );
1276 output_html_with_http_headers $query, $cookie, $template->output;