Bug 8995: (follow-up) Add tests, move open_url/coins routines to Koha namespace
[koha.git] / Koha / Biblio.pm
blobfae91cef3307ceecfcf45d635fabc8d8bab53700
1 package Koha::Biblio;
3 # Copyright ByWater Solutions 2014
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 use Modern::Perl;
22 use Carp;
23 use List::MoreUtils qw(any);
24 use URI;
25 use URI::Escape;
27 use C4::Biblio qw();
29 use Koha::Database;
30 use Koha::DateUtils qw( dt_from_string );
32 use base qw(Koha::Object);
34 use Koha::ArticleRequest::Status;
35 use Koha::ArticleRequests;
36 use Koha::Biblio::Metadatas;
37 use Koha::Biblioitems;
38 use Koha::IssuingRules;
39 use Koha::Item::Transfer::Limits;
40 use Koha::Items;
41 use Koha::Libraries;
42 use Koha::Subscriptions;
44 =head1 NAME
46 Koha::Biblio - Koha Biblio Object class
48 =head1 API
50 =head2 Class Methods
52 =cut
54 =head3 store
56 Overloaded I<store> method to set default values
58 =cut
60 sub store {
61 my ( $self ) = @_;
63 $self->datecreated( dt_from_string ) unless $self->datecreated;
65 return $self->SUPER::store;
68 =head3 metadata
70 my $metadata = $biblio->metadata();
72 Returns a Koha::Biblio::Metadata object
74 =cut
76 sub metadata {
77 my ( $self ) = @_;
79 my $metadata = $self->_result->metadata;
80 return Koha::Biblio::Metadata->_new_from_dbic($metadata);
83 =head3 subtitles
85 my @subtitles = $biblio->subtitles();
87 Returns list of subtitles for a record.
89 Keyword to MARC mapping for subtitle must be set for this method to return any possible values.
91 =cut
93 sub subtitles {
94 my ( $self ) = @_;
96 return map { $_->{subfield} } @{
97 C4::Biblio::GetRecordValue(
98 'subtitle',
99 C4::Biblio::GetMarcBiblio({ biblionumber => $self->id }),
100 $self->frameworkcode ) };
103 =head3 can_article_request
105 my $bool = $biblio->can_article_request( $borrower );
107 Returns true if article requests can be made for this record
109 $borrower must be a Koha::Patron object
111 =cut
113 sub can_article_request {
114 my ( $self, $borrower ) = @_;
116 my $rule = $self->article_request_type($borrower);
117 return q{} if $rule eq 'item_only' && !$self->items()->count();
118 return 1 if $rule && $rule ne 'no';
120 return q{};
123 =head3 can_be_transferred
125 $biblio->can_be_transferred({ to => $to_library, from => $from_library })
127 Checks if at least one item of a biblio can be transferred to given library.
129 This feature is controlled by two system preferences:
130 UseBranchTransferLimits to enable / disable the feature
131 BranchTransferLimitsType to use either an itemnumber or ccode as an identifier
132 for setting the limitations
134 Performance-wise, it is recommended to use this method for a biblio instead of
135 iterating each item of a biblio with Koha::Item->can_be_transferred().
137 Takes HASHref that can have the following parameters:
138 MANDATORY PARAMETERS:
139 $to : Koha::Library
140 OPTIONAL PARAMETERS:
141 $from : Koha::Library # if given, only items from that
142 # holdingbranch are considered
144 Returns 1 if at least one of the item of a biblio can be transferred
145 to $to_library, otherwise 0.
147 =cut
149 sub can_be_transferred {
150 my ($self, $params) = @_;
152 my $to = $params->{to};
153 my $from = $params->{from};
155 return 1 unless C4::Context->preference('UseBranchTransferLimits');
156 my $limittype = C4::Context->preference('BranchTransferLimitsType');
158 my $items;
159 foreach my $item_of_bib ($self->items->as_list) {
160 next unless $item_of_bib->holdingbranch;
161 next if $from && $from->branchcode ne $item_of_bib->holdingbranch;
162 return 1 if $item_of_bib->holdingbranch eq $to->branchcode;
163 my $code = $limittype eq 'itemtype'
164 ? $item_of_bib->effective_itemtype
165 : $item_of_bib->ccode;
166 return 1 unless $code;
167 $items->{$code}->{$item_of_bib->holdingbranch} = 1;
170 # At this point we will have a HASHref containing each itemtype/ccode that
171 # this biblio has, inside which are all of the holdingbranches where those
172 # items are located at. Then, we will query Koha::Item::Transfer::Limits to
173 # find out whether a transfer limits for such $limittype from any of the
174 # listed holdingbranches to the given $to library exist. If at least one
175 # holdingbranch for that $limittype does not have a transfer limit to given
176 # $to library, then we know that the transfer is possible.
177 foreach my $code (keys %{$items}) {
178 my @holdingbranches = keys %{$items->{$code}};
179 return 1 if Koha::Item::Transfer::Limits->search({
180 toBranch => $to->branchcode,
181 fromBranch => { 'in' => \@holdingbranches },
182 $limittype => $code
183 }, {
184 group_by => [qw/fromBranch/]
185 })->count == scalar(@holdingbranches) ? 0 : 1;
188 return 0;
191 =head3 hidden_in_opac
193 my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
195 Returns true if the biblio matches the hidding criteria defined in $rules.
196 Returns false otherwise.
198 Takes HASHref that can have the following parameters:
199 OPTIONAL PARAMETERS:
200 $rules : { <field> => [ value_1, ... ], ... }
202 Note: $rules inherits its structure from the parsed YAML from reading
203 the I<OpacHiddenItems> system preference.
205 =cut
207 sub hidden_in_opac {
208 my ( $self, $params ) = @_;
210 my $rules = $params->{rules} // {};
212 return !(any { !$_->hidden_in_opac({ rules => $rules }) } $self->items->as_list);
215 =head3 article_request_type
217 my $type = $biblio->article_request_type( $borrower );
219 Returns the article request type based on items, or on the record
220 itself if there are no items.
222 $borrower must be a Koha::Patron object
224 =cut
226 sub article_request_type {
227 my ( $self, $borrower ) = @_;
229 return q{} unless $borrower;
231 my $rule = $self->article_request_type_for_items( $borrower );
232 return $rule if $rule;
234 # If the record has no items that are requestable, go by the record itemtype
235 $rule = $self->article_request_type_for_bib($borrower);
236 return $rule if $rule;
238 return q{};
241 =head3 article_request_type_for_bib
243 my $type = $biblio->article_request_type_for_bib
245 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record
247 =cut
249 sub article_request_type_for_bib {
250 my ( $self, $borrower ) = @_;
252 return q{} unless $borrower;
254 my $borrowertype = $borrower->categorycode;
255 my $itemtype = $self->itemtype();
257 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowertype, itemtype => $itemtype });
259 return q{} unless $issuing_rule;
260 return $issuing_rule->article_requests || q{}
263 =head3 article_request_type_for_items
265 my $type = $biblio->article_request_type_for_items
267 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record's items
269 If there is a conflict where some items are 'bib_only' and some are 'item_only', 'bib_only' will be returned.
271 =cut
273 sub article_request_type_for_items {
274 my ( $self, $borrower ) = @_;
276 my $counts;
277 foreach my $item ( $self->items()->as_list() ) {
278 my $rule = $item->article_request_type($borrower);
279 return $rule if $rule eq 'bib_only'; # we don't need to go any further
280 $counts->{$rule}++;
283 return 'item_only' if $counts->{item_only};
284 return 'yes' if $counts->{yes};
285 return 'no' if $counts->{no};
286 return q{};
289 =head3 article_requests
291 my @requests = $biblio->article_requests
293 Returns the article requests associated with this Biblio
295 =cut
297 sub article_requests {
298 my ( $self, $borrower ) = @_;
300 $self->{_article_requests} ||= Koha::ArticleRequests->search( { biblionumber => $self->biblionumber() } );
302 return wantarray ? $self->{_article_requests}->as_list : $self->{_article_requests};
305 =head3 article_requests_current
307 my @requests = $biblio->article_requests_current
309 Returns the article requests associated with this Biblio that are incomplete
311 =cut
313 sub article_requests_current {
314 my ( $self, $borrower ) = @_;
316 $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
318 biblionumber => $self->biblionumber(),
319 -or => [
320 { status => Koha::ArticleRequest::Status::Pending },
321 { status => Koha::ArticleRequest::Status::Processing }
326 return wantarray ? $self->{_article_requests_current}->as_list : $self->{_article_requests_current};
329 =head3 article_requests_finished
331 my @requests = $biblio->article_requests_finished
333 Returns the article requests associated with this Biblio that are completed
335 =cut
337 sub article_requests_finished {
338 my ( $self, $borrower ) = @_;
340 $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
342 biblionumber => $self->biblionumber(),
343 -or => [
344 { status => Koha::ArticleRequest::Status::Completed },
345 { status => Koha::ArticleRequest::Status::Canceled }
350 return wantarray ? $self->{_article_requests_finished}->as_list : $self->{_article_requests_finished};
353 =head3 items
355 my $items = $biblio->items();
357 Returns the related Koha::Items object for this biblio
359 =cut
361 sub items {
362 my ($self) = @_;
364 my $items_rs = $self->_result->items;
366 return Koha::Items->_new_from_dbic( $items_rs );
369 =head3 itemtype
371 my $itemtype = $biblio->itemtype();
373 Returns the itemtype for this record.
375 =cut
377 sub itemtype {
378 my ( $self ) = @_;
380 return $self->biblioitem()->itemtype();
383 =head3 holds
385 my $holds = $biblio->holds();
387 return the current holds placed on this record
389 =cut
391 sub holds {
392 my ( $self, $params, $attributes ) = @_;
393 $attributes->{order_by} = 'priority' unless exists $attributes->{order_by};
394 my $hold_rs = $self->_result->reserves->search( $params, $attributes );
395 return Koha::Holds->_new_from_dbic($hold_rs);
398 =head3 current_holds
400 my $holds = $biblio->current_holds
402 Return the holds placed on this bibliographic record.
403 It does not include future holds.
405 =cut
407 sub current_holds {
408 my ($self) = @_;
409 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
410 return $self->holds(
411 { reservedate => { '<=' => $dtf->format_date(dt_from_string) } } );
414 =head3 biblioitem
416 my $field = $self->biblioitem()->itemtype
418 Returns the related Koha::Biblioitem object for this Biblio object
420 =cut
422 sub biblioitem {
423 my ($self) = @_;
425 $self->{_biblioitem} ||= Koha::Biblioitems->find( { biblionumber => $self->biblionumber() } );
427 return $self->{_biblioitem};
430 =head3 subscriptions
432 my $subscriptions = $self->subscriptions
434 Returns the related Koha::Subscriptions object for this Biblio object
436 =cut
438 sub subscriptions {
439 my ($self) = @_;
441 $self->{_subscriptions} ||= Koha::Subscriptions->search( { biblionumber => $self->biblionumber } );
443 return $self->{_subscriptions};
446 =head3 has_items_waiting_or_intransit
448 my $itemsWaitingOrInTransit = $biblio->has_items_waiting_or_intransit
450 Tells if this bibliographic record has items waiting or in transit.
452 =cut
454 sub has_items_waiting_or_intransit {
455 my ( $self ) = @_;
457 if ( Koha::Holds->search({ biblionumber => $self->id,
458 found => ['W', 'T'] })->count ) {
459 return 1;
462 foreach my $item ( $self->items->as_list ) {
463 return 1 if $item->get_transfer;
466 return 0;
469 =head2 get_coins
471 my $coins = $biblio->get_coins;
473 Returns the COinS (a span) which can be included in a biblio record
475 =cut
477 sub get_coins {
478 my ( $self ) = @_;
480 my $record = $self->metadata->record;
482 my $pos7 = substr $record->leader(), 7, 1;
483 my $pos6 = substr $record->leader(), 6, 1;
484 my $mtx;
485 my $genre;
486 my ( $aulast, $aufirst ) = ( '', '' );
487 my @authors;
488 my $title;
489 my $hosttitle;
490 my $pubyear = '';
491 my $isbn = '';
492 my $issn = '';
493 my $publisher = '';
494 my $pages = '';
495 my $titletype = '';
497 # For the purposes of generating COinS metadata, LDR/06-07 can be
498 # considered the same for UNIMARC and MARC21
499 my $fmts6 = {
500 'a' => 'book',
501 'b' => 'manuscript',
502 'c' => 'book',
503 'd' => 'manuscript',
504 'e' => 'map',
505 'f' => 'map',
506 'g' => 'film',
507 'i' => 'audioRecording',
508 'j' => 'audioRecording',
509 'k' => 'artwork',
510 'l' => 'document',
511 'm' => 'computerProgram',
512 'o' => 'document',
513 'r' => 'document',
515 my $fmts7 = {
516 'a' => 'journalArticle',
517 's' => 'journal',
520 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
522 if ( $genre eq 'book' ) {
523 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
526 ##### We must transform mtx to a valable mtx and document type ####
527 if ( $genre eq 'book' ) {
528 $mtx = 'book';
529 $titletype = 'b';
530 } elsif ( $genre eq 'journal' ) {
531 $mtx = 'journal';
532 $titletype = 'j';
533 } elsif ( $genre eq 'journalArticle' ) {
534 $mtx = 'journal';
535 $genre = 'article';
536 $titletype = 'a';
537 } else {
538 $mtx = 'dc';
541 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
543 # Setting datas
544 $aulast = $record->subfield( '700', 'a' ) || '';
545 $aufirst = $record->subfield( '700', 'b' ) || '';
546 push @authors, "$aufirst $aulast" if ($aufirst or $aulast);
548 # others authors
549 if ( $record->field('200') ) {
550 for my $au ( $record->field('200')->subfield('g') ) {
551 push @authors, $au;
555 $title = $record->subfield( '200', 'a' );
556 my $subfield_210d = $record->subfield('210', 'd');
557 if ($subfield_210d and $subfield_210d =~ /(\d{4})/) {
558 $pubyear = $1;
560 $publisher = $record->subfield( '210', 'c' ) || '';
561 $isbn = $record->subfield( '010', 'a' ) || '';
562 $issn = $record->subfield( '011', 'a' ) || '';
563 } else {
565 # MARC21 need some improve
567 # Setting datas
568 if ( $record->field('100') ) {
569 push @authors, $record->subfield( '100', 'a' );
572 # others authors
573 if ( $record->field('700') ) {
574 for my $au ( $record->field('700')->subfield('a') ) {
575 push @authors, $au;
578 $title = $record->subfield( '245', 'a' ) . $record->subfield( '245', 'b' );
579 if ($titletype eq 'a') {
580 $pubyear = $record->field('008') || '';
581 $pubyear = substr($pubyear->data(), 7, 4) if $pubyear;
582 $isbn = $record->subfield( '773', 'z' ) || '';
583 $issn = $record->subfield( '773', 'x' ) || '';
584 $hosttitle = $record->subfield( '773', 't' ) || $record->subfield( '773', 'a') || q{};
585 my @rels = $record->subfield( '773', 'g' );
586 $pages = join(', ', @rels);
587 } else {
588 $pubyear = $record->subfield( '260', 'c' ) || '';
589 $publisher = $record->subfield( '260', 'b' ) || '';
590 $isbn = $record->subfield( '020', 'a' ) || '';
591 $issn = $record->subfield( '022', 'a' ) || '';
596 my @params = (
597 [ 'ctx_ver', 'Z39.88-2004' ],
598 [ 'rft_val_fmt', "info:ofi/fmt:kev:mtx:$mtx" ],
599 [ ($mtx eq 'dc' ? 'rft.type' : 'rft.genre'), $genre ],
600 [ "rft.${titletype}title", $title ],
603 # rft.title is authorized only once, so by checking $titletype
604 # we ensure that rft.title is not already in the list.
605 if ($hosttitle and $titletype) {
606 push @params, [ 'rft.title', $hosttitle ];
609 push @params, (
610 [ 'rft.isbn', $isbn ],
611 [ 'rft.issn', $issn ],
614 # If it's a subscription, these informations have no meaning.
615 if ($genre ne 'journal') {
616 push @params, (
617 [ 'rft.aulast', $aulast ],
618 [ 'rft.aufirst', $aufirst ],
619 (map { [ 'rft.au', $_ ] } @authors),
620 [ 'rft.pub', $publisher ],
621 [ 'rft.date', $pubyear ],
622 [ 'rft.pages', $pages ],
626 my $coins_value = join( '&amp;',
627 map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params );
629 return $coins_value;
632 =head2 get_openurl
634 my $url = $biblio->get_openurl;
636 Returns url for OpenURL resolver set in OpenURLResolverURL system preference
638 =cut
640 sub get_openurl {
641 my ( $self ) = @_;
643 my $OpenURLResolverURL = C4::Context->preference('OpenURLResolverURL');
645 if ($OpenURLResolverURL) {
646 my $uri = URI->new($OpenURLResolverURL);
648 if (not defined $uri->query) {
649 $OpenURLResolverURL .= '?';
650 } else {
651 $OpenURLResolverURL .= '&amp;';
653 $OpenURLResolverURL .= $self->get_coins;
656 return $OpenURLResolverURL;
659 =head3 type
661 =cut
663 sub _type {
664 return 'Biblio';
667 =head1 AUTHOR
669 Kyle M Hall <kyle@bywatersolutions.com>
671 =cut