Bug 23237: Fix POD and typos
[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 can_article_request
84
85 my $bool = $biblio->can_article_request( $borrower );
86
87 Returns true if article requests can be made for this record
88
89 $borrower must be a Koha::Patron object
90
91 =cut
92
93 sub can_article_request {
94     my ( $self, $borrower ) = @_;
95
96     my $rule = $self->article_request_type($borrower);
97     return q{} if $rule eq 'item_only' && !$self->items()->count();
98     return 1 if $rule && $rule ne 'no';
99
100     return q{};
101 }
102
103 =head3 can_be_transferred
104
105 $biblio->can_be_transferred({ to => $to_library, from => $from_library })
106
107 Checks if at least one item of a biblio can be transferred to given library.
108
109 This feature is controlled by two system preferences:
110 UseBranchTransferLimits to enable / disable the feature
111 BranchTransferLimitsType to use either an itemnumber or ccode as an identifier
112                          for setting the limitations
113
114 Performance-wise, it is recommended to use this method for a biblio instead of
115 iterating each item of a biblio with Koha::Item->can_be_transferred().
116
117 Takes HASHref that can have the following parameters:
118     MANDATORY PARAMETERS:
119     $to   : Koha::Library
120     OPTIONAL PARAMETERS:
121     $from : Koha::Library # if given, only items from that
122                           # holdingbranch are considered
123
124 Returns 1 if at least one of the item of a biblio can be transferred
125 to $to_library, otherwise 0.
126
127 =cut
128
129 sub can_be_transferred {
130     my ($self, $params) = @_;
131
132     my $to   = $params->{to};
133     my $from = $params->{from};
134
135     return 1 unless C4::Context->preference('UseBranchTransferLimits');
136     my $limittype = C4::Context->preference('BranchTransferLimitsType');
137
138     my $items;
139     foreach my $item_of_bib ($self->items->as_list) {
140         next unless $item_of_bib->holdingbranch;
141         next if $from && $from->branchcode ne $item_of_bib->holdingbranch;
142         return 1 if $item_of_bib->holdingbranch eq $to->branchcode;
143         my $code = $limittype eq 'itemtype'
144             ? $item_of_bib->effective_itemtype
145             : $item_of_bib->ccode;
146         return 1 unless $code;
147         $items->{$code}->{$item_of_bib->holdingbranch} = 1;
148     }
149
150     # At this point we will have a HASHref containing each itemtype/ccode that
151     # this biblio has, inside which are all of the holdingbranches where those
152     # items are located at. Then, we will query Koha::Item::Transfer::Limits to
153     # find out whether a transfer limits for such $limittype from any of the
154     # listed holdingbranches to the given $to library exist. If at least one
155     # holdingbranch for that $limittype does not have a transfer limit to given
156     # $to library, then we know that the transfer is possible.
157     foreach my $code (keys %{$items}) {
158         my @holdingbranches = keys %{$items->{$code}};
159         return 1 if Koha::Item::Transfer::Limits->search({
160             toBranch => $to->branchcode,
161             fromBranch => { 'in' => \@holdingbranches },
162             $limittype => $code
163         }, {
164             group_by => [qw/fromBranch/]
165         })->count == scalar(@holdingbranches) ? 0 : 1;
166     }
167
168     return 0;
169 }
170
171 =head3 hidden_in_opac
172
173 my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
174
175 Returns true if the biblio matches the hidding criteria defined in $rules.
176 Returns false otherwise.
177
178 Takes HASHref that can have the following parameters:
179     OPTIONAL PARAMETERS:
180     $rules : { <field> => [ value_1, ... ], ... }
181
182 Note: $rules inherits its structure from the parsed YAML from reading
183 the I<OpacHiddenItems> system preference.
184
185 =cut
186
187 sub hidden_in_opac {
188     my ( $self, $params ) = @_;
189
190     my $rules = $params->{rules} // {};
191
192     my @items = $self->items->as_list;
193
194     return 0 unless @items; # Do not hide if there is no item
195
196     return !(any { !$_->hidden_in_opac({ rules => $rules }) } @items);
197 }
198
199 =head3 article_request_type
200
201 my $type = $biblio->article_request_type( $borrower );
202
203 Returns the article request type based on items, or on the record
204 itself if there are no items.
205
206 $borrower must be a Koha::Patron object
207
208 =cut
209
210 sub article_request_type {
211     my ( $self, $borrower ) = @_;
212
213     return q{} unless $borrower;
214
215     my $rule = $self->article_request_type_for_items( $borrower );
216     return $rule if $rule;
217
218     # If the record has no items that are requestable, go by the record itemtype
219     $rule = $self->article_request_type_for_bib($borrower);
220     return $rule if $rule;
221
222     return q{};
223 }
224
225 =head3 article_request_type_for_bib
226
227 my $type = $biblio->article_request_type_for_bib
228
229 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record
230
231 =cut
232
233 sub article_request_type_for_bib {
234     my ( $self, $borrower ) = @_;
235
236     return q{} unless $borrower;
237
238     my $borrowertype = $borrower->categorycode;
239     my $itemtype     = $self->itemtype();
240
241     my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowertype, itemtype => $itemtype });
242
243     return q{} unless $issuing_rule;
244     return $issuing_rule->article_requests || q{}
245 }
246
247 =head3 article_request_type_for_items
248
249 my $type = $biblio->article_request_type_for_items
250
251 Returns the article request type 'yes', 'no', 'item_only', 'bib_only', for the given record's items
252
253 If there is a conflict where some items are 'bib_only' and some are 'item_only', 'bib_only' will be returned.
254
255 =cut
256
257 sub article_request_type_for_items {
258     my ( $self, $borrower ) = @_;
259
260     my $counts;
261     foreach my $item ( $self->items()->as_list() ) {
262         my $rule = $item->article_request_type($borrower);
263         return $rule if $rule eq 'bib_only';    # we don't need to go any further
264         $counts->{$rule}++;
265     }
266
267     return 'item_only' if $counts->{item_only};
268     return 'yes'       if $counts->{yes};
269     return 'no'        if $counts->{no};
270     return q{};
271 }
272
273 =head3 article_requests
274
275 my @requests = $biblio->article_requests
276
277 Returns the article requests associated with this Biblio
278
279 =cut
280
281 sub article_requests {
282     my ( $self, $borrower ) = @_;
283
284     $self->{_article_requests} ||= Koha::ArticleRequests->search( { biblionumber => $self->biblionumber() } );
285
286     return wantarray ? $self->{_article_requests}->as_list : $self->{_article_requests};
287 }
288
289 =head3 article_requests_current
290
291 my @requests = $biblio->article_requests_current
292
293 Returns the article requests associated with this Biblio that are incomplete
294
295 =cut
296
297 sub article_requests_current {
298     my ( $self, $borrower ) = @_;
299
300     $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
301         {
302             biblionumber => $self->biblionumber(),
303             -or          => [
304                 { status => Koha::ArticleRequest::Status::Pending },
305                 { status => Koha::ArticleRequest::Status::Processing }
306             ]
307         }
308     );
309
310     return wantarray ? $self->{_article_requests_current}->as_list : $self->{_article_requests_current};
311 }
312
313 =head3 article_requests_finished
314
315 my @requests = $biblio->article_requests_finished
316
317 Returns the article requests associated with this Biblio that are completed
318
319 =cut
320
321 sub article_requests_finished {
322     my ( $self, $borrower ) = @_;
323
324     $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
325         {
326             biblionumber => $self->biblionumber(),
327             -or          => [
328                 { status => Koha::ArticleRequest::Status::Completed },
329                 { status => Koha::ArticleRequest::Status::Canceled }
330             ]
331         }
332     );
333
334     return wantarray ? $self->{_article_requests_finished}->as_list : $self->{_article_requests_finished};
335 }
336
337 =head3 items
338
339 my $items = $biblio->items();
340
341 Returns the related Koha::Items object for this biblio
342
343 =cut
344
345 sub items {
346     my ($self) = @_;
347
348     my $items_rs = $self->_result->items;
349
350     return Koha::Items->_new_from_dbic( $items_rs );
351 }
352
353 =head3 itemtype
354
355 my $itemtype = $biblio->itemtype();
356
357 Returns the itemtype for this record.
358
359 =cut
360
361 sub itemtype {
362     my ( $self ) = @_;
363
364     return $self->biblioitem()->itemtype();
365 }
366
367 =head3 holds
368
369 my $holds = $biblio->holds();
370
371 return the current holds placed on this record
372
373 =cut
374
375 sub holds {
376     my ( $self, $params, $attributes ) = @_;
377     $attributes->{order_by} = 'priority' unless exists $attributes->{order_by};
378     my $hold_rs = $self->_result->reserves->search( $params, $attributes );
379     return Koha::Holds->_new_from_dbic($hold_rs);
380 }
381
382 =head3 current_holds
383
384 my $holds = $biblio->current_holds
385
386 Return the holds placed on this bibliographic record.
387 It does not include future holds.
388
389 =cut
390
391 sub current_holds {
392     my ($self) = @_;
393     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
394     return $self->holds(
395         { reservedate => { '<=' => $dtf->format_date(dt_from_string) } } );
396 }
397
398 =head3 biblioitem
399
400 my $field = $self->biblioitem()->itemtype
401
402 Returns the related Koha::Biblioitem object for this Biblio object
403
404 =cut
405
406 sub biblioitem {
407     my ($self) = @_;
408
409     $self->{_biblioitem} ||= Koha::Biblioitems->find( { biblionumber => $self->biblionumber() } );
410
411     return $self->{_biblioitem};
412 }
413
414 =head3 subscriptions
415
416 my $subscriptions = $self->subscriptions
417
418 Returns the related Koha::Subscriptions object for this Biblio object
419
420 =cut
421
422 sub subscriptions {
423     my ($self) = @_;
424
425     $self->{_subscriptions} ||= Koha::Subscriptions->search( { biblionumber => $self->biblionumber } );
426
427     return $self->{_subscriptions};
428 }
429
430 =head3 has_items_waiting_or_intransit
431
432 my $itemsWaitingOrInTransit = $biblio->has_items_waiting_or_intransit
433
434 Tells if this bibliographic record has items waiting or in transit.
435
436 =cut
437
438 sub has_items_waiting_or_intransit {
439     my ( $self ) = @_;
440
441     if ( Koha::Holds->search({ biblionumber => $self->id,
442                                found => ['W', 'T'] })->count ) {
443         return 1;
444     }
445
446     foreach my $item ( $self->items->as_list ) {
447         return 1 if $item->get_transfer;
448     }
449
450     return 0;
451 }
452
453 =head2 get_coins
454
455 my $coins = $biblio->get_coins;
456
457 Returns the COinS (a span) which can be included in a biblio record
458
459 =cut
460
461 sub get_coins {
462     my ( $self ) = @_;
463
464     my $record = $self->metadata->record;
465
466     my $pos7 = substr $record->leader(), 7, 1;
467     my $pos6 = substr $record->leader(), 6, 1;
468     my $mtx;
469     my $genre;
470     my ( $aulast, $aufirst ) = ( '', '' );
471     my @authors;
472     my $title;
473     my $hosttitle;
474     my $pubyear   = '';
475     my $isbn      = '';
476     my $issn      = '';
477     my $publisher = '';
478     my $pages     = '';
479     my $titletype = '';
480
481     # For the purposes of generating COinS metadata, LDR/06-07 can be
482     # considered the same for UNIMARC and MARC21
483     my $fmts6 = {
484         'a' => 'book',
485         'b' => 'manuscript',
486         'c' => 'book',
487         'd' => 'manuscript',
488         'e' => 'map',
489         'f' => 'map',
490         'g' => 'film',
491         'i' => 'audioRecording',
492         'j' => 'audioRecording',
493         'k' => 'artwork',
494         'l' => 'document',
495         'm' => 'computerProgram',
496         'o' => 'document',
497         'r' => 'document',
498     };
499     my $fmts7 = {
500         'a' => 'journalArticle',
501         's' => 'journal',
502     };
503
504     $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
505
506     if ( $genre eq 'book' ) {
507             $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
508     }
509
510     ##### We must transform mtx to a valable mtx and document type ####
511     if ( $genre eq 'book' ) {
512             $mtx = 'book';
513             $titletype = 'b';
514     } elsif ( $genre eq 'journal' ) {
515             $mtx = 'journal';
516             $titletype = 'j';
517     } elsif ( $genre eq 'journalArticle' ) {
518             $mtx   = 'journal';
519             $genre = 'article';
520             $titletype = 'a';
521     } else {
522             $mtx = 'dc';
523     }
524
525     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
526
527         # Setting datas
528         $aulast  = $record->subfield( '700', 'a' ) || '';
529         $aufirst = $record->subfield( '700', 'b' ) || '';
530         push @authors, "$aufirst $aulast" if ($aufirst or $aulast);
531
532         # others authors
533         if ( $record->field('200') ) {
534             for my $au ( $record->field('200')->subfield('g') ) {
535                 push @authors, $au;
536             }
537         }
538
539         $title     = $record->subfield( '200', 'a' );
540         my $subfield_210d = $record->subfield('210', 'd');
541         if ($subfield_210d and $subfield_210d =~ /(\d{4})/) {
542             $pubyear = $1;
543         }
544         $publisher = $record->subfield( '210', 'c' ) || '';
545         $isbn      = $record->subfield( '010', 'a' ) || '';
546         $issn      = $record->subfield( '011', 'a' ) || '';
547     } else {
548
549         # MARC21 need some improve
550
551         # Setting datas
552         if ( $record->field('100') ) {
553             push @authors, $record->subfield( '100', 'a' );
554         }
555
556         # others authors
557         if ( $record->field('700') ) {
558             for my $au ( $record->field('700')->subfield('a') ) {
559                 push @authors, $au;
560             }
561         }
562         $title = $record->subfield( '245', 'a' ) . $record->subfield( '245', 'b' );
563         if ($titletype eq 'a') {
564             $pubyear   = $record->field('008') || '';
565             $pubyear   = substr($pubyear->data(), 7, 4) if $pubyear;
566             $isbn      = $record->subfield( '773', 'z' ) || '';
567             $issn      = $record->subfield( '773', 'x' ) || '';
568             $hosttitle = $record->subfield( '773', 't' ) || $record->subfield( '773', 'a') || q{};
569             my @rels = $record->subfield( '773', 'g' );
570             $pages = join(', ', @rels);
571         } else {
572             $pubyear   = $record->subfield( '260', 'c' ) || '';
573             $publisher = $record->subfield( '260', 'b' ) || '';
574             $isbn      = $record->subfield( '020', 'a' ) || '';
575             $issn      = $record->subfield( '022', 'a' ) || '';
576         }
577
578     }
579
580     my @params = (
581         [ 'ctx_ver', 'Z39.88-2004' ],
582         [ 'rft_val_fmt', "info:ofi/fmt:kev:mtx:$mtx" ],
583         [ ($mtx eq 'dc' ? 'rft.type' : 'rft.genre'), $genre ],
584         [ "rft.${titletype}title", $title ],
585     );
586
587     # rft.title is authorized only once, so by checking $titletype
588     # we ensure that rft.title is not already in the list.
589     if ($hosttitle and $titletype) {
590         push @params, [ 'rft.title', $hosttitle ];
591     }
592
593     push @params, (
594         [ 'rft.isbn', $isbn ],
595         [ 'rft.issn', $issn ],
596     );
597
598     # If it's a subscription, these informations have no meaning.
599     if ($genre ne 'journal') {
600         push @params, (
601             [ 'rft.aulast', $aulast ],
602             [ 'rft.aufirst', $aufirst ],
603             (map { [ 'rft.au', $_ ] } @authors),
604             [ 'rft.pub', $publisher ],
605             [ 'rft.date', $pubyear ],
606             [ 'rft.pages', $pages ],
607         );
608     }
609
610     my $coins_value = join( '&amp;',
611         map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params );
612
613     return $coins_value;
614 }
615
616 =head2 get_openurl
617
618 my $url = $biblio->get_openurl;
619
620 Returns url for OpenURL resolver set in OpenURLResolverURL system preference
621
622 =cut
623
624 sub get_openurl {
625     my ( $self ) = @_;
626
627     my $OpenURLResolverURL = C4::Context->preference('OpenURLResolverURL');
628
629     if ($OpenURLResolverURL) {
630         my $uri = URI->new($OpenURLResolverURL);
631
632         if (not defined $uri->query) {
633             $OpenURLResolverURL .= '?';
634         } else {
635             $OpenURLResolverURL .= '&amp;';
636         }
637         $OpenURLResolverURL .= $self->get_coins;
638     }
639
640     return $OpenURLResolverURL;
641 }
642
643 =head3 type
644
645 =cut
646
647 sub _type {
648     return 'Biblio';
649 }
650
651 =head1 AUTHOR
652
653 Kyle M Hall <kyle@bywatersolutions.com>
654
655 =cut
656
657 1;