1 package C4::AuthoritiesMarc;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
30 use Koha::MetadataRecord::Authority;
31 use Koha::Authorities;
32 use Koha::Authority::MergeRequests;
33 use Koha::Authority::Types;
36 use Koha::SearchEngine;
37 use Koha::SearchEngine::Search;
39 use vars qw(@ISA @EXPORT);
47 &GetAuthMARCFromKohaField
63 &FindDuplicateAuthority
75 =head2 GetAuthMARCFromKohaField
77 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
79 returns tag and subfield linked to kohafield
82 Suppose Kohafield is only linked to ONE subfield
86 sub GetAuthMARCFromKohaField {
87 #AUTHfind_marc_from_kohafield
88 my ( $kohafield,$authtypecode ) = @_;
89 my $dbh=C4::Context->dbh;
90 return 0, 0 unless $kohafield;
91 $authtypecode="" unless $authtypecode;
92 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
93 $sth->execute($kohafield,$authtypecode);
94 my ($tagfield,$tagsubfield) = $sth->fetchrow;
96 return ($tagfield,$tagsubfield);
99 =head2 SearchAuthorities
101 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
102 $excluding, $operator, $value, $offset,$length,$authtypecode,
103 $sortby[, $skipmetadata])
105 returns ref to array result and count of results returned
109 sub SearchAuthorities {
110 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
111 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
112 my $dbh=C4::Context->dbh;
113 $sortby="" unless $sortby;
117 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
119 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
120 # the authtypecode. Then, search on $a of this tag_to_report
121 # also store main entry MARC tag, to extract it at end of search
123 ##first set the authtype search and may be multiple authorities
127 my @auths=split / /,$authtypecode ;
128 foreach my $auth (@auths){
129 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
130 push @authtypecode ,$auth;
134 while ($n>1){$query= "\@or ".$query;$n--;}
137 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
145 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
148 if ( @$tags[$i] eq "mainmainentry" ) {
149 $attr = " \@attr 1=Heading-Main ";
151 elsif ( @$tags[$i] eq "mainentry" ) {
152 $attr = " \@attr 1=Heading ";
154 elsif ( @$tags[$i] eq "match" ) {
155 $attr = " \@attr 1=Match ";
157 elsif ( @$tags[$i] eq "match-heading" ) {
158 $attr = " \@attr 1=Match-heading ";
160 elsif ( @$tags[$i] eq "see-from" ) {
161 $attr = " \@attr 1=Match-heading-see-from ";
163 elsif ( @$tags[$i] eq "thesaurus" ) {
164 $attr = " \@attr 1=Subject-heading-thesaurus ";
166 elsif ( @$tags[$i] eq "all" ) {
167 $attr = " \@attr 1=Any ";
169 else { # Use the index passed in params
170 $attr = " \@attr 1=" . @$tags[$i] . " ";
173 else { # Assume any if no index was specified
174 $attr = " \@attr 1=Any ";
177 my $operator = @$operator[$i];
178 if ( $operator and $operator eq 'is' ) {
179 $attr .= " \@attr 4=1 \@attr 5=100 "
180 ; ##Phrase, No truncation,all of subfield field must match
182 elsif ( $operator and $operator eq "=" ) {
183 $attr .= " \@attr 4=107 "; #Number Exact match
185 elsif ( $operator and $operator eq "start" ) {
186 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
187 ; #Firstinfield Phrase, Right truncated
189 elsif ( $operator and $operator eq "exact" ) {
190 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
191 ; ##Phrase, No truncation,all of subfield field must match
194 $attr .= " \@attr 5=1 \@attr 4=6 "
195 ; ## Word list, right truncated, anywhere
196 if ( $sortby eq 'Relevance' ) {
197 $attr .= "\@attr 2=102 ";
201 s/"/\\"/g; # Escape the double-quotes in the search value
202 $attr = $attr . "\"" . @$value[$i] . "\"";
207 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
211 ##Add how many queries generated
212 if (defined $query && $query=~/\S+/){
213 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
218 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
220 if ($sortby eq 'HeadingAsc') {
221 $orderstring = '@attr 7=1 @attr 1=Heading 0';
222 } elsif ($sortby eq 'HeadingDsc') {
223 $orderstring = '@attr 7=2 @attr 1=Heading 0';
224 } elsif ($sortby eq 'AuthidAsc') {
225 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
226 } elsif ($sortby eq 'AuthidDsc') {
227 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
230 $qpquery .= ' all:all' unless $value->[0];
232 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
236 $qpquery .= " #$sortby" unless $sortby eq '';
238 $QParser->parse( $qpquery );
239 $query = $QParser->target_syntax('authorityserver');
241 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
242 $query="\@or $orderstring $query" if $orderstring;
245 $offset = 0 if not defined $offset or $offset < 0;
246 my $counter = $offset;
247 $length=10 unless $length;
250 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
251 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
253 $oAResult= $oAuth[0]->search($Anewq) ;
254 while (($i = ZOOM::event(\@oAuth)) != 0) {
255 my $ev = $oAuth[$i-1]->last_event();
256 last if $ev == ZOOM::Event::ZEND;
258 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
260 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
265 $nbresults=$oAResult->size();
266 my $nremains=$nbresults;
268 my @finalresult = ();
272 ##Find authid and linkid fields
273 ##we may be searching multiple authoritytypes.
274 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
275 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
276 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
277 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
279 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
280 my $rec=$oAResult->record($counter);
281 my $separator=C4::Context->preference('AuthoritySeparator');
282 my $authrecord = C4::Search::new_record_from_zebra(
287 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
292 SetUTF8Flag( $authrecord );
294 my $authid=$authrecord->field('001')->data();
296 $newline{authid} = $authid;
297 if ( !$skipmetadata ) {
298 my $auth_tag_to_report;
299 $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report
302 my $mainentry = $authrecord->field($auth_tag_to_report);
304 foreach ( $mainentry->subfields() ) {
305 $reported_tag .= '$' . $_->[0] . $_->[1];
309 my ( $thisauthtype, $thisauthtypecode );
310 if ( my $authority = Koha::Authorities->find($authid) ) {
311 $thisauthtypecode = $authority->authtypecode;
312 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
314 unless (defined $thisauthtype) {
315 $thisauthtypecode = $authtypecode;
316 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
318 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
320 $newline{authtype} = defined($thisauthtype) ?
321 $thisauthtype->authtypetext : '';
322 $newline{summary} = $summary;
323 $newline{even} = $counter % 2;
324 $newline{reported_tag} = $reported_tag;
327 push @finalresult, \%newline;
330 if (! $skipmetadata) {
331 for (my $z=0; $z<@finalresult; $z++){
332 my $count = Koha::Authorities->get_usage_count({ authid => $finalresult[$z]{authid} });
333 $finalresult[$z]{used}=$count;
339 $oAResult->destroy();
340 # $oAuth[0]->destroy();
342 return (\@finalresult, $nbresults);
345 =head2 GuessAuthTypeCode
347 my $authtypecode = GuessAuthTypeCode($record);
349 Get the record and tries to guess the adequate authtypecode from its content.
353 sub GuessAuthTypeCode {
354 my ($record, $heading_fields) = @_;
355 return unless defined $record;
356 $heading_fields //= {
358 '100'=>{authtypecode=>'PERSO_NAME'},
359 '110'=>{authtypecode=>'CORPO_NAME'},
360 '111'=>{authtypecode=>'MEETI_NAME'},
361 '130'=>{authtypecode=>'UNIF_TITLE'},
362 '148'=>{authtypecode=>'CHRON_TERM'},
363 '150'=>{authtypecode=>'TOPIC_TERM'},
364 '151'=>{authtypecode=>'GEOGR_NAME'},
365 '155'=>{authtypecode=>'GENRE/FORM'},
366 '180'=>{authtypecode=>'GEN_SUBDIV'},
367 '181'=>{authtypecode=>'GEO_SUBDIV'},
368 '182'=>{authtypecode=>'CHRON_SUBD'},
369 '185'=>{authtypecode=>'FORM_SUBD'},
371 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
372 # 604 with embedded 700, 701, 702
373 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
374 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
375 #216 Trademark 716 [Reserved for future use]
376 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
377 #230 Title 500 4-- with embedded 500 605
378 #240 Name and title (embedded 200, 210, 215, or 220 and 230) 4-- with embedded 7-- and 500 7-- 604 with embedded 7-- and 500 500
379 #245 Name and collective title (embedded 200, 210, 215, or 220 and 235) 4-- with embedded 7-- and 501 604 with embedded 7-- and 501 7-- 501
380 #250 Topical subject 606
381 #260 Place access 620
382 #280 Form, genre or physical characteristics 608
385 # Could also be represented with :
387 #a = personal name entry
388 #b = corporate name entry
389 #c = territorial or geographical name
393 #g = collective uniform title
395 #i = name/collective uniform title
398 #l = form, genre or physical characteristics
400 '200'=>{authtypecode=>'NP'},
401 '210'=>{authtypecode=>'CO'},
402 '215'=>{authtypecode=>'SNG'},
403 '216'=>{authtypecode=>'TM'},
404 '220'=>{authtypecode=>'FAM'},
405 '230'=>{authtypecode=>'TU'},
406 '235'=>{authtypecode=>'CO_UNI_TI'},
407 '240'=>{authtypecode=>'SAUTTIT'},
408 '245'=>{authtypecode=>'NAME_COL'},
409 '250'=>{authtypecode=>'SNC'},
410 '260'=>{authtypecode=>'PA'},
411 '280'=>{authtypecode=>'GENRE/FORM'},
414 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
415 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
422 my $authtid = GuessAuthId($record);
424 Get the record and tries to guess the adequate authtypecode from its content.
430 return unless ($record && $record->field('001'));
431 # my $authtypecode=GuessAuthTypeCode($record);
432 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
433 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
434 # else {return $record->field($tag)->data}
435 return $record->field('001')->data;
440 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
442 returns a ref to hashref of authorities tag and subfield structure.
446 $tagslabel->{$tag}->{$subfield}->{'attribute'}
448 where attribute takes values in :
466 my ($forlibrarian,$authtypecode)= @_;
467 my $dbh=C4::Context->dbh;
468 $authtypecode="" unless $authtypecode;
470 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
473 # check that authority exists
474 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
475 $sth->execute($authtypecode);
476 my ($total) = $sth->fetchrow;
477 $authtypecode="" unless ($total >0);
479 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
480 FROM auth_tag_structure
485 $sth->execute($authtypecode);
486 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
488 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
489 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
490 $res->{$tag}->{tab} = " "; # XXX
491 $res->{$tag}->{mandatory} = $mandatory;
492 $res->{$tag}->{repeatable} = $repeatable;
495 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
496 FROM auth_subfield_structure
498 ORDER BY tagfield,tagsubfield"
500 $sth->execute($authtypecode);
503 my $authorised_value;
513 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
514 $mandatory, $repeatable, $authorised_value, $authtypecode,
515 $value_builder, $kohafield, $seealso, $hidden,
516 $isurl, $defaultvalue, $link )
520 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
521 $res->{$tag}->{$subfield}->{tab} = $tab;
522 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
523 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
524 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
525 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
526 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
527 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
528 $res->{$tag}->{$subfield}->{seealso} = $seealso;
529 $res->{$tag}->{$subfield}->{hidden} = $hidden;
530 $res->{$tag}->{$subfield}->{isurl} = $isurl;
531 $res->{$tag}->{$subfield}->{link} = $link;
532 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
539 $authid= &AddAuthority($record, $authid,$authtypecode)
541 Either Create Or Modify existing authority.
542 returns authid of the newly created authority
547 # pass the MARC::Record to this function, and it will create the records in the authority table
548 my ($record,$authid,$authtypecode) = @_;
549 my $dbh=C4::Context->dbh;
550 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
552 # if authid empty => true add, find a new authid number
554 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
555 $format= 'UNIMARCAUTH';
561 #update date/time to 005 for marc and unimarc
562 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
563 my $f5=$record->field('005');
565 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
568 $f5->update($time.".0");
571 SetUTF8Flag($record);
572 if ($format eq "MARC21") {
573 my $userenv = C4::Context->userenv;
575 my $marcorgcode = C4::Context->preference('MARCOrgCode');
576 if ( $userenv && $userenv->{'branch'} ) {
577 $library = Koha::Libraries->find( $userenv->{'branch'} );
578 # userenv's library could not exist because of a trick in misc/commit_file.pl (see FIXME and set_userenv statement)
579 $marcorgcode = $library ? $library->get_effective_marcorgcode : $marcorgcode;
581 if (!$record->leader) {
582 $record->leader($leader);
584 if (!$record->field('003')) {
585 $record->insert_fields_ordered(
586 MARC::Field->new('003', $marcorgcode),
589 my $date=POSIX::strftime("%y%m%d",localtime);
590 if (!$record->field('008')) {
591 # Get a valid default value for field 008
592 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
593 if(!$default_008 or length($default_008)<34) {
594 $default_008 = '|| aca||aabn | a|a d';
597 $default_008 = substr($default_008,0,34);
600 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
602 if (!$record->field('040')) {
603 $record->insert_fields_ordered(
604 MARC::Field->new('040','','',
612 if ($format eq "UNIMARCAUTH") {
613 $record->leader(" nx j22 ") unless ($record->leader());
614 my $date=POSIX::strftime("%Y%m%d",localtime);
615 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
616 if (my $string=$record->subfield('100',"a")){
617 $string=~s/fre50/frey50/;
618 $record->field('100')->update('a'=>$string);
620 elsif ($record->field('100')){
621 $record->field('100')->update('a'=>$date.$defaultfield100);
623 $record->append_fields(
624 MARC::Field->new('100',' ',' '
625 ,'a'=>$date.$defaultfield100)
629 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
630 if (!$authid and $format eq "MARC21") {
631 # only need to do this fix when modifying an existing authority
632 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
634 if (my $field=$record->field($auth_type_tag)){
635 $field->update($auth_type_subfield=>$authtypecode);
638 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
641 # Save record into auth_header, update 001
643 # Save a blank record, get authid
644 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
645 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
646 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
648 # Insert/update the recordID in MARC record
649 $record->delete_field( $record->field('001') );
650 $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
652 $dbh->do( "UPDATE auth_header SET authtypecode=?, marc=?, marcxml=? WHERE authid=?", undef, $authtypecode, $record->as_usmarc, $record->as_xml_record($format), $authid ) or die $DBI::errstr;
653 ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
660 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
662 Deletes $authid and calls merge to cleanup linked biblio records.
663 Parameter skip_merge is used in authorities/merge.pl. You should normally not
670 my $authid = $params->{authid} || return;
671 my $skip_merge = $params->{skip_merge};
672 my $dbh = C4::Context->dbh;
674 # Remove older pending merge requests for $authid to itself. (See bug 22437)
675 my $condition = { authid => $authid, authid_new => [undef, 0, $authid], done => 0 };
676 Koha::Authority::MergeRequests->search($condition)->delete;
678 merge({ mergefrom => $authid }) if !$skip_merge;
679 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
680 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
681 ModZebra( $authid, "recordDelete", "authorityserver", undef);
686 $authid= &ModAuthority($authid,$record,$authtypecode)
688 Modifies authority record, optionally updates attached biblios.
693 my ( $authid, $record, $authtypecode ) = @_;
694 my $oldrecord = GetAuthority($authid);
695 #Now rewrite the $record to table with an add
696 $authid = AddAuthority($record, $authid, $authtypecode);
697 merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
698 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
702 =head2 GetAuthorityXML
704 $marcxml= &GetAuthorityXML( $authid)
706 returns xml form of record $authid
710 sub GetAuthorityXML {
711 # Returns MARC::XML of the authority passed in parameter.
713 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
714 my $dbh=C4::Context->dbh;
715 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
716 $sth->execute($authid);
717 my ($marcxml)=$sth->fetchrow;
721 # for MARC21, call GetAuthority instead of
722 # getting the XML directly since we may
723 # need to fix up the location of the authority
724 # code -- note that this is reasonably safe
725 # because GetAuthorityXML is used only by the
726 # indexing processes like zebraqueue_start.pl
727 my $record = GetAuthority($authid);
728 return $record->as_xml_record('MARC21');
734 $record= &GetAuthority( $authid)
736 Returns MARC::Record of the authority passed in parameter.
742 my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
743 return unless $authority;
744 return ($authority->record);
747 =head2 FindDuplicateAuthority
749 $record= &FindDuplicateAuthority( $record, $authtypecode)
751 return $authid,Summary if duplicate is found.
753 Comments : an improvement would be to return All the records that match.
757 sub FindDuplicateAuthority {
759 my ($record,$authtypecode)=@_;
760 # warn "IN for ".$record->as_formatted;
761 my $dbh = C4::Context->dbh;
762 # warn "".$record->as_formatted;
763 my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
764 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
765 # build a request for SearchAuthorities
767 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
774 my $query='at:'.$authtypecode.' ';
775 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
776 if ($record->field($auth_tag_to_report)) {
777 foreach ($record->field($auth_tag_to_report)->subfields()) {
778 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
781 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
782 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver' ] );
783 # there is at least 1 result => return the 1st one
784 if (!defined $error && @{$results} ) {
785 my $marcrecord = C4::Search::new_record_from_zebra(
789 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
791 # no result, returns nothing
797 $summary= &BuildSummary( $record, $authid, $authtypecode)
799 Returns a hashref with a summary of the specified record.
801 Comment : authtypecode can be inferred from both record and authid.
802 Moreover, authid can also be inferred from $record.
803 Would it be interesting to delete those things.
808 ## give this a Marc record to return summary
809 my ($record,$authid,$authtypecode)=@_;
810 my $dbh=C4::Context->dbh;
812 my $summary_template;
813 # handle $authtypecode is NULL or eq ""
815 my $authref = Koha::Authority::Types->find($authtypecode);
817 $summary{authtypecode} = $authref->authtypecode;
818 $summary{type} = $authref->authtypetext;
819 $summary_template = $authref->summary;
820 # for MARC21, the authority type summary displays a label meant for
822 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
823 $summary{label} = $authref->summary;
825 $summary{summary} = $authref->summary;
829 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
830 my %marc21controlrefs = ( 'a' => 'earlier',
836 'n' => 'notapplicable',
840 my %unimarc_relation_from_code = (
846 $thesaurus{'1'}="Peuples";
847 $thesaurus{'2'}="Anthroponymes";
848 $thesaurus{'3'}="Oeuvres";
849 $thesaurus{'4'}="Chronologie";
850 $thesaurus{'5'}="Lieux";
851 $thesaurus{'6'}="Sujets";
854 # if the library has a summary defined, use it. Otherwise, build a standard one
855 # FIXME - it appears that the summary field in the authority frameworks
856 # can work as a display template. However, this doesn't
857 # suit the MARC21 version, so for now the "templating"
858 # feature will be enabled only for UNIMARC for backwards
860 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
861 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
862 my (@textbefore, @tag, @subtag, @textafter);
863 for(my $i = 0; $i < scalar @matches; $i++){
864 push @textbefore, $matches[$i] if($i%4 == 0);
865 push @tag, $matches[$i] if($i%4 == 1);
866 push @subtag, $matches[$i] if($i%4 == 2);
867 push @textafter, $matches[$i] if($i%4 == 3);
869 for(my $i = scalar @tag; $i >= 0; $i--){
870 my $textbefore = $textbefore[$i] || '';
871 my $tag = $tag[$i] || '';
872 my $subtag = $subtag[$i] || '';
873 my $textafter = $textafter[$i] || '';
875 my $field = $record->field($tag);
879 $value = $textbefore . $field->data() . $textafter;
882 my @subfields = $field->subfield($subtag);
884 $value = $textbefore . join (" - ", @subfields) . $textafter;
888 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
890 $summary{summary} =~ s/\\n/<br \/>/g;
897 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
898 # construct UNIMARC summary, that is quite different from MARC21 one
900 foreach my $field ($record->field('2..')) {
902 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
903 hemain => ( $field->subfield('a') // undef ),
904 field => $field->tag(),
908 foreach my $field ($record->field('3..')) {
909 push @notes, { note => $field->subfield('a'), field => $field->tag() };
911 foreach my $field ($record->field('4..')) {
912 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
914 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
915 hemain => ( $field->subfield('a') // undef ),
917 field => $field->tag(),
923 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
924 my $heading = $_->as_string('abcdefgjxyz');
929 hemain => ( $_->subfield('a') // undef ),
931 authid => ( $_->subfield('9') // undef ),
933 } $record->field('5..');
936 @otherscript = map { {
937 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
938 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
941 } } $record->field('7..');
944 # construct MARC21 summary
945 # FIXME - looping over 1XX is questionable
946 # since MARC21 authority should have only one 1XX
947 my $subfields_to_report;
948 foreach my $field ($record->field('1..')) {
949 my $tag = $field->tag();
950 next if "152" eq $tag;
951 # FIXME - 152 is not a good tag to use
952 # in MARC21 -- purely local tags really ought to be
955 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
956 } elsif ($tag eq '110') {
957 $subfields_to_report = 'abcdefghklmnoprstvxyz';
958 } elsif ($tag eq '111') {
959 $subfields_to_report = 'acdefghklnpqstvxyz';
960 } elsif ($tag eq '130') {
961 $subfields_to_report = 'adfghklmnoprstvxyz';
962 } elsif ($tag eq '148') {
963 $subfields_to_report = 'abvxyz';
964 } elsif ($tag eq '150') {
965 $subfields_to_report = 'abvxyz';
966 } elsif ($tag eq '151') {
967 $subfields_to_report = 'avxyz';
968 } elsif ($tag eq '155') {
969 $subfields_to_report = 'abvxyz';
970 } elsif ($tag eq '180') {
971 $subfields_to_report = 'vxyz';
972 } elsif ($tag eq '181') {
973 $subfields_to_report = 'vxyz';
974 } elsif ($tag eq '182') {
975 $subfields_to_report = 'vxyz';
976 } elsif ($tag eq '185') {
977 $subfields_to_report = 'vxyz';
979 if ($subfields_to_report) {
981 heading => $field->as_string($subfields_to_report),
982 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
987 heading => $field->as_string(),
988 hemain => ( $field->subfield( 'a' ) // undef ),
993 foreach my $field ($record->field('4..')) { #See From
994 my $type = 'seefrom';
995 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
996 if ($type eq 'notapplicable') {
997 $type = substr $field->subfield('w'), 2, 1;
998 $type = 'earlier' if $type && $type ne 'n';
1000 if ($type eq 'subfi') {
1002 heading => $field->as_string($marc21subfields),
1003 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1004 type => ($field->subfield('i') || ''),
1005 field => $field->tag(),
1009 heading => $field->as_string($marc21subfields),
1010 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1012 field => $field->tag(),
1016 foreach my $field ($record->field('5..')) { #See Also
1017 my $type = 'seealso';
1018 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1019 if ($type eq 'notapplicable') {
1020 $type = substr $field->subfield('w'), 2, 1;
1021 $type = 'earlier' if $type && $type ne 'n';
1023 if ($type eq 'subfi') {
1025 heading => $field->as_string($marc21subfields),
1026 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1027 type => scalar $field->subfield('i'),
1028 field => $field->tag(),
1029 search => $field->as_string($marc21subfields) || '',
1030 authid => $field->subfield('9') || ''
1034 heading => $field->as_string($marc21subfields),
1035 hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1037 field => $field->tag(),
1038 search => $field->as_string($marc21subfields) || '',
1039 authid => $field->subfield('9') || ''
1043 foreach my $field ($record->field('6..')) {
1044 push @notes, { note => $field->as_string(), field => $field->tag() };
1046 foreach my $field ($record->field('880')) {
1047 my $linkage = $field->subfield('6');
1048 my $category = substr $linkage, 0, 1;
1049 if ($category eq '1') {
1050 $category = 'preferred';
1051 } elsif ($category eq '4') {
1052 $category = 'seefrom';
1053 } elsif ($category eq '5') {
1054 $category = 'seealso';
1057 if ($field->subfield('w')) {
1058 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1062 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1063 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1066 $summary{mainentry} = $authorized[0]->{heading};
1067 $summary{mainmainentry} = $authorized[0]->{hemain};
1068 $summary{authorized} = \@authorized;
1069 $summary{notes} = \@notes;
1070 $summary{seefrom} = \@seefrom;
1071 $summary{seealso} = \@seealso;
1072 $summary{otherscript} = \@otherscript;
1076 =head2 GetAuthorizedHeading
1078 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1080 Takes a MARC::Record object describing an authority record or an authid, and
1081 returns a string representation of the first authorized heading. This routine
1082 should be considered a temporary shim to ease the future migration of authority
1083 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1087 sub GetAuthorizedHeading {
1090 unless ($record = $args->{record}) {
1091 return unless $args->{authid};
1092 $record = GetAuthority($args->{authid});
1094 return unless (ref $record eq 'MARC::Record');
1095 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1096 # construct UNIMARC summary, that is quite different from MARC21 one
1098 foreach my $field ($record->field('2..')) {
1099 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1102 foreach my $field ($record->field('1..')) {
1103 my $tag = $field->tag();
1104 next if "152" eq $tag;
1105 # FIXME - 152 is not a good tag to use
1106 # in MARC21 -- purely local tags really ought to be
1108 if ($tag eq '100') {
1109 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1110 } elsif ($tag eq '110') {
1111 return $field->as_string('abcdefghklmnoprstvxyz68');
1112 } elsif ($tag eq '111') {
1113 return $field->as_string('acdefghklnpqstvxyz68');
1114 } elsif ($tag eq '130') {
1115 return $field->as_string('adfghklmnoprstvxyz68');
1116 } elsif ($tag eq '148') {
1117 return $field->as_string('abvxyz68');
1118 } elsif ($tag eq '150') {
1119 return $field->as_string('abvxyz68');
1120 } elsif ($tag eq '151') {
1121 return $field->as_string('avxyz68');
1122 } elsif ($tag eq '155') {
1123 return $field->as_string('abvxyz68');
1124 } elsif ($tag eq '180') {
1125 return $field->as_string('vxyz68');
1126 } elsif ($tag eq '181') {
1127 return $field->as_string('vxyz68');
1128 } elsif ($tag eq '182') {
1129 return $field->as_string('vxyz68');
1130 } elsif ($tag eq '185') {
1131 return $field->as_string('vxyz68');
1133 return $field->as_string();
1140 =head2 BuildAuthHierarchies
1142 $text= &BuildAuthHierarchies( $authid, $force)
1144 return text containing trees for hierarchies
1145 for them to be stored in auth_header
1148 122,1314,2452;1324,2342,3,2452
1152 sub BuildAuthHierarchies{
1153 my $authid = shift @_;
1154 # warn "authid : $authid";
1155 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1157 my $dbh=C4::Context->dbh;
1159 my $data = GetHeaderAuthority($authid);
1160 if ($data->{'authtrees'} and not $force){
1161 return $data->{'authtrees'};
1162 # } elsif ($data->{'authtrees'}){
1163 # $hierarchies=$data->{'authtrees'};
1165 my $record = GetAuthority($authid);
1167 return unless $record;
1168 foreach my $field ($record->field('5..')){
1171 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1172 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1174 my $subfauthid=_get_authid_subfield($field) || '';
1175 next if ($subfauthid eq $authid);
1176 my $parentrecord = GetAuthority($subfauthid);
1177 next unless $parentrecord;
1178 my $localresult=$hierarchies;
1180 $trees = BuildAuthHierarchies($subfauthid);
1183 @trees = split(/;/,$trees);
1185 push @trees, $trees;
1190 @globalresult = (@globalresult,@trees);
1193 $hierarchies=join(";",@globalresult);
1195 #Unless there is no ancestor, I am alone.
1196 $hierarchies="$authid" unless ($hierarchies);
1198 AddAuthorityTrees($authid,$hierarchies);
1199 return $hierarchies;
1202 =head2 BuildAuthHierarchy
1204 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1206 return a hashref in order to display hierarchy for record and final Authid $authid
1217 sub BuildAuthHierarchy{
1218 my $record = shift @_;
1219 my $class = shift @_;
1220 my $authid_constructed = shift @_;
1221 return unless ($record && $record->field('001'));
1222 my $authid=$record->field('001')->data();
1224 my $parents=""; my $children="";
1225 my (@loopparents,@loopchildren);
1226 my $marcflavour = C4::Context->preference('marcflavour');
1227 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1228 foreach my $field ($record->field('5..')){
1229 my $subfauthid=_get_authid_subfield($field);
1230 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1231 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1232 if ($relationship eq 'h'){
1233 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1235 elsif ($relationship eq 'g'){
1236 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1238 # brothers could get in there with an else
1241 $cell{"parents"}=\@loopparents;
1242 $cell{"children"}=\@loopchildren;
1243 $cell{"class"}=$class;
1244 $cell{"authid"}=$authid;
1245 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1246 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1250 =head2 BuildAuthHierarchyBranch
1252 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1254 Return a data structure representing an authority hierarchy
1255 given a list of authorities representing a single branch in
1256 an authority hierarchy tree. $authid is the current node in
1257 the tree (which may or may not be somewhere in the middle).
1258 $cnt represents the level of the upper-most item, and is only
1259 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1260 don't ever pass in anything but zero to it).
1264 sub BuildAuthHierarchyBranch {
1265 my ($tree, $authid, $cnt) = @_;
1267 my $elementdata = GetAuthority(shift @$tree);
1268 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1269 if (scalar @$tree > 0) {
1270 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1271 my $nextAuthid = $nextBranch->{authid};
1273 # If we already have the next branch listed as a child, let's
1274 # replace the old listing with the new one. If not, we will add
1275 # the branch at the end.
1276 foreach my $cell (@{$branch->{children}}) {
1277 if ($cell->{authid} eq $nextAuthid) {
1278 $cell = $nextBranch;
1283 push @{$branch->{children}}, $nextBranch unless $found;
1288 =head2 GenerateHierarchy
1290 $hierarchy = &GenerateHierarchy($authid);
1292 Return an arrayref holding one or more "trees" representing
1293 authority hierarchies.
1297 sub GenerateHierarchy {
1299 my $trees = BuildAuthHierarchies($authid);
1300 my @trees = split /;/,$trees ;
1301 push @trees,$trees unless (@trees);
1302 my @loophierarchies;
1303 foreach my $tree (@trees){
1304 my @tree=split /,/,$tree;
1305 push @tree, $tree unless (@tree);
1306 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1307 push @loophierarchies, [ $branch ];
1309 return \@loophierarchies;
1312 sub _get_authid_subfield{
1314 return $field->subfield('9')||$field->subfield('3');
1317 =head2 GetHeaderAuthority
1319 $ref= &GetHeaderAuthority( $authid)
1321 return a hashref in order auth_header table data
1325 sub GetHeaderAuthority{
1326 my $authid = shift @_;
1327 my $sql= "SELECT * from auth_header WHERE authid = ?";
1328 my $dbh=C4::Context->dbh;
1329 my $rq= $dbh->prepare($sql);
1330 $rq->execute($authid);
1331 my $data= $rq->fetchrow_hashref;
1335 =head2 AddAuthorityTrees
1337 $ref= &AddAuthorityTrees( $authid, $trees)
1339 return success or failure
1343 sub AddAuthorityTrees{
1344 my $authid = shift @_;
1345 my $trees = shift @_;
1346 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1347 my $dbh=C4::Context->dbh;
1348 my $rq= $dbh->prepare($sql);
1349 return $rq->execute($trees,$authid);
1355 mergefrom => $mergefrom,
1356 [ MARCfrom => $MARCfrom, ]
1357 [ mergeto => $mergeto, ]
1358 [ MARCto => $MARCto, ]
1359 [ biblionumbers => [ $a, $b, $c ], ]
1360 [ override_limit => 1, ]
1363 Merge biblios linked to authority $mergefrom (mandatory parameter).
1364 If $mergeto equals mergefrom, the linked biblio field is updated.
1365 If $mergeto is different, the biblio field will be linked to $mergeto.
1366 If $mergeto is missing, the biblio field is deleted.
1368 MARCfrom is used to determine if a cleared subfield in the authority record
1369 should be removed from a biblio. MARCto is used to populate the biblio
1370 record with the updated values; if you do not pass it, the biblio field
1371 will be deleted (same as missing mergeto).
1373 Normally all biblio records linked to $mergefrom, will be considered. But
1374 you can pass specific numbers via the biblionumbers parameter.
1376 The parameter override_limit is used by the cron job to force larger
1379 Note: Although $mergefrom and $mergeto will normally be of the same
1380 authority type, merge also supports moving to another authority type.
1385 my ( $params ) = @_;
1386 my $mergefrom = $params->{mergefrom} || return;
1387 my $MARCfrom = $params->{MARCfrom};
1388 my $mergeto = $params->{mergeto};
1389 my $MARCto = $params->{MARCto};
1390 my $override_limit = $params->{override_limit};
1392 # If we do not have biblionumbers, we get all linked biblios if the
1393 # number of linked records does not exceed the limit UNLESS we override.
1395 if( $params->{biblionumbers} ) {
1396 @biblionumbers = @{ $params->{biblionumbers} };
1397 } elsif( $override_limit ) {
1398 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1399 } else { # now first check number of linked records
1400 my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1401 my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1402 if( $hits > 0 && $hits <= $max ) {
1403 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1404 } elsif( $hits > $max ) { #postpone this merge to the cron job
1405 Koha::Authority::MergeRequest->new({
1406 authid => $mergefrom,
1407 oldrecord => $MARCfrom,
1408 authid_new => $mergeto,
1412 return 0 if !@biblionumbers;
1414 # Search authtypes and reporting tags
1415 my $authfrom = Koha::Authorities->find($mergefrom);
1416 my $authto = Koha::Authorities->find($mergeto);
1417 my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1418 my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1419 my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1420 my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1423 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1424 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1425 # is empty, make sure that $9 and $a remain (instead of clearing the
1426 # reference) in order to allow for data recovery.
1427 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1428 if( $MARCto && $authtypeto && !@record_to ) {
1429 push @record_to, [ 'a', ' ' ]; # do not remove the space
1433 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1434 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1435 # 2XX is for UNIMARC; we use -1 in order to skip 100 in UNIMARC; this will not impact MARC21, since there is only one tag
1436 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1437 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1438 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1441 # Get all candidate tags for the change
1442 # (This will reduce the search scope in marc records).
1443 # For a deleted authority record, we scan all auth controlled fields
1444 my $dbh = C4::Context->dbh;
1445 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1446 my $tags_using_authtype = $authtypefrom && $authtypefrom->authtypecode ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode )) : $dbh->selectcol_arrayref( "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''" );
1448 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1449 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1452 my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1453 my $skip_subfields = $overwrite
1454 # This hash contains all subfields from the authority report fields
1455 # Including $MARCfrom as well as $MARCto
1456 # We only need it in loose merge mode; replaces the former $exclude
1458 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1460 my $counteditedbiblio = 0;
1461 foreach my $biblionumber ( @biblionumbers ) {
1462 my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1463 next if !$marcrecord;
1465 foreach my $tagfield (@$tags_using_authtype) {
1466 my $countfrom = 0; # used in strict mode to remove duplicates
1467 foreach my $field ( $marcrecord->field($tagfield) ) {
1468 my $auth_number = $field->subfield("9"); # link to authority
1469 my $tag = $field->tag();
1470 next if !defined($auth_number) || $auth_number ne $mergefrom;
1472 if ( !$mergeto || !@record_to ||
1473 ( $overwrite && $countfrom > 1 ) ) {
1474 # !mergeto or !record_to indicates a delete
1475 # Other condition: remove this duplicate in strict mode
1476 $marcrecord->delete_field($field);
1480 my $newtag = $tags_new && @$tags_new
1481 ? _merge_newtag( $tag, $tags_new )
1483 my $controlled_ind = $authto->controlled_indicators({ record => $MARCto, biblio_tag => $newtag });
1484 my $field_to = MARC::Field->new(
1486 $controlled_ind->{ind1} // $field->indicator(1),
1487 $controlled_ind->{ind2} // $field->indicator(2),
1488 9 => $mergeto, # Needed to create field, will be moved
1490 my ( @prefix, @postfix );
1491 if ( !$overwrite ) {
1492 # add subfields back in loose mode, check skip_subfields
1493 # The first extra subfields will be in front of the
1494 # controlled block, the rest at the end.
1495 my $prefix_flag = 1;
1496 foreach my $subfield ( $field->subfields ) {
1497 next if $subfield->[0] eq '9'; # skip but leave flag
1498 if ( $skip_subfields->{ $subfield->[0] } ) {
1499 # This marks the beginning of the controlled block
1504 push @prefix, [ $subfield->[0], $subfield->[1] ];
1506 push @postfix, [ $subfield->[0], $subfield->[1] ];
1510 foreach my $subfield ( @prefix, @record_to, @postfix ) {
1511 $field_to->add_subfields($subfield->[0] => $subfield->[1]);
1513 if( exists $controlled_ind->{sub2} ) { # thesaurus info
1514 if( defined $controlled_ind->{sub2} ) {
1516 $field_to->update( 2 => $controlled_ind->{sub2} );
1518 # Key alerts us here to remove $2
1519 $field_to->delete_subfield( code => '2' );
1522 # Move $9 to the end
1523 $field_to->delete_subfield( code => '9' );
1524 $field_to->add_subfields( 9 => $mergeto );
1526 if ($tags_new && @$tags_new) {
1527 $marcrecord->delete_field($field);
1528 append_fields_ordered( $marcrecord, $field_to );
1530 $field->replace_with($field_to);
1536 ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1537 $counteditedbiblio++;
1539 return $counteditedbiblio;
1543 # Routine is only called for an (exceptional) authtypecode change
1544 # Fixes old behavior of returning the first tag found
1545 my ( $oldtag, $new_tags ) = @_;
1547 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1548 my $prefix = substr( $oldtag, 0, 1 );
1549 my $guess = $prefix . substr( $new_tags->[0], -2 );
1550 if( grep { $_ eq $guess } @$new_tags ) {
1553 # Otherwise return one from the same block e.g. 6XX for 650
1554 # If not there too, fall back to first new tag (old behavior!)
1555 my @same_block = grep { /^$prefix/ } @$new_tags;
1556 return @same_block ? $same_block[0] : $new_tags->[0];
1559 sub append_fields_ordered {
1560 # while we lack this function in MARC::Record
1561 # we do not want insert_fields_ordered since it inserts before
1562 my ( $record, $field ) = @_;
1563 if( my @flds = $record->field( $field->tag ) ) {
1564 $record->insert_fields_after( pop @flds, $field );
1565 } else { # now fallback to insert_fields_ordered
1566 $record->insert_fields_ordered( $field );
1570 =head2 get_auth_type_location
1572 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1574 Get the tag and subfield used to store the heading type
1575 for indexing purposes. The C<$auth_type> parameter is
1576 optional; if it is not supplied, assume ''.
1578 This routine searches the MARC authority framework
1579 for the tag and subfield whose kohafield is
1580 C<auth_header.authtypecode>; if no such field is
1581 defined in the framework, default to the hardcoded value
1582 specific to the MARC format.
1586 sub get_auth_type_location {
1587 my $auth_type_code = @_ ? shift : '';
1589 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1590 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1591 return ($tag, $subfield);
1593 if (C4::Context->preference('marcflavour') eq "MARC21") {
1594 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1596 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1601 END { } # module clean-up code here (global destructor)
1608 Koha Development Team <http://koha-community.org/>
1610 Paul POULAIN paul.poulain@free.fr