Bug 22566: Fix some more issues
[koha.git] / Koha / Biblio.pm
1 package Koha::Biblio;
2
3 # Copyright ByWater Solutions 2014
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
15 #
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.
19
20 use Modern::Perl;
21
22 use Carp;
23 use List::MoreUtils qw(any);
24 use URI;
25 use URI::Escape;
26
27 use C4::Biblio qw();
28
29 use Koha::Database;
30 use Koha::DateUtils qw( dt_from_string );
31
32 use base qw(Koha::Object);
33
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;
43
44 =head1 NAME
45
46 Koha::Biblio - Koha Biblio Object class
47
48 =head1 API
49
50 =head2 Class Methods
51
52 =cut
53
54 =head3 store
55
56 Overloaded I<store> method to set default values
57
58 =cut
59
60 sub store {
61     my ( $self ) = @_;
62
63     $self->datecreated( dt_from_string ) unless $self->datecreated;
64
65     return $self->SUPER::store;
66 }
67
68 =head3 metadata
69
70 my $metadata = $biblio->metadata();
71
72 Returns a Koha::Biblio::Metadata object
73
74 =cut
75
76 sub metadata {
77     my ( $self ) = @_;
78
79     my $metadata = $self->_result->metadata;
80     return Koha::Biblio::Metadata->_new_from_dbic($metadata);
81 }
82
83 =head3 subtitles
84
85 my @subtitles = $biblio->subtitles();
86
87 Returns list of subtitles for a record.
88
89 Keyword to MARC mapping for subtitle must be set for this method to return any possible values.
90
91 =cut
92
93 sub subtitles {
94     my ( $self ) = @_;
95
96     return map { $_->{subfield} } @{
97         C4::Biblio::GetRecordValue(
98             'subtitle',
99             C4::Biblio::GetMarcBiblio({ biblionumber => $self->id }),
100             $self->frameworkcode ) };
101 }
102
103 =head3 can_article_request
104
105 my $bool = $biblio->can_article_request( $borrower );
106
107 Returns true if article requests can be made for this record
108
109 $borrower must be a Koha::Patron object
110
111 =cut
112
113 sub can_article_request {
114     my ( $self, $borrower ) = @_;
115
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';
119
120     return q{};
121 }
122
123 =head3 can_be_transferred
124
125 $biblio->can_be_transferred({ to => $to_library, from => $from_library })
126
127 Checks if at least one item of a biblio can be transferred to given library.
128
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
133
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().
136
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
143
144 Returns 1 if at least one of the item of a biblio can be transferred
145 to $to_library, otherwise 0.
146
147 =cut
148
149 sub can_be_transferred {
150     my ($self, $params) = @_;
151
152     my $to   = $params->{to};
153     my $from = $params->{from};
154
155     return 1 unless C4::Context->preference('UseBranchTransferLimits');
156     my $limittype = C4::Context->preference('BranchTransferLimitsType');
157
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;
168     }
169
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;
186     }
187
188     return 0;
189 }
190
191 =head3 hidden_in_opac
192
193 my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
194
195 Returns true if the biblio matches the hidding criteria defined in $rules.
196 Returns false otherwise.
197
198 Takes HASHref that can have the following parameters:
199     OPTIONAL PARAMETERS:
200     $rules : { <field> => [ value_1, ... ], ... }
201
202 Note: $rules inherits its structure from the parsed YAML from reading
203 the I<OpacHiddenItems> system preference.
204
205 =cut
206
207 sub hidden_in_opac {
208     my ( $self, $params ) = @_;
209
210     my $rules = $params->{rules} // {};
211
212     return !(any { !$_->hidden_in_opac({ rules => $rules }) } $self->items->as_list);
213 }
214
215 =head3 article_request_type
216
217 my $type = $biblio->article_request_type( $borrower );
218
219 Returns the article request type based on items, or on the record
220 itself if there are no items.
221
222 $borrower must be a Koha::Patron object
223
224 =cut
225
226 sub article_request_type {
227     my ( $self, $borrower ) = @_;
228
229     return q{} unless $borrower;
230
231     my $rule = $self->article_request_type_for_items( $borrower );
232     return $rule if $rule;
233
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;
237
238     return q{};
239 }
240
241 =head3 article_request_type_for_bib
242
243 my $type = $biblio->article_request_type_for_bib
244
245 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record
246
247 =cut
248
249 sub article_request_type_for_bib {
250     my ( $self, $borrower ) = @_;
251
252     return q{} unless $borrower;
253
254     my $borrowertype = $borrower->categorycode;
255     my $itemtype     = $self->itemtype();
256
257     my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowertype, itemtype => $itemtype });
258
259     return q{} unless $issuing_rule;
260     return $issuing_rule->article_requests || q{}
261 }
262
263 =head3 article_request_type_for_items
264
265 my $type = $biblio->article_request_type_for_items
266
267 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record's items
268
269 If there is a conflict where some items are 'bib_only' and some are 'item_only', 'bib_only' will be returned.
270
271 =cut
272
273 sub article_request_type_for_items {
274     my ( $self, $borrower ) = @_;
275
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}++;
281     }
282
283     return 'item_only' if $counts->{item_only};
284     return 'yes'       if $counts->{yes};
285     return 'no'        if $counts->{no};
286     return q{};
287 }
288
289 =head3 article_requests
290
291 my @requests = $biblio->article_requests
292
293 Returns the article requests associated with this Biblio
294
295 =cut
296
297 sub article_requests {
298     my ( $self, $borrower ) = @_;
299
300     $self->{_article_requests} ||= Koha::ArticleRequests->search( { biblionumber => $self->biblionumber() } );
301
302     return wantarray ? $self->{_article_requests}->as_list : $self->{_article_requests};
303 }
304
305 =head3 article_requests_current
306
307 my @requests = $biblio->article_requests_current
308
309 Returns the article requests associated with this Biblio that are incomplete
310
311 =cut
312
313 sub article_requests_current {
314     my ( $self, $borrower ) = @_;
315
316     $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
317         {
318             biblionumber => $self->biblionumber(),
319             -or          => [
320                 { status => Koha::ArticleRequest::Status::Pending },
321                 { status => Koha::ArticleRequest::Status::Processing }
322             ]
323         }
324     );
325
326     return wantarray ? $self->{_article_requests_current}->as_list : $self->{_article_requests_current};
327 }
328
329 =head3 article_requests_finished
330
331 my @requests = $biblio->article_requests_finished
332
333 Returns the article requests associated with this Biblio that are completed
334
335 =cut
336
337 sub article_requests_finished {
338     my ( $self, $borrower ) = @_;
339
340     $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
341         {
342             biblionumber => $self->biblionumber(),
343             -or          => [
344                 { status => Koha::ArticleRequest::Status::Completed },
345                 { status => Koha::ArticleRequest::Status::Canceled }
346             ]
347         }
348     );
349
350     return wantarray ? $self->{_article_requests_finished}->as_list : $self->{_article_requests_finished};
351 }
352
353 =head3 items
354
355 my $items = $biblio->items();
356
357 Returns the related Koha::Items object for this biblio
358
359 =cut
360
361 sub items {
362     my ($self) = @_;
363
364     my $items_rs = $self->_result->items;
365
366     return Koha::Items->_new_from_dbic( $items_rs );
367 }
368
369 =head3 itemtype
370
371 my $itemtype = $biblio->itemtype();
372
373 Returns the itemtype for this record.
374
375 =cut
376
377 sub itemtype {
378     my ( $self ) = @_;
379
380     return $self->biblioitem()->itemtype();
381 }
382
383 =head3 holds
384
385 my $holds = $biblio->holds();
386
387 return the current holds placed on this record
388
389 =cut
390
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);
396 }
397
398 =head3 current_holds
399
400 my $holds = $biblio->current_holds
401
402 Return the holds placed on this bibliographic record.
403 It does not include future holds.
404
405 =cut
406
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) } } );
412 }
413
414 =head3 biblioitem
415
416 my $field = $self->biblioitem()->itemtype
417
418 Returns the related Koha::Biblioitem object for this Biblio object
419
420 =cut
421
422 sub biblioitem {
423     my ($self) = @_;
424
425     $self->{_biblioitem} ||= Koha::Biblioitems->find( { biblionumber => $self->biblionumber() } );
426
427     return $self->{_biblioitem};
428 }
429
430 =head3 subscriptions
431
432 my $subscriptions = $self->subscriptions
433
434 Returns the related Koha::Subscriptions object for this Biblio object
435
436 =cut
437
438 sub subscriptions {
439     my ($self) = @_;
440
441     $self->{_subscriptions} ||= Koha::Subscriptions->search( { biblionumber => $self->biblionumber } );
442
443     return $self->{_subscriptions};
444 }
445
446 =head3 has_items_waiting_or_intransit
447
448 my $itemsWaitingOrInTransit = $biblio->has_items_waiting_or_intransit
449
450 Tells if this bibliographic record has items waiting or in transit.
451
452 =cut
453
454 sub has_items_waiting_or_intransit {
455     my ( $self ) = @_;
456
457     if ( Koha::Holds->search({ biblionumber => $self->id,
458                                found => ['W', 'T'] })->count ) {
459         return 1;
460     }
461
462     foreach my $item ( $self->items->as_list ) {
463         return 1 if $item->get_transfer;
464     }
465
466     return 0;
467 }
468
469 =head2 get_coins
470
471 my $coins = $biblio->get_coins;
472
473 Returns the COinS (a span) which can be included in a biblio record
474
475 =cut
476
477 sub get_coins {
478     my ( $self ) = @_;
479
480     my $record = $self->metadata->record;
481
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 = '';
496
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',
514     };
515     my $fmts7 = {
516         'a' => 'journalArticle',
517         's' => 'journal',
518     };
519
520     $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
521
522     if ( $genre eq 'book' ) {
523             $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
524     }
525
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';
539     }
540
541     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
542
543         # Setting datas
544         $aulast  = $record->subfield( '700', 'a' ) || '';
545         $aufirst = $record->subfield( '700', 'b' ) || '';
546         push @authors, "$aufirst $aulast" if ($aufirst or $aulast);
547
548         # others authors
549         if ( $record->field('200') ) {
550             for my $au ( $record->field('200')->subfield('g') ) {
551                 push @authors, $au;
552             }
553         }
554
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;
559         }
560         $publisher = $record->subfield( '210', 'c' ) || '';
561         $isbn      = $record->subfield( '010', 'a' ) || '';
562         $issn      = $record->subfield( '011', 'a' ) || '';
563     } else {
564
565         # MARC21 need some improve
566
567         # Setting datas
568         if ( $record->field('100') ) {
569             push @authors, $record->subfield( '100', 'a' );
570         }
571
572         # others authors
573         if ( $record->field('700') ) {
574             for my $au ( $record->field('700')->subfield('a') ) {
575                 push @authors, $au;
576             }
577         }
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' ) || '';
592         }
593
594     }
595
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 ],
601     );
602
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 ];
607     }
608
609     push @params, (
610         [ 'rft.isbn', $isbn ],
611         [ 'rft.issn', $issn ],
612     );
613
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 ],
623         );
624     }
625
626     my $coins_value = join( '&amp;',
627         map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params );
628
629     return $coins_value;
630 }
631
632 =head2 get_openurl
633
634 my $url = $biblio->get_openurl;
635
636 Returns url for OpenURL resolver set in OpenURLResolverURL system preference
637
638 =cut
639
640 sub get_openurl {
641     my ( $self ) = @_;
642
643     my $OpenURLResolverURL = C4::Context->preference('OpenURLResolverURL');
644
645     if ($OpenURLResolverURL) {
646         my $uri = URI->new($OpenURLResolverURL);
647
648         if (not defined $uri->query) {
649             $OpenURLResolverURL .= '?';
650         } else {
651             $OpenURLResolverURL .= '&amp;';
652         }
653         $OpenURLResolverURL .= $self->get_coins;
654     }
655
656     return $OpenURLResolverURL;
657 }
658
659 =head3 type
660
661 =cut
662
663 sub _type {
664     return 'Biblio';
665 }
666
667 =head1 AUTHOR
668
669 Kyle M Hall <kyle@bywatersolutions.com>
670
671 =cut
672
673 1;