Bug 23089: Unit tests
[koha.git] / Koha / Biblio.pm
blobb5ffe81642968cf1e947c213b88513fb3ce36446
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::Koha;
28 use C4::Biblio qw();
30 use Koha::Database;
31 use Koha::DateUtils qw( dt_from_string );
33 use base qw(Koha::Object);
35 use Koha::ArticleRequest::Status;
36 use Koha::ArticleRequests;
37 use Koha::Biblio::Metadatas;
38 use Koha::Biblioitems;
39 use Koha::IssuingRules;
40 use Koha::Item::Transfer::Limits;
41 use Koha::Items;
42 use Koha::Libraries;
43 use Koha::Subscriptions;
45 =head1 NAME
47 Koha::Biblio - Koha Biblio Object class
49 =head1 API
51 =head2 Class Methods
53 =cut
55 =head3 store
57 Overloaded I<store> method to set default values
59 =cut
61 sub store {
62 my ( $self ) = @_;
64 $self->datecreated( dt_from_string ) unless $self->datecreated;
66 return $self->SUPER::store;
69 =head3 metadata
71 my $metadata = $biblio->metadata();
73 Returns a Koha::Biblio::Metadata object
75 =cut
77 sub metadata {
78 my ( $self ) = @_;
80 my $metadata = $self->_result->metadata;
81 return Koha::Biblio::Metadata->_new_from_dbic($metadata);
84 =head3 can_article_request
86 my $bool = $biblio->can_article_request( $borrower );
88 Returns true if article requests can be made for this record
90 $borrower must be a Koha::Patron object
92 =cut
94 sub can_article_request {
95 my ( $self, $borrower ) = @_;
97 my $rule = $self->article_request_type($borrower);
98 return q{} if $rule eq 'item_only' && !$self->items()->count();
99 return 1 if $rule && $rule ne 'no';
101 return q{};
104 =head3 can_be_transferred
106 $biblio->can_be_transferred({ to => $to_library, from => $from_library })
108 Checks if at least one item of a biblio can be transferred to given library.
110 This feature is controlled by two system preferences:
111 UseBranchTransferLimits to enable / disable the feature
112 BranchTransferLimitsType to use either an itemnumber or ccode as an identifier
113 for setting the limitations
115 Performance-wise, it is recommended to use this method for a biblio instead of
116 iterating each item of a biblio with Koha::Item->can_be_transferred().
118 Takes HASHref that can have the following parameters:
119 MANDATORY PARAMETERS:
120 $to : Koha::Library
121 OPTIONAL PARAMETERS:
122 $from : Koha::Library # if given, only items from that
123 # holdingbranch are considered
125 Returns 1 if at least one of the item of a biblio can be transferred
126 to $to_library, otherwise 0.
128 =cut
130 sub can_be_transferred {
131 my ($self, $params) = @_;
133 my $to = $params->{to};
134 my $from = $params->{from};
136 return 1 unless C4::Context->preference('UseBranchTransferLimits');
137 my $limittype = C4::Context->preference('BranchTransferLimitsType');
139 my $items;
140 foreach my $item_of_bib ($self->items->as_list) {
141 next unless $item_of_bib->holdingbranch;
142 next if $from && $from->branchcode ne $item_of_bib->holdingbranch;
143 return 1 if $item_of_bib->holdingbranch eq $to->branchcode;
144 my $code = $limittype eq 'itemtype'
145 ? $item_of_bib->effective_itemtype
146 : $item_of_bib->ccode;
147 return 1 unless $code;
148 $items->{$code}->{$item_of_bib->holdingbranch} = 1;
151 # At this point we will have a HASHref containing each itemtype/ccode that
152 # this biblio has, inside which are all of the holdingbranches where those
153 # items are located at. Then, we will query Koha::Item::Transfer::Limits to
154 # find out whether a transfer limits for such $limittype from any of the
155 # listed holdingbranches to the given $to library exist. If at least one
156 # holdingbranch for that $limittype does not have a transfer limit to given
157 # $to library, then we know that the transfer is possible.
158 foreach my $code (keys %{$items}) {
159 my @holdingbranches = keys %{$items->{$code}};
160 return 1 if Koha::Item::Transfer::Limits->search({
161 toBranch => $to->branchcode,
162 fromBranch => { 'in' => \@holdingbranches },
163 $limittype => $code
164 }, {
165 group_by => [qw/fromBranch/]
166 })->count == scalar(@holdingbranches) ? 0 : 1;
169 return 0;
172 =head3 hidden_in_opac
174 my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
176 Returns true if the biblio matches the hidding criteria defined in $rules.
177 Returns false otherwise.
179 Takes HASHref that can have the following parameters:
180 OPTIONAL PARAMETERS:
181 $rules : { <field> => [ value_1, ... ], ... }
183 Note: $rules inherits its structure from the parsed YAML from reading
184 the I<OpacHiddenItems> system preference.
186 =cut
188 sub hidden_in_opac {
189 my ( $self, $params ) = @_;
191 my $rules = $params->{rules} // {};
193 my @items = $self->items->as_list;
195 return 0 unless @items; # Do not hide if there is no item
197 return !(any { !$_->hidden_in_opac({ rules => $rules }) } @items);
200 =head3 article_request_type
202 my $type = $biblio->article_request_type( $borrower );
204 Returns the article request type based on items, or on the record
205 itself if there are no items.
207 $borrower must be a Koha::Patron object
209 =cut
211 sub article_request_type {
212 my ( $self, $borrower ) = @_;
214 return q{} unless $borrower;
216 my $rule = $self->article_request_type_for_items( $borrower );
217 return $rule if $rule;
219 # If the record has no items that are requestable, go by the record itemtype
220 $rule = $self->article_request_type_for_bib($borrower);
221 return $rule if $rule;
223 return q{};
226 =head3 article_request_type_for_bib
228 my $type = $biblio->article_request_type_for_bib
230 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record
232 =cut
234 sub article_request_type_for_bib {
235 my ( $self, $borrower ) = @_;
237 return q{} unless $borrower;
239 my $borrowertype = $borrower->categorycode;
240 my $itemtype = $self->itemtype();
242 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowertype, itemtype => $itemtype });
244 return q{} unless $issuing_rule;
245 return $issuing_rule->article_requests || q{}
248 =head3 article_request_type_for_items
250 my $type = $biblio->article_request_type_for_items
252 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record's items
254 If there is a conflict where some items are 'bib_only' and some are 'item_only', 'bib_only' will be returned.
256 =cut
258 sub article_request_type_for_items {
259 my ( $self, $borrower ) = @_;
261 my $counts;
262 foreach my $item ( $self->items()->as_list() ) {
263 my $rule = $item->article_request_type($borrower);
264 return $rule if $rule eq 'bib_only'; # we don't need to go any further
265 $counts->{$rule}++;
268 return 'item_only' if $counts->{item_only};
269 return 'yes' if $counts->{yes};
270 return 'no' if $counts->{no};
271 return q{};
274 =head3 article_requests
276 my @requests = $biblio->article_requests
278 Returns the article requests associated with this Biblio
280 =cut
282 sub article_requests {
283 my ( $self, $borrower ) = @_;
285 $self->{_article_requests} ||= Koha::ArticleRequests->search( { biblionumber => $self->biblionumber() } );
287 return wantarray ? $self->{_article_requests}->as_list : $self->{_article_requests};
290 =head3 article_requests_current
292 my @requests = $biblio->article_requests_current
294 Returns the article requests associated with this Biblio that are incomplete
296 =cut
298 sub article_requests_current {
299 my ( $self, $borrower ) = @_;
301 $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
303 biblionumber => $self->biblionumber(),
304 -or => [
305 { status => Koha::ArticleRequest::Status::Pending },
306 { status => Koha::ArticleRequest::Status::Processing }
311 return wantarray ? $self->{_article_requests_current}->as_list : $self->{_article_requests_current};
314 =head3 article_requests_finished
316 my @requests = $biblio->article_requests_finished
318 Returns the article requests associated with this Biblio that are completed
320 =cut
322 sub article_requests_finished {
323 my ( $self, $borrower ) = @_;
325 $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
327 biblionumber => $self->biblionumber(),
328 -or => [
329 { status => Koha::ArticleRequest::Status::Completed },
330 { status => Koha::ArticleRequest::Status::Canceled }
335 return wantarray ? $self->{_article_requests_finished}->as_list : $self->{_article_requests_finished};
338 =head3 items
340 my $items = $biblio->items();
342 Returns the related Koha::Items object for this biblio
344 =cut
346 sub items {
347 my ($self) = @_;
349 my $items_rs = $self->_result->items;
351 return Koha::Items->_new_from_dbic( $items_rs );
354 =head3 itemtype
356 my $itemtype = $biblio->itemtype();
358 Returns the itemtype for this record.
360 =cut
362 sub itemtype {
363 my ( $self ) = @_;
365 return $self->biblioitem()->itemtype();
368 =head3 holds
370 my $holds = $biblio->holds();
372 return the current holds placed on this record
374 =cut
376 sub holds {
377 my ( $self, $params, $attributes ) = @_;
378 $attributes->{order_by} = 'priority' unless exists $attributes->{order_by};
379 my $hold_rs = $self->_result->reserves->search( $params, $attributes );
380 return Koha::Holds->_new_from_dbic($hold_rs);
383 =head3 current_holds
385 my $holds = $biblio->current_holds
387 Return the holds placed on this bibliographic record.
388 It does not include future holds.
390 =cut
392 sub current_holds {
393 my ($self) = @_;
394 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
395 return $self->holds(
396 { reservedate => { '<=' => $dtf->format_date(dt_from_string) } } );
399 =head3 biblioitem
401 my $field = $self->biblioitem()->itemtype
403 Returns the related Koha::Biblioitem object for this Biblio object
405 =cut
407 sub biblioitem {
408 my ($self) = @_;
410 $self->{_biblioitem} ||= Koha::Biblioitems->find( { biblionumber => $self->biblionumber() } );
412 return $self->{_biblioitem};
415 =head3 subscriptions
417 my $subscriptions = $self->subscriptions
419 Returns the related Koha::Subscriptions object for this Biblio object
421 =cut
423 sub subscriptions {
424 my ($self) = @_;
426 $self->{_subscriptions} ||= Koha::Subscriptions->search( { biblionumber => $self->biblionumber } );
428 return $self->{_subscriptions};
431 =head3 has_items_waiting_or_intransit
433 my $itemsWaitingOrInTransit = $biblio->has_items_waiting_or_intransit
435 Tells if this bibliographic record has items waiting or in transit.
437 =cut
439 sub has_items_waiting_or_intransit {
440 my ( $self ) = @_;
442 if ( Koha::Holds->search({ biblionumber => $self->id,
443 found => ['W', 'T'] })->count ) {
444 return 1;
447 foreach my $item ( $self->items->as_list ) {
448 return 1 if $item->get_transfer;
451 return 0;
454 =head2 get_coins
456 my $coins = $biblio->get_coins;
458 Returns the COinS (a span) which can be included in a biblio record
460 =cut
462 sub get_coins {
463 my ( $self ) = @_;
465 my $record = $self->metadata->record;
467 my $pos7 = substr $record->leader(), 7, 1;
468 my $pos6 = substr $record->leader(), 6, 1;
469 my $mtx;
470 my $genre;
471 my ( $aulast, $aufirst ) = ( '', '' );
472 my @authors;
473 my $title;
474 my $hosttitle;
475 my $pubyear = '';
476 my $isbn = '';
477 my $issn = '';
478 my $publisher = '';
479 my $pages = '';
480 my $titletype = '';
482 # For the purposes of generating COinS metadata, LDR/06-07 can be
483 # considered the same for UNIMARC and MARC21
484 my $fmts6 = {
485 'a' => 'book',
486 'b' => 'manuscript',
487 'c' => 'book',
488 'd' => 'manuscript',
489 'e' => 'map',
490 'f' => 'map',
491 'g' => 'film',
492 'i' => 'audioRecording',
493 'j' => 'audioRecording',
494 'k' => 'artwork',
495 'l' => 'document',
496 'm' => 'computerProgram',
497 'o' => 'document',
498 'r' => 'document',
500 my $fmts7 = {
501 'a' => 'journalArticle',
502 's' => 'journal',
505 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
507 if ( $genre eq 'book' ) {
508 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
511 ##### We must transform mtx to a valable mtx and document type ####
512 if ( $genre eq 'book' ) {
513 $mtx = 'book';
514 $titletype = 'b';
515 } elsif ( $genre eq 'journal' ) {
516 $mtx = 'journal';
517 $titletype = 'j';
518 } elsif ( $genre eq 'journalArticle' ) {
519 $mtx = 'journal';
520 $genre = 'article';
521 $titletype = 'a';
522 } else {
523 $mtx = 'dc';
526 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
528 # Setting datas
529 $aulast = $record->subfield( '700', 'a' ) || '';
530 $aufirst = $record->subfield( '700', 'b' ) || '';
531 push @authors, "$aufirst $aulast" if ($aufirst or $aulast);
533 # others authors
534 if ( $record->field('200') ) {
535 for my $au ( $record->field('200')->subfield('g') ) {
536 push @authors, $au;
540 $title = $record->subfield( '200', 'a' );
541 my $subfield_210d = $record->subfield('210', 'd');
542 if ($subfield_210d and $subfield_210d =~ /(\d{4})/) {
543 $pubyear = $1;
545 $publisher = $record->subfield( '210', 'c' ) || '';
546 $isbn = $record->subfield( '010', 'a' ) || '';
547 $issn = $record->subfield( '011', 'a' ) || '';
548 } else {
550 # MARC21 need some improve
552 # Setting datas
553 if ( $record->field('100') ) {
554 push @authors, $record->subfield( '100', 'a' );
557 # others authors
558 if ( $record->field('700') ) {
559 for my $au ( $record->field('700')->subfield('a') ) {
560 push @authors, $au;
563 $title = $record->field('245')->as_string('ab');
564 if ($titletype eq 'a') {
565 $pubyear = $record->field('008') || '';
566 $pubyear = substr($pubyear->data(), 7, 4) if $pubyear;
567 $isbn = $record->subfield( '773', 'z' ) || '';
568 $issn = $record->subfield( '773', 'x' ) || '';
569 $hosttitle = $record->subfield( '773', 't' ) || $record->subfield( '773', 'a') || q{};
570 my @rels = $record->subfield( '773', 'g' );
571 $pages = join(', ', @rels);
572 } else {
573 $pubyear = $record->subfield( '260', 'c' ) || '';
574 $publisher = $record->subfield( '260', 'b' ) || '';
575 $isbn = $record->subfield( '020', 'a' ) || '';
576 $issn = $record->subfield( '022', 'a' ) || '';
581 my @params = (
582 [ 'ctx_ver', 'Z39.88-2004' ],
583 [ 'rft_val_fmt', "info:ofi/fmt:kev:mtx:$mtx" ],
584 [ ($mtx eq 'dc' ? 'rft.type' : 'rft.genre'), $genre ],
585 [ "rft.${titletype}title", $title ],
588 # rft.title is authorized only once, so by checking $titletype
589 # we ensure that rft.title is not already in the list.
590 if ($hosttitle and $titletype) {
591 push @params, [ 'rft.title', $hosttitle ];
594 push @params, (
595 [ 'rft.isbn', $isbn ],
596 [ 'rft.issn', $issn ],
599 # If it's a subscription, these informations have no meaning.
600 if ($genre ne 'journal') {
601 push @params, (
602 [ 'rft.aulast', $aulast ],
603 [ 'rft.aufirst', $aufirst ],
604 (map { [ 'rft.au', $_ ] } @authors),
605 [ 'rft.pub', $publisher ],
606 [ 'rft.date', $pubyear ],
607 [ 'rft.pages', $pages ],
611 my $coins_value = join( '&amp;',
612 map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params );
614 return $coins_value;
617 =head2 get_openurl
619 my $url = $biblio->get_openurl;
621 Returns url for OpenURL resolver set in OpenURLResolverURL system preference
623 =cut
625 sub get_openurl {
626 my ( $self ) = @_;
628 my $OpenURLResolverURL = C4::Context->preference('OpenURLResolverURL');
630 if ($OpenURLResolverURL) {
631 my $uri = URI->new($OpenURLResolverURL);
633 if (not defined $uri->query) {
634 $OpenURLResolverURL .= '?';
635 } else {
636 $OpenURLResolverURL .= '&amp;';
638 $OpenURLResolverURL .= $self->get_coins;
641 return $OpenURLResolverURL;
644 =head3 is_serial
646 my $serial = $biblio->is_serial
648 Return boolean true if this bibbliographic record is continuing resource
650 =cut
652 sub is_serial {
653 my ( $self ) = @_;
655 return 1 if $self->serial;
657 my $record = $self->metadata->record;
658 return 1 if substr($record->leader, 7, 1) eq 's';
660 return 0;
663 =head3 custom_cover_image_url
665 my $image_url = $biblio->custom_cover_image_url
667 Return the specific url of the cover image for this bibliographic record.
668 It is built regaring the value of the system preference CustomCoverImagesURL
670 =cut
672 sub custom_cover_image_url {
673 my ( $self ) = @_;
674 my $url = C4::Context->preference('CustomCoverImagesURL');
675 if ( $url =~ m|{isbn}| ) {
676 my $isbn = $self->biblioitem->isbn;
677 $url =~ s|{isbn}|$isbn|g;
679 if ( $url =~ m|{normalized_isbn}| ) {
680 my $normalized_isbn = C4::Koha::GetNormalizedISBN($self->biblioitem->isbn);
681 $url =~ s|{normalized_isbn}|$normalized_isbn|g;
683 if ( $url =~ m|{issn}| ) {
684 my $issn = $self->biblioitem->issn;
685 $url =~ s|{issn}|$issn|g;
688 my $re = qr|{(?<field>\d{3})\$(?<subfield>.)}|;
689 if ( $url =~ $re ) {
690 my $field = $+{field};
691 my $subfield = $+{subfield};
692 my $marc_record = $self->metadata->record;
693 my $value = $marc_record->subfield($field, $subfield);
694 $url =~ s|$re|$value|;
697 return $url;
700 =head3 type
702 =cut
704 sub _type {
705 return 'Biblio';
708 =head1 AUTHOR
710 Kyle M Hall <kyle@bywatersolutions.com>
712 =cut