Bug 19821: Use database_test entry if exists
[koha-ffzg.git] / Koha / Biblio.pm
index a373308..e3618dc 100644 (file)
@@ -4,42 +4,42 @@ package Koha::Biblio;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 3 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use Modern::Perl;
 
-use Carp;
-use List::MoreUtils qw(any);
+use List::MoreUtils qw( any );
 use URI;
-use URI::Escape;
+use URI::Escape qw( uri_escape_utf8 );
 
-use C4::Koha;
-use C4::Biblio qw();
+use C4::Koha qw( GetNormalizedISBN );
+use C4::XSLT qw( transformMARCXML4XSLT );
 
 use Koha::Database;
 use Koha::DateUtils qw( dt_from_string );
 
 use base qw(Koha::Object);
 
-use Koha::ArticleRequest::Status;
+use Koha::Acquisition::Orders;
 use Koha::ArticleRequests;
 use Koha::Biblio::Metadatas;
 use Koha::Biblioitems;
-use Koha::IssuingRules;
+use Koha::CirculationRules;
 use Koha::Item::Transfer::Limits;
 use Koha::Items;
 use Koha::Libraries;
+use Koha::Suggestions;
 use Koha::Subscriptions;
 
 =head1 NAME
@@ -81,6 +81,37 @@ sub metadata {
     return Koha::Biblio::Metadata->_new_from_dbic($metadata);
 }
 
+=head3 orders
+
+my $orders = $biblio->orders();
+
+Returns a Koha::Acquisition::Orders object
+
+=cut
+
+sub orders {
+    my ( $self ) = @_;
+
+    my $orders = $self->_result->orders;
+    return Koha::Acquisition::Orders->_new_from_dbic($orders);
+}
+
+=head3 active_orders
+
+my $active_orders = $biblio->active_orders();
+
+Returns the active acquisition orders related to this biblio.
+An order is considered active when it is not cancelled (i.e. when datecancellation
+is not undef).
+
+=cut
+
+sub active_orders {
+    my ( $self ) = @_;
+
+    return $self->orders->search({ datecancellationprinted => undef });
+}
+
 =head3 can_article_request
 
 my $bool = $biblio->can_article_request( $borrower );
@@ -172,36 +203,37 @@ sub can_be_transferred {
 
 =head3 pickup_locations
 
-@pickup_locations = $biblio->pickup_locations( {patron => $patron } )
+    my $pickup_locations = $biblio->pickup_locations( {patron => $patron } );
 
-Returns possible pickup locations for this biblio items, according to patron's home library (if patron is defined and holds are allowed only from hold groups)
-and if item can be transferred to each pickup location.
+Returns a Koha::Libraries set of possible pickup locations for this biblio's items,
+according to patron's home library (if patron is defined and holds are allowed
+only from hold groups) and if item can be transferred to each pickup location.
 
 =cut
 
 sub pickup_locations {
-    my ($self, $params) = @_;
+    my ( $self, $params ) = @_;
 
     my $patron = $params->{patron};
 
     my @pickup_locations;
-    foreach my $item_of_bib ($self->items->as_list) {
-        push @pickup_locations, $item_of_bib->pickup_locations( {patron => $patron} );
+    foreach my $item_of_bib ( $self->items->as_list ) {
+        push @pickup_locations,
+          $item_of_bib->pickup_locations( { patron => $patron } )
+          ->_resultset->get_column('branchcode')->all;
     }
 
-    my %seen;
-    @pickup_locations =
-      grep { !$seen{ $_->branchcode }++ } @pickup_locations;
-
-    return wantarray ? @pickup_locations : \@pickup_locations;
+    return Koha::Libraries->search(
+        { branchcode => { '-in' => \@pickup_locations } }, { order_by => ['branchname'] } );
 }
 
 =head3 hidden_in_opac
 
-my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
+    my $bool = $biblio->hidden_in_opac({ [ rules => $rules ] })
 
 Returns true if the biblio matches the hidding criteria defined in $rules.
-Returns false otherwise.
+Returns false otherwise. It involves the I<OpacHiddenItems> and
+I<OpacHiddenItemsHidesRecord> system preferences.
 
 Takes HASHref that can have the following parameters:
     OPTIONAL PARAMETERS:
@@ -221,6 +253,9 @@ sub hidden_in_opac {
 
     return 0 unless @items; # Do not hide if there is no item
 
+    # Ok, there are items, don't even try the rules unless OpacHiddenItemsHidesRecord
+    return 0 unless C4::Context->preference('OpacHiddenItemsHidesRecord');
+
     return !(any { !$_->hidden_in_opac({ rules => $rules }) } @items);
 }
 
@@ -266,10 +301,16 @@ sub article_request_type_for_bib {
     my $borrowertype = $borrower->categorycode;
     my $itemtype     = $self->itemtype();
 
-    my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowertype, itemtype => $itemtype });
+    my $rule = Koha::CirculationRules->get_effective_rule(
+        {
+            rule_name    => 'article_requests',
+            categorycode => $borrowertype,
+            itemtype     => $itemtype,
+        }
+    );
 
-    return q{} unless $issuing_rule;
-    return $issuing_rule->article_requests || q{}
+    return q{} unless $rule;
+    return $rule->rule_value || q{}
 }
 
 =head3 article_request_type_for_items
@@ -300,82 +341,63 @@ sub article_request_type_for_items {
 
 =head3 article_requests
 
-my @requests = $biblio->article_requests
+    my $article_requests = $biblio->article_requests
 
-Returns the article requests associated with this Biblio
+Returns the article requests associated with this biblio
 
 =cut
 
 sub article_requests {
-    my ( $self, $borrower ) = @_;
-
-    $self->{_article_requests} ||= Koha::ArticleRequests->search( { biblionumber => $self->biblionumber() } );
-
-    return wantarray ? $self->{_article_requests}->as_list : $self->{_article_requests};
-}
-
-=head3 article_requests_current
-
-my @requests = $biblio->article_requests_current
-
-Returns the article requests associated with this Biblio that are incomplete
-
-=cut
-
-sub article_requests_current {
-    my ( $self, $borrower ) = @_;
-
-    $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
-        {
-            biblionumber => $self->biblionumber(),
-            -or          => [
-                { status => Koha::ArticleRequest::Status::Pending },
-                { status => Koha::ArticleRequest::Status::Processing }
-            ]
-        }
-    );
+    my ( $self ) = @_;
 
-    return wantarray ? $self->{_article_requests_current}->as_list : $self->{_article_requests_current};
+    return Koha::ArticleRequests->_new_from_dbic( scalar $self->_result->article_requests );
 }
 
-=head3 article_requests_finished
+=head3 items
 
-my @requests = $biblio->article_requests_finished
+my $items = $biblio->items();
 
-Returns the article requests associated with this Biblio that are completed
+Returns the related Koha::Items object for this biblio
 
 =cut
 
-sub article_requests_finished {
-    my ( $self, $borrower ) = @_;
+sub items {
+    my ($self) = @_;
 
-    $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
-        {
-            biblionumber => $self->biblionumber(),
-            -or          => [
-                { status => Koha::ArticleRequest::Status::Completed },
-                { status => Koha::ArticleRequest::Status::Canceled }
-            ]
-        }
-    );
+    my $items_rs = $self->_result->items;
 
-    return wantarray ? $self->{_article_requests_finished}->as_list : $self->{_article_requests_finished};
+    return Koha::Items->_new_from_dbic( $items_rs );
 }
 
-=head3 items
+=head3 host_items
 
-my $items = $biblio->items();
+my $host_items = $biblio->host_items();
 
-Returns the related Koha::Items object for this biblio
+Return the host items (easy analytical record)
 
 =cut
 
-sub items {
+sub host_items {
     my ($self) = @_;
 
-    my $items_rs = $self->_result->items;
+    return Koha::Items->new->empty
+      unless C4::Context->preference('EasyAnalyticalRecords');
 
-    return Koha::Items->_new_from_dbic( $items_rs );
+    my $marcflavour = C4::Context->preference("marcflavour");
+    my $analyticfield = '773';
+    if ( $marcflavour eq 'MARC21' ) {
+        $analyticfield = '773';
+    }
+    elsif ( $marcflavour eq 'UNIMARC' ) {
+        $analyticfield = '461';
+    }
+    my $marc_record = $self->metadata->record;
+    my @itemnumbers;
+    foreach my $field ( $marc_record->field($analyticfield) ) {
+        push @itemnumbers, $field->subfield('9');
+    }
+
+    return Koha::Items->search( { itemnumber => { -in => \@itemnumbers } } );
 }
 
 =head3 itemtype
@@ -439,6 +461,21 @@ sub biblioitem {
     return $self->{_biblioitem};
 }
 
+=head3 suggestions
+
+my $suggestions = $self->suggestions
+
+Returns the related Koha::Suggestions object for this Biblio object
+
+=cut
+
+sub suggestions {
+    my ($self) = @_;
+
+    my $suggestions_rs = $self->_result->suggestions;
+    return Koha::Suggestions->_new_from_dbic( $suggestions_rs );
+}
+
 =head3 subscriptions
 
 my $subscriptions = $self->subscriptions
@@ -587,7 +624,8 @@ sub get_coins {
                 push @authors, $au;
             }
         }
-        $title = $record->field('245')->as_string('ab');
+        $title = $record->field('245');
+        $title &&= $title->as_string('ab');
         if ($titletype eq 'a') {
             $pubyear   = $record->field('008') || '';
             $pubyear   = substr($pubyear->data(), 7, 4) if $pubyear;
@@ -701,29 +739,109 @@ sub custom_cover_image_url {
     my $url = C4::Context->preference('CustomCoverImagesURL');
     if ( $url =~ m|{isbn}| ) {
         my $isbn = $self->biblioitem->isbn;
+        return unless $isbn;
         $url =~ s|{isbn}|$isbn|g;
     }
     if ( $url =~ m|{normalized_isbn}| ) {
         my $normalized_isbn = C4::Koha::GetNormalizedISBN($self->biblioitem->isbn);
+        return unless $normalized_isbn;
         $url =~ s|{normalized_isbn}|$normalized_isbn|g;
     }
     if ( $url =~ m|{issn}| ) {
         my $issn = $self->biblioitem->issn;
+        return unless $issn;
         $url =~ s|{issn}|$issn|g;
     }
 
-    my $re = qr|{(?<field>\d{3})\$(?<subfield>.)}|;
+    my $re = qr|{(?<field>\d{3})(\$(?<subfield>.))?}|;
     if ( $url =~ $re ) {
         my $field = $+{field};
         my $subfield = $+{subfield};
         my $marc_record = $self->metadata->record;
-        my $value = $marc_record->subfield($field, $subfield);
+        my $value;
+        if ( $subfield ) {
+            $value = $marc_record->subfield( $field, $subfield );
+        } else {
+            my $controlfield = $marc_record->field($field);
+            $value = $controlfield->data() if $controlfield;
+        }
+        return unless $value;
         $url =~ s|$re|$value|;
     }
 
     return $url;
 }
 
+=head3 cover_images
+
+Return the cover images associated with this biblio.
+
+=cut
+
+sub cover_images {
+    my ( $self ) = @_;
+
+    my $cover_images_rs = $self->_result->cover_images;
+    return unless $cover_images_rs;
+    return Koha::CoverImages->_new_from_dbic($cover_images_rs);
+}
+
+=head3 get_marc_notes
+
+    $marcnotesarray = $biblio->get_marc_notes({ marcflavour => $marcflavour });
+
+Get all notes from the MARC record and returns them in an array.
+The notes are stored in different fields depending on MARC flavour.
+MARC21 5XX $u subfields receive special attention as they are URIs.
+
+=cut
+
+sub get_marc_notes {
+    my ( $self, $params ) = @_;
+
+    my $marcflavour = $params->{marcflavour};
+    my $opac = $params->{opac};
+
+    my $scope = $marcflavour eq "UNIMARC"? '3..': '5..';
+    my @marcnotes;
+
+    #MARC21 specs indicate some notes should be private if first indicator 0
+    my %maybe_private = (
+        541 => 1,
+        542 => 1,
+        561 => 1,
+        583 => 1,
+        590 => 1
+    );
+
+    my %hiddenlist = map { $_ => 1 }
+        split( /,/, C4::Context->preference('NotesToHide'));
+    my $record = $self->metadata->record;
+    $record = transformMARCXML4XSLT( $self->biblionumber, $record, $opac );
+
+    foreach my $field ( $record->field($scope) ) {
+        my $tag = $field->tag();
+        next if $hiddenlist{ $tag };
+        next if $opac && $maybe_private{$tag} && !$field->indicator(1);
+        if( $marcflavour ne 'UNIMARC' && $field->subfield('u') ) {
+            # Field 5XX$u always contains URI
+            # Examples: 505u, 506u, 510u, 514u, 520u, 530u, 538u, 540u, 542u, 552u, 555u, 561u, 563u, 583u
+            # We first push the other subfields, then all $u's separately
+            # Leave further actions to the template (see e.g. opac-detail)
+            my $othersub =
+                join '', ( 'a' .. 't', 'v' .. 'z', '0' .. '9' ); # excl 'u'
+            push @marcnotes, { marcnote => $field->as_string($othersub) };
+            foreach my $sub ( $field->subfield('u') ) {
+                $sub =~ s/^\s+|\s+$//g; # trim
+                push @marcnotes, { marcnote => $sub };
+            }
+        } else {
+            push @marcnotes, { marcnote => $field->as_string() };
+        }
+    }
+    return \@marcnotes;
+}
+
 =head3 to_api
 
     my $json = $biblio->to_api;
@@ -737,16 +855,8 @@ on the API.
 sub to_api {
     my ($self, $args) = @_;
 
-    my @embeds = keys %{ $args->{embed} };
-    my $remaining_embeds = {};
-
-    foreach my $embed (@embeds) {
-        $remaining_embeds = delete $args->{embed}->{$embed}
-            unless $self->can($embed);
-    }
-
     my $response = $self->SUPER::to_api( $args );
-    my $biblioitem = $self->biblioitem->to_api({ embed => $remaining_embeds });
+    my $biblioitem = $self->biblioitem->to_api;
 
     return { %$response, %$biblioitem };
 }
@@ -769,6 +879,69 @@ sub to_api_mapping {
     };
 }
 
+=head3 get_marc_host
+
+    $host = $biblio->get_marc_host;
+    # OR:
+    ( $host, $relatedparts ) = $biblio->get_marc_host;
+
+    Returns host biblio record from MARC21 773 (undef if no 773 present).
+    It looks at the first 773 field with MARCorgCode or only a control
+    number. Complete $w or numeric part is used to search host record.
+    The optional parameter no_items triggers a check if $biblio has items.
+    If there are, the sub returns undef.
+    Called in list context, it also returns 773$g (related parts).
+
+=cut
+
+sub get_marc_host {
+    my ($self, $params) = @_;
+    my $no_items = $params->{no_items};
+    return if C4::Context->preference('marcflavour') eq 'UNIMARC'; # TODO
+    return if $params->{no_items} && $self->items->count > 0;
+
+    my $record;
+    eval { $record = $self->metadata->record };
+    return if !$record;
+
+    # We pick the first $w with your MARCOrgCode or the first $w that has no
+    # code (between parentheses) at all.
+    my $orgcode = C4::Context->preference('MARCOrgCode') // q{};
+    my $hostfld;
+    foreach my $f ( $record->field('773') ) {
+        my $w = $f->subfield('w') or next;
+        if( $w =~ /^\($orgcode\)\s*(\d+)/i or $w =~ /^\d+/ ) {
+            $hostfld = $f;
+            last;
+        }
+    }
+    return if !$hostfld;
+    my $rcn = $hostfld->subfield('w');
+
+    # Look for control number with/without orgcode
+    my $engine = Koha::SearchEngine::Search->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
+    my $bibno;
+    for my $try (1..2) {
+        my ( $error, $results, $total_hits ) = $engine->simple_search_compat( 'Control-number='.$rcn, 0,1 );
+        if( !$error and $total_hits == 1 ) {
+            $bibno = $engine->extract_biblionumber( $results->[0] );
+            last;
+        }
+        # Add or remove orgcode for second try
+        if( $try == 1 && $rcn =~ /\)\s*(\d+)/ ) {
+            $rcn = $1; # number only
+        } elsif( $try == 1 && $rcn =~ /^\d+/ ) {
+            $rcn = "($orgcode)$rcn";
+        } else {
+            last;
+        }
+    }
+    if( $bibno ) {
+        my $host = Koha::Biblios->find($bibno) or return;
+        return wantarray ? ( $host, $hostfld->subfield('g') ) : $host;
+    }
+}
+
 =head2 Internal methods
 
 =head3 type