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::Circulation qw( GetTransfers );
49 use C4::Tags qw( get_tags );
50 use C4::XISBN qw( get_xisbns );
51 use C4::External::Amazon qw( get_amazon_tld );
52 use C4::External::BakerTaylor qw( image_url link_url );
53 use C4::External::Syndetics qw(
62 use C4::XSLT qw( XSLTParse4Display );
63 use C4::ShelfBrowser qw( GetNearbyItems );
64 use C4::Reserves qw( GetReserveStatus );
65 use C4::Charset qw( SetUTF8Flag );
67 use List::MoreUtils qw( any );
69 use C4::CourseReserves qw( GetItemCourseReservesInfo );
72 use Koha::RecordProcessor;
73 use Koha::AuthorisedValues;
74 use Koha::CirculationRules;
77 use Koha::Acquisition::Orders;
78 use Koha::Virtualshelves;
84 use Koha::Serial::Items;
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 $patron = Koha::Patrons->find( $borrowernumber );
110 my $biblio = Koha::Biblios->find( $biblionumber );
111 my $record = $biblio ? $biblio->metadata->record : undef;
112 unless ( $biblio && $record ) {
113 print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early
117 my $items = $biblio->items->search_ordered;
118 if ($specific_item) {
119 $items = $items->search( { itemnumber => scalar $query->param('itemnumber') } );
120 $template->param( specific_item => 1 );
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 ( $items->count >= 1 ) {
131 $items = $items->filter_by_visible_in_opac( { patron => $patron } );
135 my $framework = $biblio ? $biblio->frameworkcode : q{};
136 my $record_processor = Koha::RecordProcessor->new({
137 filters => 'ViewPolicy',
140 frameworkcode => $framework
143 $record_processor->process($record);
145 # redirect if opacsuppression is enabled and biblio is suppressed
146 if (C4::Context->preference('OpacSuppression')) {
147 # FIXME hardcoded; the suppression flag ought to be materialized
148 # as a column on biblio or the like
149 my $opacsuppressionfield = '942';
150 my $opacsuppressionfieldvalue = $record->field($opacsuppressionfield);
151 # redirect to opac-blocked info page or 404?
152 my $opacsuppressionredirect;
153 if ( C4::Context->preference("OpacSuppressionRedirect") ) {
154 $opacsuppressionredirect = "/cgi-bin/koha/opac-blocked.pl";
156 $opacsuppressionredirect = "/cgi-bin/koha/errors/404.pl";
158 if ( $opacsuppressionfieldvalue &&
159 $opacsuppressionfieldvalue->subfield("n") &&
160 $opacsuppressionfieldvalue->subfield("n") == 1) {
161 # if OPAC suppression by IP address
162 if (C4::Context->preference('OpacSuppressionByIPRange')) {
163 my $IPAddress = $ENV{'REMOTE_ADDR'};
164 my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
165 if ($IPAddress !~ /^$IPRange/) {
166 print $query->redirect($opacsuppressionredirect);
170 print $query->redirect($opacsuppressionredirect);
180 # get biblionumbers stored in the cart
183 if($query->cookie("bib_list")){
184 my $cart_list = $query->cookie("bib_list");
185 @cart_list = split(/\//, $cart_list);
186 if ( grep {$_ eq $biblionumber} @cart_list) {
187 $template->param( incart => 1 );
192 SetUTF8Flag($record);
193 my $marcflavour = C4::Context->preference("marcflavour");
194 my $ean = GetNormalizedEAN( $record, $marcflavour );
196 my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults");
198 # We look for the busc param to build the simple paging from the search
199 if ($OpacBrowseResults) {
200 my $session = get_session($query->cookie("CGISESSID"));
201 my %paging = (previous => {}, next => {});
202 if ($session->param('busc')) {
203 use URI::Escape qw( uri_escape_utf8 uri_unescape );
205 # Rebuild the string to store on session
206 # param value is URI encoded and params separator is HTML encode (&)
209 my $arrParamsBusc = shift;
211 my $pasarParams = '';
213 for (keys %$arrParamsBusc) {
214 if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) {
215 if (defined($arrParamsBusc->{$_})) {
216 $pasarParams .= '&' if ($j);
217 $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} ));
221 for my $value (@{$arrParamsBusc->{$_}}) {
222 next if !defined($value);
223 $pasarParams .= '&' if ($j);
224 $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value));
232 # Search given the current values from the busc param
235 my ($arrParamsBusc, $offset, $results_per_page, $patron) = @_;
237 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
239 @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'};
240 @servers = ("biblioserver") unless (@servers);
242 my ($default_sort_by, @sort_by);
243 $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder') if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
244 @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'};
245 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
246 my ($error, $results_hashref, $facets);
248 my $searcher = Koha::SearchEngine::Search->new(
249 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
250 my $json = JSON->new->utf8->allow_nonref(1);
251 ($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'});
255 my $search_context = {
259 for (my $i=0;$i<@servers;$i++) {
260 my $server = $servers[$i];
261 $hits = $results_hashref->{$server}->{"hits"};
262 @newresults = searchResults( $search_context, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"});
267 # Build the current list of biblionumbers in this search
270 my ($newresultsRef, $results_per_page) = @_;
272 my $listBiblios = '';
274 foreach (@$newresultsRef) {
275 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
276 $listBiblios .= $bibnum . ',';
278 last if ($j == $results_per_page);
280 chop $listBiblios if ($listBiblios =~ /,$/);
284 my $busc = $session->param("busc");
285 my @arrBusc = split(/\&(?:amp;)?/, $busc);
287 my %arrParamsBusc = ();
289 ($key, $value) = split(/=/, $_, 2);
290 if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) {
291 $arrParamsBusc{$key} = uri_unescape($value);
293 unless (exists($arrParamsBusc{$key})) {
294 $arrParamsBusc{$key} = [];
296 push @{$arrParamsBusc{$key}}, uri_unescape($value);
300 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
301 my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count;
302 $arrParamsBusc{'count'} = $results_per_page;
303 my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0;
304 # The value OPACnumSearchResults has changed and the search has to be rebuild
305 if ($count != $results_per_page) {
306 if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
308 my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'});
309 for (@arrBibliosAux) {
310 last if ($_ == $biblionumber);
313 $indexBiblio += $offset;
314 $offset = int($indexBiblio / $count) * $count;
315 $arrParamsBusc{'offset'} = $offset;
317 $arrParamsBusc{'count'} = $count;
318 $results_per_page = $count;
319 my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page, $patron);
320 $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page);
321 delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'}));
322 delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'}));
323 delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'}));
324 delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'}));
325 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
326 $session->param("busc" => $newbusc);
327 @arrBusc = split(/\&(?:amp;)?/, $newbusc);
329 my $modifyListBiblios = 0;
330 # We come from a previous click
331 if (exists($arrParamsBusc{'previous'})) {
332 $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'});
333 delete $arrParamsBusc{'previous'};
334 } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click
335 $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'});
336 delete $arrParamsBusc{'next'};
338 if ($modifyListBiblios) {
339 if (exists($arrParamsBusc{'newlistBiblios'})) {
340 my $listBibliosAux = $arrParamsBusc{'listBiblios'};
341 $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'};
342 my @arrAux = split(',', $listBibliosAux);
343 $arrParamsBusc{'newlistBiblios'} = $listBibliosAux;
344 if ($modifyListBiblios == 1) {
345 $arrParamsBusc{'next'} = $arrAux[0];
346 $paging{'next'}->{biblionumber} = $arrAux[0];
348 $arrParamsBusc{'previous'} = $arrAux[$#arrAux];
349 $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux];
352 delete $arrParamsBusc{'listBiblios'};
354 my $offsetAux = $arrParamsBusc{'offset'};
355 $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'};
356 $arrParamsBusc{'offsetSearch'} = $offsetAux;
357 $offset = $arrParamsBusc{'offset'};
358 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
359 $session->param("busc" => $newbusc);
360 @arrBusc = split(/\&(?:amp;)?/, $newbusc);
365 # Rebuild the query for the button "back to results"
367 unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) {
368 $buscParam .= '&' unless ($j == 0);
369 $buscParam .= $_; # string already URI encoded
373 $template->param('busc' => $buscParam);
376 # We are inside the list of biblios and we don't have to search
377 if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) {
378 @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
380 # We are at the first item of the list
381 if ($arrBiblios[0] == $biblionumber) {
382 if (@arrBiblios > 1) {
383 for (my $j = 1; $j < @arrBiblios; $j++) {
384 next unless ($arrBiblios[$j]);
385 $paging{'next'}->{biblionumber} = $arrBiblios[$j];
389 # search again if we are not at the first searching list
390 if ($offset && !$arrParamsBusc{'previous'}) {
392 $offsetSearch = $offset - $results_per_page;
394 # we are at the last item of the list
395 } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
396 for (my $j = $#arrBiblios - 1; $j >= 0; $j--) {
397 next unless ($arrBiblios[$j]);
398 $paging{'previous'}->{biblionumber} = $arrBiblios[$j];
402 # search again if we are at the first list and there is more results
403 $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios);
405 # search again if we aren't at the first list and there is more results
406 $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios));
408 $offsetSearch = $offset + $results_per_page if ($searchAgain);
410 for (my $j = 1; $j < $#arrBiblios; $j++) {
411 if ($arrBiblios[$j] == $biblionumber) {
412 for (my $z = $j - 1; $z >= 0; $z--) {
413 next unless ($arrBiblios[$z]);
414 $paging{'previous'}->{biblionumber} = $arrBiblios[$z];
417 for (my $z = $j + 1; $z < @arrBiblios; $z++) {
418 next unless ($arrBiblios[$z]);
419 $paging{'next'}->{biblionumber} = $arrBiblios[$z];
427 $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0);
430 my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page, $patron);
431 my @newresults = @$newresultsRef;
432 # build the new listBiblios
433 my $listBiblios = buildListBiblios(\@newresults, $results_per_page);
434 unless (exists($arrParamsBusc{'listBiblios'})) {
435 $arrParamsBusc{'listBiblios'} = $listBiblios;
436 @arrBiblios = split(',', $arrParamsBusc{'listBiblios'});
438 $arrParamsBusc{'newlistBiblios'} = $listBiblios;
440 # From the new list we build again the next and previous result
442 if ($arrBiblios[0] == $biblionumber) {
443 for (my $j = $#newresults; $j >= 0; $j--) {
444 next unless ($newresults[$j]);
445 $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber};
446 $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber};
447 $arrParamsBusc{'offsetSearch'} = $offsetSearch;
450 } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) {
451 for (my $j = 0; $j < @newresults; $j++) {
452 next unless ($newresults[$j]);
453 $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber};
454 $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber};
455 $arrParamsBusc{'offsetSearch'} = $offsetSearch;
460 # build new busc param
461 my $newbusc = rebuildBuscParam(\%arrParamsBusc);
462 $session->param("busc" => $newbusc);
464 my ($numberBiblioPaging, $dataBiblioPaging);
466 $numberBiblioPaging = $paging{'previous'}->{biblionumber};
467 if ($numberBiblioPaging) {
468 $template->param( 'previousBiblionumber' => $numberBiblioPaging );
469 $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
470 $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
473 $numberBiblioPaging = $paging{'next'}->{biblionumber};
474 if ($numberBiblioPaging) {
475 $template->param( 'nextBiblionumber' => $numberBiblioPaging );
476 $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging );
477 $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging;
479 # Partial list of biblio results
481 for (my $j = 0; $j < @arrBiblios; $j++) {
482 next unless ($arrBiblios[$j]);
483 $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber);
484 next unless $dataBiblioPaging;
485 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]};
487 $template->param('listResults' => \@listResults) if (@listResults);
488 $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset);
489 $template->param( 'offset' => $offset );
494 OPACShowCheckoutName => C4::Context->preference("OPACShowCheckoutName"),
497 my $host_items = $biblio->host_items->filter_by_visible_in_opac({ patron => $patron });
499 $items = $biblio->items->search_ordered(
503 $items->get_column('itemnumber'),
504 $host_items->get_column('itemnumber')
510 my $dat = &GetBiblioData($biblionumber);
511 my $HideMARC = $record_processor->filters->[0]->should_hide_marc(
513 frameworkcode => $dat->{'frameworkcode'},
517 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
519 my $itemtype = $dat->{'itemtype'};
521 $dat->{'imageurl'} = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
522 $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description};
526 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) };
528 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) };
530 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) };
532 #coping with subscriptions
533 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
534 my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
537 $dat->{'serial'}=1 if $subscriptionsnumber;
538 foreach my $subscription (@subscriptions) {
539 my $serials_to_display;
541 $cell{subscriptionid} = $subscription->{subscriptionid};
542 $cell{subscriptionnotes} = $subscription->{notes};
543 $cell{missinglist} = $subscription->{missinglist};
544 $cell{opacnote} = $subscription->{opacnote};
545 $cell{histstartdate} = $subscription->{histstartdate};
546 $cell{histenddate} = $subscription->{histenddate};
547 $cell{branchcode} = $subscription->{branchcode};
548 $cell{callnumber} = $subscription->{callnumber};
549 $cell{location} = $subscription->{location};
550 $cell{closed} = $subscription->{closed};
551 $cell{letter} = $subscription->{letter};
552 $cell{biblionumber} = $subscription->{biblionumber};
553 #get the three latest serials.
554 $serials_to_display = $subscription->{opacdisplaycount};
555 $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display;
556 $cell{opacdisplaycount} = $serials_to_display;
557 $cell{latestserials} =
558 GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
559 if ( $borrowernumber ) {
560 my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} );
561 my $subscriber = $subscription_object->subscribers->find( $borrowernumber );
562 $cell{hasalert} = 1 if $subscriber;
567 $dat->{'count'} = $items->count;
569 my (%item_reserves, %priority);
570 my ($show_holds_count, $show_priority);
571 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
572 m/holds/o and $show_holds_count = 1;
573 m/priority/ and $show_priority = 1;
576 if ( $show_holds_count || $show_priority) {
577 my $holds = $biblio->holds;
578 $template->param( holds_count => $holds->count );
579 while ( my $hold = $holds->next ) {
580 $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber;
581 if ($show_priority && $hold->borrowernumber == $borrowernumber) {
584 ? ($priority{ $hold->itemnumber } = $hold->priority)
585 : ($template->param( priority => $hold->priority ));
589 $template->param( show_priority => $has_hold ) ;
592 my (@itemloop, @otheritemloop);
593 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
594 if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) {
595 $template->param(SeparateHoldings => 1);
597 my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch');
598 my $viewallitems = $query->param('viewallitems');
599 my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50;
601 # Get component parts details
602 my $showcomp = C4::Context->preference('ShowComponentRecords');
603 my ( $parts, $show_analytics );
604 if ( $showcomp eq 'both' || $showcomp eq 'opac' ) {
605 if ( my $components = $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) ) {
606 $show_analytics = 1 if @{$components}; # just show link when having results
607 for my $part ( @{$components} ) {
608 $part = C4::Search::new_record_from_zebra( 'biblioserver', $part );
609 my $id = Koha::SearchEngine::Search::extract_biblionumber( $part );
616 xsl_syspref => 'OPACXSLTResultsDisplay',
621 $template->param( ComponentParts => $parts );
622 my ( $comp_query, $comp_sort ) = $biblio->get_components_query;
623 my $cpq = $comp_query . "&sort_by=" . $comp_sort;
624 $template->param( ComponentPartsQuery => $cpq );
626 } else { # check if we should show analytics anyway
627 $show_analytics = 1 if @{$biblio->get_marc_components(1)}; # count matters here, results does not
630 # XSLT processing of some stuff
632 my @plugin_responses = Koha::Plugins->call(
633 'opac_detail_xslt_variables',
635 biblio_id => $biblionumber,
636 lang => C4::Languages::getlanguage(),
637 patron_id => $borrowernumber,
640 for my $plugin_variables ( @plugin_responses ) {
641 $variables = { %$variables, %$plugin_variables };
643 $variables->{anonymous_session} = $borrowernumber ? 0 : 1;
644 $variables->{show_analytics_link} = $show_analytics;
646 XSLTBloc => XSLTParse4Display({
647 biblionumber => $biblionumber,
649 xsl_syspref => 'OPACXSLTDetailsDisplay',
651 xslt_variables => $variables,
656 my ( @itemnumbers_on_order );
657 if ( C4::Context->preference('OPACAcquisitionDetails' ) ) {
658 my $orders = C4::Acquisition::SearchOrders({
659 biblionumber => $biblionumber,
662 my $total_quantity = 0;
663 for my $order ( @$orders ) {
664 my $order = Koha::Acquisition::Orders->find( $order->{ordernumber} );
665 my $basket = $order->basket;
666 if ( $basket->effective_create_items eq 'ordering' ) {
667 @itemnumbers_on_order = $order->items->get_column('itemnumber');
669 $total_quantity += $order->quantity;
671 $template->{VARS}->{acquisition_details} = {
672 total_quantity => $total_quantity,
676 my $allow_onshelf_holds;
677 my ( $itemloop_has_images, $otheritemloop_has_images );
678 if ( not $viewallitems and $items->count > $max_items_to_display ) {
681 items_count => $items->count,
685 while ( my $item = $items->next ) {
686 my $item_info = $item->unblessed;
687 $item->{holds_count} = $item_reserves{ $item->itemnumber };
688 $item->{priority} = $priority{ $item->itemnumber };
690 $allow_onshelf_holds = Koha::CirculationRules->get_onshelfholds_policy(
691 { item => $item, patron => $patron } )
692 unless $allow_onshelf_holds;
694 # get collection code description, too
695 my $ccode = $item->ccode;
696 $item_info->{'ccode'} = $collections->{$ccode}
699 && exists( $collections->{$ccode} );
701 my $copynumber = $item->copynumber;
702 $item_info->{copynumber} = $copynumbers->{$copynumber}
703 if ( defined($copynumbers)
704 && defined($copynumber)
705 && exists( $copynumbers->{$copynumber} ) );
707 if ( defined $item->location ) {
708 $item_info->{'location_description'} =
709 $shelflocations->{ $item->location };
712 my $itemtype = $item->itemtype;
713 $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
714 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
715 $item_info->{'description'} =
716 $itemtypes->{ $itemtype->itemtype }->{translated_description};
719 qw(ccode materials enumchron copynumber itemnotes location_description uri)
722 $itemfields{$field} = 1 if $item_info->{$field};
725 # FIXME The following must be Koha::Item->serial
726 my $serial_item = Koha::Serial::Items->find($item->itemnumber);
727 if ( $serial_item ) {
728 $item_info->{serial} = $serial_item;
731 $item_info->{checkout} = $item->checkout;
734 C4::Reserves::GetReserveStatus( $item->itemnumber );
735 if ( $reserve_status eq "Waiting" ) { $item_info->{'waiting'} = 1; }
736 if ( $reserve_status eq "Reserved" ) { $item_info->{'onhold'} = 1; }
738 if ( C4::Context->preference('UseRecalls') ) {
739 my $pending_recall_count = Koha::Recalls->search(
741 item_id => $item->itemnumber,
745 if ( $pending_recall_count ) { $item_info->has_pending_recall = 1; }
748 my ( $transfertwhen, $transfertfrom, $transfertto ) =
749 GetTransfers( $item->itemnumber );
750 if ( defined($transfertwhen) && $transfertwhen ne '' ) {
751 $item_info->{transfertwhen} = $transfertwhen;
752 $item_info->{transfertfrom} = $transfertfrom;
753 $item_info->{transfertto} = $transfertto;
756 if ( C4::Context->preference('OPACAcquisitionDetails') ) {
757 $item_info->{on_order} = 1
758 if grep { $_ eq $item->itemnumber } @itemnumbers_on_order;
761 if ( C4::Context->preference("OPACLocalCoverImages") == 1 ) {
762 $item_info->{cover_images} = $item->cover_images;
766 if ( $item->in_bundle ) {
767 $item_info->{bundle_host} = $item->bundle_host;
770 if ( C4::Context->preference('UseCourseReserves') ) {
771 $item_info->{course_reserves} = GetItemCourseReservesInfo( itemnumber => $item->itemnumber );
774 $item_info->{holding_branch} = $item->holding_branch;
775 $item_info->{home_branch} = $item->home_branch;
777 my $itembranch = $item->$separatebranch;
779 and C4::Context->preference('OpacSeparateHoldings') )
781 if ( $itembranch and $itembranch eq $currentbranch ) {
782 push @itemloop, $item_info;
783 $itemloop_has_images++ if $item->cover_images->count;
786 push @otheritemloop, $item_info;
787 $otheritemloop_has_images++ if $item->cover_images->count;
791 push @itemloop, $item_info;
792 $itemloop_has_images++ if $item->cover_images->count;
797 if( $allow_onshelf_holds || CountItemsIssued($biblionumber) || $biblio->has_items_waiting_or_intransit ) {
798 $template->param( ReservableItems => 1 );
802 itemloop_has_images => $itemloop_has_images,
803 otheritemloop_has_images => $otheritemloop_has_images,
806 # Display only one tab if one items list is empty
807 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
808 $template->param(SeparateHoldings => 0);
809 if (scalar(@itemloop) == 0) {
810 @itemloop = @otheritemloop;
814 my $marcnotesarray = $biblio->get_marc_notes({ opac => 1, record => $record });
816 if( C4::Context->preference('ArticleRequests') ) {
817 my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef;
818 my $itemtype = Koha::ItemTypes->find($biblio->itemtype);
819 my $artreqpossible = $patron
820 ? $biblio->can_article_request( $patron )
822 ? $itemtype->may_article_request
824 $template->param( artreqpossible => $artreqpossible );
827 my $norequests = ! $biblio->items->filter_by_for_hold->count;
829 MARCNOTES => $marcnotesarray,
830 norequests => $norequests,
831 itemdata_ccode => $itemfields{ccode},
832 itemdata_materials => $itemfields{materials},
833 itemdata_enumchron => $itemfields{enumchron},
834 itemdata_uri => $itemfields{uri},
835 itemdata_copynumber => $itemfields{copynumber},
836 itemdata_itemnotes => $itemfields{itemnotes},
837 itemdata_location => $itemfields{location_description},
838 OpacStarRatings => C4::Context->preference("OpacStarRatings"),
841 if (C4::Context->preference("AlternateHoldingsField") && $items->count == 0) {
842 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
843 my $subfields = substr $fieldspec, 3;
844 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
845 my @alternateholdingsinfo = ();
846 my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
848 for my $field (@holdingsfields) {
849 my %holding = ( holding => '' );
850 my $havesubfield = 0;
851 for my $subfield ($field->subfields()) {
852 if ((index $subfields, $$subfield[0]) >= 0) {
853 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
854 $holding{'holding'} .= $$subfield[1];
859 push(@alternateholdingsinfo, \%holding);
864 ALTERNATEHOLDINGS => \@alternateholdingsinfo,
868 # FIXME: The template uses this hash directly. Need to filter.
869 foreach ( keys %{$dat} ) {
870 next if ( $HideMARC->{$_} );
871 $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
874 # some useful variables for enhanced content;
875 # in each case, we're grabbing the first value we find in
876 # the record and normalizing it
877 my $upc = GetNormalizedUPC($record,$marcflavour);
878 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
879 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
880 my $content_identifier_exists;
881 if ( $isbn or $ean or $oclc or $upc ) {
882 $content_identifier_exists = 1;
885 normalized_upc => $upc,
886 normalized_ean => $ean,
887 normalized_oclc => $oclc,
888 normalized_isbn => $isbn,
889 content_identifier_exists => $content_identifier_exists,
892 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
893 # COinS format FIXME: for books Only
894 my $coins = eval { $biblio->get_coins };
895 $template->param( ocoins => $coins );
897 my ( $loggedincommenter, $reviews );
898 if ( C4::Context->preference('OPACComments') ) {
899 $reviews = Koha::Reviews->search(
901 biblionumber => $biblionumber,
902 -or => { approved => 1, borrowernumber => $borrowernumber }
905 order_by => { -desc => 'datereviewed' }
908 my $libravatar_enabled = 0;
909 if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) {
911 require Libravatar::URL;
912 Libravatar::URL->import();
915 $libravatar_enabled = 1;
918 for my $review (@$reviews) {
919 my $review_patron = Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar
921 # setting some borrower info into this hash
922 if ( $review_patron ) {
923 $review->{patron} = $review_patron;
924 if ( $libravatar_enabled and $review_patron->email ) {
925 $review->{avatarurl} = libravatar_url( email => $review_patron->email, https => $ENV{HTTPS} );
928 if ( $review_patron->borrowernumber eq $borrowernumber ) {
929 $loggedincommenter = 1;
935 if ( C4::Context->preference("OPACISBD") ) {
936 $template->param( ISBD => 1 );
940 itemloop => \@itemloop,
941 otheritemloop => \@otheritemloop,
942 biblionumber => $biblionumber,
943 subscriptions => \@subs,
944 subscriptionsnumber => $subscriptionsnumber,
946 loggedincommenter => $loggedincommenter
950 if (C4::Context->preference("virtualshelves") ) {
951 my $shelves = Koha::Virtualshelves->search(
953 biblionumber => $biblionumber,
957 join => 'virtualshelfcontents',
960 $template->param( shelves => $shelves );
964 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
967 XISBNS => scalar get_xisbns($isbn, $biblionumber)
970 if ($@) { warn "XISBN Failed $@"; }
974 my @sc_fields = $record->field(955);
975 my @lc_fields = $marcflavour eq 'UNIMARC'
976 ? $record->field(930)
977 : $record->field(852);
978 my @serialcollections = ();
980 foreach my $sc_field (@sc_fields) {
983 $row_data{text} = $sc_field->subfield('r');
984 $row_data{branch} = $sc_field->subfield('9');
985 foreach my $lc_field (@lc_fields) {
986 $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC'
987 ? $lc_field->subfield('a') # 930$a
988 : $lc_field->subfield('h') # 852$h
989 if ($sc_field->subfield('5') eq $lc_field->subfield('5'));
992 if ($row_data{text} && $row_data{branch}) {
993 push (@serialcollections, \%row_data);
997 if (scalar(@serialcollections) > 0) {
999 serialcollection => 1,
1000 serialcollections => \@serialcollections);
1003 # Local cover Images stuff
1004 if (C4::Context->preference("OPACLocalCoverImages")){
1005 $template->param(OPACLocalCoverImages => 1);
1009 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) {
1010 $template->param( C4::HTML5Media->gethtml5media($record));
1013 my $syndetics_elements;
1015 if ( C4::Context->preference("SyndeticsEnabled") ) {
1016 $template->param("SyndeticsEnabled" => 1);
1017 $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode"));
1019 $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc);
1020 for my $element (values %$syndetics_elements) {
1021 $template->param("Syndetics$element"."Exists" => 1 );
1022 #warn "Exists: "."Syndetics$element"."Exists";
1028 if ( C4::Context->preference("SyndeticsEnabled")
1029 && C4::Context->preference("SyndeticsSummary")
1030 && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) {
1032 my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements);
1033 $template->param( SYNDETICS_SUMMARY => $syndetics_summary );
1039 if ( C4::Context->preference("SyndeticsEnabled")
1040 && C4::Context->preference("SyndeticsTOC")
1041 && exists($syndetics_elements->{'TOC'}) ) {
1043 my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc);
1044 $template->param( SYNDETICS_TOC => $syndetics_toc );
1049 if ( C4::Context->preference("SyndeticsEnabled")
1050 && C4::Context->preference("SyndeticsExcerpt")
1051 && exists($syndetics_elements->{'DBCHAPTER'}) ) {
1053 my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc);
1054 $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt );
1059 if ( C4::Context->preference("SyndeticsEnabled")
1060 && C4::Context->preference("SyndeticsReviews")) {
1062 my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements);
1063 $template->param( SYNDETICS_REVIEWS => $syndetics_reviews );
1068 if ( C4::Context->preference("SyndeticsEnabled")
1069 && C4::Context->preference("SyndeticsAuthorNotes")
1070 && exists($syndetics_elements->{'ANOTES'}) ) {
1072 my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc);
1073 $template->param( SYNDETICS_ANOTES => $syndetics_anotes );
1078 # LibraryThingForLibraries ID Code and Tabbed View Option
1079 if( C4::Context->preference('LibraryThingForLibrariesEnabled') )
1081 $template->param(LibraryThingForLibrariesID =>
1082 C4::Context->preference('LibraryThingForLibrariesID') );
1083 $template->param(LibraryThingForLibrariesTabbedView =>
1084 C4::Context->preference('LibraryThingForLibrariesTabbedView') );
1088 if( C4::Context->preference('NovelistSelectEnabled') )
1090 $template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') );
1091 $template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') );
1092 $template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') );
1097 if ( C4::Context->preference("Babeltheque") ) {
1100 Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"),
1105 if ( C4::Context->preference( "SocialNetworks" ) ) {
1106 $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" );
1107 $template->param( SocialNetworks => 1 );
1110 # Shelf Browser Stuff
1111 if (C4::Context->preference("OPACShelfBrowser")) {
1112 my $starting_itemnumber = $query->param('shelfbrowse_itemnumber');
1113 if (defined($starting_itemnumber)) {
1114 $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
1115 my $nearby = GetNearbyItems($starting_itemnumber);
1118 starting_itemnumber => $starting_itemnumber,
1119 starting_homebranch => $nearby->{starting_homebranch}->{description},
1120 starting_location => $nearby->{starting_location}->{description},
1121 starting_ccode => $nearby->{starting_ccode}->{description},
1122 shelfbrowser_prev_item => $nearby->{prev_item},
1123 shelfbrowser_next_item => $nearby->{next_item},
1124 shelfbrowser_items => $nearby->{items},
1127 # in which tab shelf browser should open ?
1128 if (grep { $starting_itemnumber == $_->itemnumber } @itemloop) {
1129 $template->param(shelfbrowser_tab => 'holdings');
1131 $template->param(shelfbrowser_tab => 'otherholdings');
1136 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages"));
1138 if (C4::Context->preference("BakerTaylorEnabled")) {
1140 BakerTaylorEnabled => 1,
1141 BakerTaylorImageURL => &image_url(),
1142 BakerTaylorLinkURL => &link_url(),
1143 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
1145 my ($bt_user, $bt_pass);
1147 $bt_user = C4::Context->preference('BakerTaylorUsername') and
1148 $bt_pass = C4::Context->preference('BakerTaylorPassword') )
1151 BakerTaylorContentURL =>
1152 sprintf("https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
1153 $bt_user,$bt_pass,$isbn)
1159 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
1162 TagsShowOnDetail => $tag_quantity,
1163 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
1165 $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
1166 'sort'=>'-weight', limit=>$tag_quantity}));
1169 if (C4::Context->preference("OPACURLOpenInNewWindow")) {
1170 # These values are going to be read by Javascript, at least in the case
1171 # of the google covers
1172 $template->param(covernewwindow => 'true');
1174 $template->param(covernewwindow => 'false');
1177 $template->param(borrowernumber => $borrowernumber);
1179 if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) {
1180 my $ratings = Koha::Ratings->search({ biblionumber => $biblionumber });
1181 my $my_rating = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
1183 ratings => $ratings,
1184 my_rating => $my_rating,
1188 #Search for title in links
1189 my $marccontrolnumber = GetMarcControlnumber ($record, $marcflavour);
1190 my $marcissns = GetMarcISSN ( $record, $marcflavour );
1191 my $issn = $marcissns->[0] || '';
1193 if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){
1194 $dat->{title} =~ s/\/+$//; # remove trailing slash
1195 $dat->{title} =~ s/\s+$//; # remove trailing space
1196 my $oclc_no = Koha::Util::MARC::oclc_number( $record );
1197 $search_for_title = parametrized_url(
1200 TITLE => $dat->{title},
1201 AUTHOR => $dat->{author},
1204 CONTROLNUMBER => $marccontrolnumber,
1205 BIBLIONUMBER => $biblionumber,
1206 OCLC_NO => $oclc_no,
1209 $template->param('OPACSearchForTitleIn' => $search_for_title);
1213 if ( C4::Context->preference("IDREF") ) {
1214 # If the record comes from the SUDOC
1215 if ( $record->field('009') ) {
1216 my $unimarc3 = $record->field("009")->data;
1217 if ( $unimarc3 =~ /^\d+$/ ) {
1225 # We try to select the best default tab to show, according to what
1226 # the user wants, and what's available for display
1227 my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab');
1231 $opac_serial_default eq 'subscriptions' && $subscriptionsnumber
1233 $opac_serial_default eq 'serialcollection' && @serialcollections > 0
1234 ? 'serialcollection' :
1235 $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0
1237 ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar (@itemloop) == 0 && $parts
1239 scalar (@itemloop) == 0
1241 $subscriptionsnumber
1243 @serialcollections > 0
1244 ? 'serialcollection' : 'subscriptions';
1245 $template->param('defaulttab' => $defaulttab);
1247 if (C4::Context->preference('OPACLocalCoverImages') == 1) {
1248 $template->param( localimages => $biblio->cover_images );
1251 $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch');
1253 if (C4::Context->preference('OpacHighlightedWords')) {
1254 $template->{VARS}->{query_desc} = $query->param('query_desc');
1256 $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks');
1259 'OpacLocationBranchToDisplay' => C4::Context->preference('OpacLocationBranchToDisplay'),
1262 if ( C4::Context->preference('OPACAuthorIdentifiers') ) {
1263 my @author_identifiers;
1264 for my $author ( @{ $biblio->get_marc_authors } ) {
1265 my $authid = $author->{authoritylink};
1266 my $authority = Koha::Authorities->find($authid);
1267 next unless $authority;
1268 my $identifiers = $authority->get_identifiers;
1269 next unless $identifiers && @$identifiers;
1272 grep { $_->{code} eq 'a' ? $_ : () }
1273 @{ $author->{MARCAUTHOR_SUBFIELDS_LOOP} };
1274 push @author_identifiers,
1275 { authid => $authid, name => $name, identifiers => $identifiers };
1277 $template->param( author_identifiers => \@author_identifiers );
1280 output_html_with_http_headers $query, $cookie, $template->output;