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::MergeRequest;
33 use Koha::Authority::Types;
36 use Koha::SearchEngine;
37 use Koha::SearchEngine::Search;
39 use vars qw(@ISA @EXPORT);
47 &GetAuthMARCFromKohaField
65 &FindDuplicateAuthority
77 =head2 GetAuthMARCFromKohaField
79 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
81 returns tag and subfield linked to kohafield
84 Suppose Kohafield is only linked to ONE subfield
88 sub GetAuthMARCFromKohaField {
89 #AUTHfind_marc_from_kohafield
90 my ( $kohafield,$authtypecode ) = @_;
91 my $dbh=C4::Context->dbh;
92 return 0, 0 unless $kohafield;
93 $authtypecode="" unless $authtypecode;
94 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
95 $sth->execute($kohafield,$authtypecode);
96 my ($tagfield,$tagsubfield) = $sth->fetchrow;
98 return ($tagfield,$tagsubfield);
101 =head2 SearchAuthorities
103 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
104 $excluding, $operator, $value, $offset,$length,$authtypecode,
105 $sortby[, $skipmetadata])
107 returns ref to array result and count of results returned
111 sub SearchAuthorities {
112 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
113 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
114 my $dbh=C4::Context->dbh;
115 $sortby="" unless $sortby;
119 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
121 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
122 # the authtypecode. Then, search on $a of this tag_to_report
123 # also store main entry MARC tag, to extract it at end of search
125 ##first set the authtype search and may be multiple authorities
129 my @auths=split / /,$authtypecode ;
130 foreach my $auth (@auths){
131 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
132 push @authtypecode ,$auth;
136 while ($n>1){$query= "\@or ".$query;$n--;}
139 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
147 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
150 if ( @$tags[$i] eq "mainmainentry" ) {
151 $attr = " \@attr 1=Heading-Main ";
153 elsif ( @$tags[$i] eq "mainentry" ) {
154 $attr = " \@attr 1=Heading ";
156 elsif ( @$tags[$i] eq "match" ) {
157 $attr = " \@attr 1=Match ";
159 elsif ( @$tags[$i] eq "match-heading" ) {
160 $attr = " \@attr 1=Match-heading ";
162 elsif ( @$tags[$i] eq "see-from" ) {
163 $attr = " \@attr 1=Match-heading-see-from ";
165 elsif ( @$tags[$i] eq "thesaurus" ) {
166 $attr = " \@attr 1=Subject-heading-thesaurus ";
168 else { # Assume any if no index was specified
169 $attr = " \@attr 1=Any ";
172 else { # Assume any if no index was specified
173 $attr = " \@attr 1=Any ";
176 my $operator = @$operator[$i];
177 if ( $operator and $operator eq 'is' ) {
178 $attr .= " \@attr 4=1 \@attr 5=100 "
179 ; ##Phrase, No truncation,all of subfield field must match
181 elsif ( $operator and $operator eq "=" ) {
182 $attr .= " \@attr 4=107 "; #Number Exact match
184 elsif ( $operator and $operator eq "start" ) {
185 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
186 ; #Firstinfield Phrase, Right truncated
188 elsif ( $operator and $operator eq "exact" ) {
189 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
190 ; ##Phrase, No truncation,all of subfield field must match
193 $attr .= " \@attr 5=1 \@attr 4=6 "
194 ; ## Word list, right truncated, anywhere
195 if ( $sortby eq 'Relevance' ) {
196 $attr .= "\@attr 2=102 ";
200 s/"/\\"/g; # Escape the double-quotes in the search value
201 $attr = $attr . "\"" . @$value[$i] . "\"";
206 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
210 ##Add how many queries generated
211 if (defined $query && $query=~/\S+/){
212 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
217 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
219 if ($sortby eq 'HeadingAsc') {
220 $orderstring = '@attr 7=1 @attr 1=Heading 0';
221 } elsif ($sortby eq 'HeadingDsc') {
222 $orderstring = '@attr 7=2 @attr 1=Heading 0';
223 } elsif ($sortby eq 'AuthidAsc') {
224 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
225 } elsif ($sortby eq 'AuthidDsc') {
226 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
229 $qpquery .= ' all:all' unless $value->[0];
231 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
235 $qpquery .= " #$sortby" unless $sortby eq '';
237 $QParser->parse( $qpquery );
238 $query = $QParser->target_syntax('authorityserver');
240 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
241 $query="\@or $orderstring $query" if $orderstring;
244 $offset = 0 if not defined $offset or $offset < 0;
245 my $counter = $offset;
246 $length=10 unless $length;
249 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
250 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
252 $oAResult= $oAuth[0]->search($Anewq) ;
253 while (($i = ZOOM::event(\@oAuth)) != 0) {
254 my $ev = $oAuth[$i-1]->last_event();
255 last if $ev == ZOOM::Event::ZEND;
257 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
259 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
264 $nbresults=$oAResult->size();
265 my $nremains=$nbresults;
267 my @finalresult = ();
271 ##Find authid and linkid fields
272 ##we may be searching multiple authoritytypes.
273 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
274 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
275 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
276 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
278 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
279 my $rec=$oAResult->record($counter);
280 my $separator=C4::Context->preference('AuthoritySeparator');
281 my $authrecord = C4::Search::new_record_from_zebra(
286 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
291 SetUTF8Flag( $authrecord );
293 my $authid=$authrecord->field('001')->data();
295 $newline{authid} = $authid;
296 if ( !$skipmetadata ) {
297 my $auth_tag_to_report;
298 $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report
301 my $mainentry = $authrecord->field($auth_tag_to_report);
303 foreach ( $mainentry->subfields() ) {
304 $reported_tag .= '$' . $_->[0] . $_->[1];
308 my ( $thisauthtype, $thisauthtypecode );
309 if ( my $authority = Koha::Authorities->find($authid) ) {
310 $thisauthtypecode = $authority->authtypecode;
311 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
313 unless (defined $thisauthtype) {
314 $thisauthtypecode = $authtypecode;
315 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
317 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
319 $newline{authtype} = defined($thisauthtype) ?
320 $thisauthtype->authtypetext : '';
321 $newline{summary} = $summary;
322 $newline{even} = $counter % 2;
323 $newline{reported_tag} = $reported_tag;
326 push @finalresult, \%newline;
329 if (! $skipmetadata) {
330 for (my $z=0; $z<@finalresult; $z++){
331 my $count=CountUsage($finalresult[$z]{authid});
332 $finalresult[$z]{used}=$count;
338 $oAResult->destroy();
339 # $oAuth[0]->destroy();
341 return (\@finalresult, $nbresults);
346 $count= &CountUsage($authid)
348 counts Usage of Authid in bibliorecords.
356 $query= "an:".$authid;
357 # Should really be replaced with a real count call, this is a
359 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
360 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,1);
362 warn "Error: $err from search $query";
369 =head2 CountUsageChildren
371 $count= &CountUsageChildren($authid)
373 counts Usage of narrower terms of Authid in bibliorecords.
377 sub CountUsageChildren {
381 =head2 GuessAuthTypeCode
383 my $authtypecode = GuessAuthTypeCode($record);
385 Get the record and tries to guess the adequate authtypecode from its content.
389 sub GuessAuthTypeCode {
390 my ($record, $heading_fields) = @_;
391 return unless defined $record;
392 $heading_fields //= {
394 '100'=>{authtypecode=>'PERSO_NAME'},
395 '110'=>{authtypecode=>'CORPO_NAME'},
396 '111'=>{authtypecode=>'MEETI_NAME'},
397 '130'=>{authtypecode=>'UNIF_TITLE'},
398 '148'=>{authtypecode=>'CHRON_TERM'},
399 '150'=>{authtypecode=>'TOPIC_TERM'},
400 '151'=>{authtypecode=>'GEOGR_NAME'},
401 '155'=>{authtypecode=>'GENRE/FORM'},
402 '180'=>{authtypecode=>'GEN_SUBDIV'},
403 '181'=>{authtypecode=>'GEO_SUBDIV'},
404 '182'=>{authtypecode=>'CHRON_SUBD'},
405 '185'=>{authtypecode=>'FORM_SUBD'},
407 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
408 # 604 with embedded 700, 701, 702
409 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
410 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
411 #216 Trademark 716 [Reserved for future use]
412 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
413 #230 Title 500 4-- with embedded 500 605
414 #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
415 #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
416 #250 Topical subject 606
417 #260 Place access 620
418 #280 Form, genre or physical characteristics 608
421 # Could also be represented with :
423 #a = personal name entry
424 #b = corporate name entry
425 #c = territorial or geographical name
429 #g = collective uniform title
431 #i = name/collective uniform title
434 #l = form, genre or physical characteristics
436 '200'=>{authtypecode=>'NP'},
437 '210'=>{authtypecode=>'CO'},
438 '215'=>{authtypecode=>'SNG'},
439 '216'=>{authtypecode=>'TM'},
440 '220'=>{authtypecode=>'FAM'},
441 '230'=>{authtypecode=>'TU'},
442 '235'=>{authtypecode=>'CO_UNI_TI'},
443 '240'=>{authtypecode=>'SAUTTIT'},
444 '245'=>{authtypecode=>'NAME_COL'},
445 '250'=>{authtypecode=>'SNC'},
446 '260'=>{authtypecode=>'PA'},
447 '280'=>{authtypecode=>'GENRE/FORM'},
450 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
451 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
458 my $authtid = GuessAuthId($record);
460 Get the record and tries to guess the adequate authtypecode from its content.
466 return unless ($record && $record->field('001'));
467 # my $authtypecode=GuessAuthTypeCode($record);
468 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
469 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
470 # else {return $record->field($tag)->data}
471 return $record->field('001')->data;
476 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
478 returns a ref to hashref of authorities tag and subfield structure.
482 $tagslabel->{$tag}->{$subfield}->{'attribute'}
484 where attribute takes values in :
502 my ($forlibrarian,$authtypecode)= @_;
503 my $dbh=C4::Context->dbh;
504 $authtypecode="" unless $authtypecode;
506 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
509 # check that authority exists
510 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
511 $sth->execute($authtypecode);
512 my ($total) = $sth->fetchrow;
513 $authtypecode="" unless ($total >0);
515 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
516 FROM auth_tag_structure
521 $sth->execute($authtypecode);
522 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
524 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
525 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
526 $res->{$tag}->{tab} = " "; # XXX
527 $res->{$tag}->{mandatory} = $mandatory;
528 $res->{$tag}->{repeatable} = $repeatable;
531 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
532 FROM auth_subfield_structure
534 ORDER BY tagfield,tagsubfield"
536 $sth->execute($authtypecode);
539 my $authorised_value;
549 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
550 $mandatory, $repeatable, $authorised_value, $authtypecode,
551 $value_builder, $kohafield, $seealso, $hidden,
552 $isurl, $defaultvalue, $link )
556 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
557 $res->{$tag}->{$subfield}->{tab} = $tab;
558 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
559 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
560 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
561 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
562 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
563 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
564 $res->{$tag}->{$subfield}->{seealso} = $seealso;
565 $res->{$tag}->{$subfield}->{hidden} = $hidden;
566 $res->{$tag}->{$subfield}->{isurl} = $isurl;
567 $res->{$tag}->{$subfield}->{link} = $link;
568 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
575 $authid= &AddAuthority($record, $authid,$authtypecode)
577 Either Create Or Modify existing authority.
578 returns authid of the newly created authority
583 # pass the MARC::Record to this function, and it will create the records in the authority table
584 my ($record,$authid,$authtypecode) = @_;
585 my $dbh=C4::Context->dbh;
586 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
588 # if authid empty => true add, find a new authid number
590 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
591 $format= 'UNIMARCAUTH';
597 #update date/time to 005 for marc and unimarc
598 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
599 my $f5=$record->field('005');
601 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
604 $f5->update($time.".0");
607 SetUTF8Flag($record);
608 if ($format eq "MARC21") {
609 my $userenv = C4::Context->userenv;
611 my $marcorgcode = C4::Context->preference('MARCOrgCode');
612 if ( $userenv && $userenv->{'branch'} ) {
613 $library = Koha::Libraries->find( $userenv->{'branch'} );
614 $marcorgcode = $library->get_effective_marcorgcode;
616 if (!$record->leader) {
617 $record->leader($leader);
619 if (!$record->field('003')) {
620 $record->insert_fields_ordered(
621 MARC::Field->new('003', $marcorgcode),
624 my $date=POSIX::strftime("%y%m%d",localtime);
625 if (!$record->field('008')) {
626 # Get a valid default value for field 008
627 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
628 if(!$default_008 or length($default_008)<34) {
629 $default_008 = '|| aca||aabn | a|a d';
632 $default_008 = substr($default_008,0,34);
635 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
637 if (!$record->field('040')) {
638 $record->insert_fields_ordered(
639 MARC::Field->new('040','','',
647 if ($format eq "UNIMARCAUTH") {
648 $record->leader(" nx j22 ") unless ($record->leader());
649 my $date=POSIX::strftime("%Y%m%d",localtime);
650 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
651 if (my $string=$record->subfield('100',"a")){
652 $string=~s/fre50/frey50/;
653 $record->field('100')->update('a'=>$string);
655 elsif ($record->field('100')){
656 $record->field('100')->update('a'=>$date.$defaultfield100);
658 $record->append_fields(
659 MARC::Field->new('100',' ',' '
660 ,'a'=>$date.$defaultfield100)
664 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
665 if (!$authid and $format eq "MARC21") {
666 # only need to do this fix when modifying an existing authority
667 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
669 if (my $field=$record->field($auth_type_tag)){
670 $field->update($auth_type_subfield=>$authtypecode);
673 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
676 # Save record into auth_header, update 001
678 # Save a blank record, get authid
679 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
680 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
681 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
683 # Insert/update the recordID in MARC record
684 $record->delete_field( $record->field('001') );
685 $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
687 $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;
688 ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
695 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
697 Deletes $authid and calls merge to cleanup linked biblio records.
698 Parameter skip_merge is used in authorities/merge.pl. You should normally not
705 my $authid = $params->{authid} || return;
706 my $skip_merge = $params->{skip_merge};
707 my $dbh = C4::Context->dbh;
708 merge({ mergefrom => $authid }) if !$skip_merge;
709 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
710 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
711 ModZebra( $authid, "recordDelete", "authorityserver", undef);
716 $authid= &ModAuthority($authid,$record,$authtypecode)
718 Modifies authority record, optionally updates attached biblios.
723 my ( $authid, $record, $authtypecode ) = @_;
724 my $oldrecord = GetAuthority($authid);
725 #Now rewrite the $record to table with an add
726 $authid = AddAuthority($record, $authid, $authtypecode);
727 merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
728 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
732 =head2 GetAuthorityXML
734 $marcxml= &GetAuthorityXML( $authid)
736 returns xml form of record $authid
740 sub GetAuthorityXML {
741 # Returns MARC::XML of the authority passed in parameter.
743 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
744 my $dbh=C4::Context->dbh;
745 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
746 $sth->execute($authid);
747 my ($marcxml)=$sth->fetchrow;
751 # for MARC21, call GetAuthority instead of
752 # getting the XML directly since we may
753 # need to fix up the location of the authority
754 # code -- note that this is reasonably safe
755 # because GetAuthorityXML is used only by the
756 # indexing processes like zebraqueue_start.pl
757 my $record = GetAuthority($authid);
758 return $record->as_xml_record('MARC21');
764 $record= &GetAuthority( $authid)
766 Returns MARC::Record of the authority passed in parameter.
772 my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
773 return unless $authority;
774 return ($authority->record);
777 =head2 FindDuplicateAuthority
779 $record= &FindDuplicateAuthority( $record, $authtypecode)
781 return $authid,Summary if duplicate is found.
783 Comments : an improvement would be to return All the records that match.
787 sub FindDuplicateAuthority {
789 my ($record,$authtypecode)=@_;
790 # warn "IN for ".$record->as_formatted;
791 my $dbh = C4::Context->dbh;
792 # warn "".$record->as_formatted;
793 my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
794 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
795 # build a request for SearchAuthorities
797 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
804 my $query='at:'.$authtypecode.' ';
805 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
806 if ($record->field($auth_tag_to_report)) {
807 foreach ($record->field($auth_tag_to_report)->subfields()) {
808 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
811 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
812 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1 );
813 # there is at least 1 result => return the 1st one
814 if (!defined $error && @{$results} ) {
815 my $marcrecord = C4::Search::new_record_from_zebra(
819 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
821 # no result, returns nothing
827 $summary= &BuildSummary( $record, $authid, $authtypecode)
829 Returns a hashref with a summary of the specified record.
831 Comment : authtypecode can be inferred from both record and authid.
832 Moreover, authid can also be inferred from $record.
833 Would it be interesting to delete those things.
838 ## give this a Marc record to return summary
839 my ($record,$authid,$authtypecode)=@_;
840 my $dbh=C4::Context->dbh;
842 my $summary_template;
843 # handle $authtypecode is NULL or eq ""
845 my $authref = Koha::Authority::Types->find($authtypecode);
847 $summary{authtypecode} = $authref->authtypecode;
848 $summary{type} = $authref->authtypetext;
849 $summary_template = $authref->summary;
850 # for MARC21, the authority type summary displays a label meant for
852 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
853 $summary{label} = $authref->summary;
855 $summary{summary} = $authref->summary;
859 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
860 my %marc21controlrefs = ( 'a' => 'earlier',
866 'n' => 'notapplicable',
870 my %unimarc_relation_from_code = (
876 $thesaurus{'1'}="Peuples";
877 $thesaurus{'2'}="Anthroponymes";
878 $thesaurus{'3'}="Oeuvres";
879 $thesaurus{'4'}="Chronologie";
880 $thesaurus{'5'}="Lieux";
881 $thesaurus{'6'}="Sujets";
884 # if the library has a summary defined, use it. Otherwise, build a standard one
885 # FIXME - it appears that the summary field in the authority frameworks
886 # can work as a display template. However, this doesn't
887 # suit the MARC21 version, so for now the "templating"
888 # feature will be enabled only for UNIMARC for backwards
890 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
891 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
892 my (@textbefore, @tag, @subtag, @textafter);
893 for(my $i = 0; $i < scalar @matches; $i++){
894 push @textbefore, $matches[$i] if($i%4 == 0);
895 push @tag, $matches[$i] if($i%4 == 1);
896 push @subtag, $matches[$i] if($i%4 == 2);
897 push @textafter, $matches[$i] if($i%4 == 3);
899 for(my $i = scalar @tag; $i >= 0; $i--){
900 my $textbefore = $textbefore[$i] || '';
901 my $tag = $tag[$i] || '';
902 my $subtag = $subtag[$i] || '';
903 my $textafter = $textafter[$i] || '';
905 my $field = $record->field($tag);
909 $value = $textbefore . $field->data() . $textafter;
912 my @subfields = $field->subfield($subtag);
914 $value = $textbefore . join (" - ", @subfields) . $textafter;
918 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
920 $summary{summary} =~ s/\\n/<br \/>/g;
927 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
928 # construct UNIMARC summary, that is quite different from MARC21 one
930 foreach my $field ($record->field('2..')) {
932 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
933 hemain => ( $field->subfield('a') // undef ),
934 field => $field->tag(),
938 foreach my $field ($record->field('3..')) {
939 push @notes, { note => $field->subfield('a'), field => $field->tag() };
941 foreach my $field ($record->field('4..')) {
942 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
944 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
945 hemain => ( $field->subfield('a') // undef ),
947 field => $field->tag(),
953 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
954 my $heading = $_->as_string('abcdefgjxyz');
959 hemain => ( $_->subfield('a') // undef ),
961 authid => ( $_->subfield('9') // undef ),
963 } $record->field('5..');
966 @otherscript = map { {
967 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
968 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
971 } } $record->field('7..');
974 # construct MARC21 summary
975 # FIXME - looping over 1XX is questionable
976 # since MARC21 authority should have only one 1XX
977 my $subfields_to_report;
978 foreach my $field ($record->field('1..')) {
979 my $tag = $field->tag();
980 next if "152" eq $tag;
981 # FIXME - 152 is not a good tag to use
982 # in MARC21 -- purely local tags really ought to be
985 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
986 } elsif ($tag eq '110') {
987 $subfields_to_report = 'abcdefghklmnoprstvxyz';
988 } elsif ($tag eq '111') {
989 $subfields_to_report = 'acdefghklnpqstvxyz';
990 } elsif ($tag eq '130') {
991 $subfields_to_report = 'adfghklmnoprstvxyz';
992 } elsif ($tag eq '148') {
993 $subfields_to_report = 'abvxyz';
994 } elsif ($tag eq '150') {
995 $subfields_to_report = 'abvxyz';
996 } elsif ($tag eq '151') {
997 $subfields_to_report = 'avxyz';
998 } elsif ($tag eq '155') {
999 $subfields_to_report = 'abvxyz';
1000 } elsif ($tag eq '180') {
1001 $subfields_to_report = 'vxyz';
1002 } elsif ($tag eq '181') {
1003 $subfields_to_report = 'vxyz';
1004 } elsif ($tag eq '182') {
1005 $subfields_to_report = 'vxyz';
1006 } elsif ($tag eq '185') {
1007 $subfields_to_report = 'vxyz';
1009 if ($subfields_to_report) {
1011 heading => $field->as_string($subfields_to_report),
1012 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1017 heading => $field->as_string(),
1018 hemain => ( $field->subfield( 'a' ) // undef ),
1023 foreach my $field ($record->field('4..')) { #See From
1024 my $type = 'seefrom';
1025 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1026 if ($type eq 'notapplicable') {
1027 $type = substr $field->subfield('w'), 2, 1;
1028 $type = 'earlier' if $type && $type ne 'n';
1030 if ($type eq 'subfi') {
1032 heading => $field->as_string($marc21subfields),
1033 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1034 type => ($field->subfield('i') || ''),
1035 field => $field->tag(),
1039 heading => $field->as_string($marc21subfields),
1040 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1042 field => $field->tag(),
1046 foreach my $field ($record->field('5..')) { #See Also
1047 my $type = 'seealso';
1048 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1049 if ($type eq 'notapplicable') {
1050 $type = substr $field->subfield('w'), 2, 1;
1051 $type = 'earlier' if $type && $type ne 'n';
1053 if ($type eq 'subfi') {
1055 heading => $field->as_string($marc21subfields),
1056 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1057 type => $field->subfield('i'),
1058 field => $field->tag(),
1059 search => $field->as_string($marc21subfields) || '',
1060 authid => $field->subfield('9') || ''
1064 heading => $field->as_string($marc21subfields),
1065 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1067 field => $field->tag(),
1068 search => $field->as_string($marc21subfields) || '',
1069 authid => $field->subfield('9') || ''
1073 foreach my $field ($record->field('6..')) {
1074 push @notes, { note => $field->as_string(), field => $field->tag() };
1076 foreach my $field ($record->field('880')) {
1077 my $linkage = $field->subfield('6');
1078 my $category = substr $linkage, 0, 1;
1079 if ($category eq '1') {
1080 $category = 'preferred';
1081 } elsif ($category eq '4') {
1082 $category = 'seefrom';
1083 } elsif ($category eq '5') {
1084 $category = 'seealso';
1087 if ($field->subfield('w')) {
1088 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1092 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1093 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1096 $summary{mainentry} = $authorized[0]->{heading};
1097 $summary{mainmainentry} = $authorized[0]->{hemain};
1098 $summary{authorized} = \@authorized;
1099 $summary{notes} = \@notes;
1100 $summary{seefrom} = \@seefrom;
1101 $summary{seealso} = \@seealso;
1102 $summary{otherscript} = \@otherscript;
1106 =head2 GetAuthorizedHeading
1108 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1110 Takes a MARC::Record object describing an authority record or an authid, and
1111 returns a string representation of the first authorized heading. This routine
1112 should be considered a temporary shim to ease the future migration of authority
1113 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1117 sub GetAuthorizedHeading {
1120 unless ($record = $args->{record}) {
1121 return unless $args->{authid};
1122 $record = GetAuthority($args->{authid});
1124 return unless (ref $record eq 'MARC::Record');
1125 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1126 # construct UNIMARC summary, that is quite different from MARC21 one
1128 foreach my $field ($record->field('2..')) {
1129 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1132 foreach my $field ($record->field('1..')) {
1133 my $tag = $field->tag();
1134 next if "152" eq $tag;
1135 # FIXME - 152 is not a good tag to use
1136 # in MARC21 -- purely local tags really ought to be
1138 if ($tag eq '100') {
1139 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1140 } elsif ($tag eq '110') {
1141 return $field->as_string('abcdefghklmnoprstvxyz68');
1142 } elsif ($tag eq '111') {
1143 return $field->as_string('acdefghklnpqstvxyz68');
1144 } elsif ($tag eq '130') {
1145 return $field->as_string('adfghklmnoprstvxyz68');
1146 } elsif ($tag eq '148') {
1147 return $field->as_string('abvxyz68');
1148 } elsif ($tag eq '150') {
1149 return $field->as_string('abvxyz68');
1150 } elsif ($tag eq '151') {
1151 return $field->as_string('avxyz68');
1152 } elsif ($tag eq '155') {
1153 return $field->as_string('abvxyz68');
1154 } elsif ($tag eq '180') {
1155 return $field->as_string('vxyz68');
1156 } elsif ($tag eq '181') {
1157 return $field->as_string('vxyz68');
1158 } elsif ($tag eq '182') {
1159 return $field->as_string('vxyz68');
1160 } elsif ($tag eq '185') {
1161 return $field->as_string('vxyz68');
1163 return $field->as_string();
1170 =head2 BuildAuthHierarchies
1172 $text= &BuildAuthHierarchies( $authid, $force)
1174 return text containing trees for hierarchies
1175 for them to be stored in auth_header
1178 122,1314,2452;1324,2342,3,2452
1182 sub BuildAuthHierarchies{
1183 my $authid = shift @_;
1184 # warn "authid : $authid";
1185 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1187 my $dbh=C4::Context->dbh;
1189 my $data = GetHeaderAuthority($authid);
1190 if ($data->{'authtrees'} and not $force){
1191 return $data->{'authtrees'};
1192 # } elsif ($data->{'authtrees'}){
1193 # $hierarchies=$data->{'authtrees'};
1195 my $record = GetAuthority($authid);
1197 return unless $record;
1198 foreach my $field ($record->field('5..')){
1201 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1202 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1204 my $subfauthid=_get_authid_subfield($field) || '';
1205 next if ($subfauthid eq $authid);
1206 my $parentrecord = GetAuthority($subfauthid);
1207 next unless $parentrecord;
1208 my $localresult=$hierarchies;
1210 $trees = BuildAuthHierarchies($subfauthid);
1213 @trees = split(/;/,$trees);
1215 push @trees, $trees;
1220 @globalresult = (@globalresult,@trees);
1223 $hierarchies=join(";",@globalresult);
1225 #Unless there is no ancestor, I am alone.
1226 $hierarchies="$authid" unless ($hierarchies);
1228 AddAuthorityTrees($authid,$hierarchies);
1229 return $hierarchies;
1232 =head2 BuildAuthHierarchy
1234 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1236 return a hashref in order to display hierarchy for record and final Authid $authid
1247 sub BuildAuthHierarchy{
1248 my $record = shift @_;
1249 my $class = shift @_;
1250 my $authid_constructed = shift @_;
1251 return unless ($record && $record->field('001'));
1252 my $authid=$record->field('001')->data();
1254 my $parents=""; my $children="";
1255 my (@loopparents,@loopchildren);
1256 my $marcflavour = C4::Context->preference('marcflavour');
1257 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1258 foreach my $field ($record->field('5..')){
1259 my $subfauthid=_get_authid_subfield($field);
1260 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1261 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1262 if ($relationship eq 'h'){
1263 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1265 elsif ($relationship eq 'g'){
1266 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1268 # brothers could get in there with an else
1271 $cell{"parents"}=\@loopparents;
1272 $cell{"children"}=\@loopchildren;
1273 $cell{"class"}=$class;
1274 $cell{"authid"}=$authid;
1275 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1276 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1280 =head2 BuildAuthHierarchyBranch
1282 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1284 Return a data structure representing an authority hierarchy
1285 given a list of authorities representing a single branch in
1286 an authority hierarchy tree. $authid is the current node in
1287 the tree (which may or may not be somewhere in the middle).
1288 $cnt represents the level of the upper-most item, and is only
1289 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1290 don't ever pass in anything but zero to it).
1294 sub BuildAuthHierarchyBranch {
1295 my ($tree, $authid, $cnt) = @_;
1297 my $elementdata = GetAuthority(shift @$tree);
1298 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1299 if (scalar @$tree > 0) {
1300 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1301 my $nextAuthid = $nextBranch->{authid};
1303 # If we already have the next branch listed as a child, let's
1304 # replace the old listing with the new one. If not, we will add
1305 # the branch at the end.
1306 foreach my $cell (@{$branch->{children}}) {
1307 if ($cell->{authid} eq $nextAuthid) {
1308 $cell = $nextBranch;
1313 push @{$branch->{children}}, $nextBranch unless $found;
1318 =head2 GenerateHierarchy
1320 $hierarchy = &GenerateHierarchy($authid);
1322 Return an arrayref holding one or more "trees" representing
1323 authority hierarchies.
1327 sub GenerateHierarchy {
1329 my $trees = BuildAuthHierarchies($authid);
1330 my @trees = split /;/,$trees ;
1331 push @trees,$trees unless (@trees);
1332 my @loophierarchies;
1333 foreach my $tree (@trees){
1334 my @tree=split /,/,$tree;
1335 push @tree, $tree unless (@tree);
1336 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1337 push @loophierarchies, [ $branch ];
1339 return \@loophierarchies;
1342 sub _get_authid_subfield{
1344 return $field->subfield('9')||$field->subfield('3');
1347 =head2 GetHeaderAuthority
1349 $ref= &GetHeaderAuthority( $authid)
1351 return a hashref in order auth_header table data
1355 sub GetHeaderAuthority{
1356 my $authid = shift @_;
1357 my $sql= "SELECT * from auth_header WHERE authid = ?";
1358 my $dbh=C4::Context->dbh;
1359 my $rq= $dbh->prepare($sql);
1360 $rq->execute($authid);
1361 my $data= $rq->fetchrow_hashref;
1365 =head2 AddAuthorityTrees
1367 $ref= &AddAuthorityTrees( $authid, $trees)
1369 return success or failure
1373 sub AddAuthorityTrees{
1374 my $authid = shift @_;
1375 my $trees = shift @_;
1376 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1377 my $dbh=C4::Context->dbh;
1378 my $rq= $dbh->prepare($sql);
1379 return $rq->execute($trees,$authid);
1385 mergefrom => $mergefrom,
1386 [ MARCfrom => $MARCfrom, ]
1387 [ mergeto => $mergeto, ]
1388 [ MARCto => $MARCto, ]
1389 [ biblionumbers => [ $a, $b, $c ], ]
1390 [ override_limit => 1, ]
1393 Merge biblios linked to authority $mergefrom (mandatory parameter).
1394 If $mergeto equals mergefrom, the linked biblio field is updated.
1395 If $mergeto is different, the biblio field will be linked to $mergeto.
1396 If $mergeto is missing, the biblio field is deleted.
1398 MARCfrom is used to determine if a cleared subfield in the authority record
1399 should be removed from a biblio. MARCto is used to populate the biblio
1400 record with the updated values; if you do not pass it, the biblio field
1401 will be deleted (same as missing mergeto).
1403 Normally all biblio records linked to $mergefrom, will be considered. But
1404 you can pass specific numbers via the biblionumbers parameter.
1406 The parameter override_limit is used by the cron job to force larger
1409 Note: Although $mergefrom and $mergeto will normally be of the same
1410 authority type, merge also supports moving to another authority type.
1415 my ( $params ) = @_;
1416 my $mergefrom = $params->{mergefrom} || return;
1417 my $MARCfrom = $params->{MARCfrom};
1418 my $mergeto = $params->{mergeto};
1419 my $MARCto = $params->{MARCto};
1420 my $override_limit = $params->{override_limit};
1422 # If we do not have biblionumbers, we get all linked biblios if the
1423 # number of linked records does not exceed the limit UNLESS we override.
1425 if( $params->{biblionumbers} ) {
1426 @biblionumbers = @{ $params->{biblionumbers} };
1427 } elsif( $override_limit ) {
1428 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1429 } else { # now first check number of linked records
1430 my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1431 my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1432 if( $hits > 0 && $hits <= $max ) {
1433 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1434 } elsif( $hits > $max ) { #postpone this merge to the cron job
1435 Koha::Authority::MergeRequest->new({
1436 authid => $mergefrom,
1437 oldrecord => $MARCfrom,
1438 authid_new => $mergeto,
1442 return 0 if !@biblionumbers;
1444 # Search authtypes and reporting tags
1445 my $authfrom = Koha::Authorities->find($mergefrom);
1446 my $authto = Koha::Authorities->find($mergeto);
1447 my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1448 my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1449 my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1450 my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1453 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1454 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1455 # is empty, make sure that $9 and $a remain (instead of clearing the
1456 # reference) in order to allow for data recovery.
1457 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1458 if( $MARCto && $authtypeto && !@record_to ) {
1459 push @record_to, [ 'a', ' ' ]; # do not remove the space
1463 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1464 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1465 # 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
1466 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1467 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1468 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1471 # Get all candidate tags for the change
1472 # (This will reduce the search scope in marc records).
1473 # For a deleted authority record, we scan all auth controlled fields
1474 my $dbh = C4::Context->dbh;
1475 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1476 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<>''" );
1478 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1479 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1482 my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1483 my $skip_subfields = $overwrite
1484 # This hash contains all subfields from the authority report fields
1485 # Including $MARCfrom as well as $MARCto
1486 # We only need it in loose merge mode; replaces the former $exclude
1488 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1489 # And we need to add $9 in order not to duplicate
1490 $skip_subfields->{9} = 1 if !$overwrite;
1492 my $counteditedbiblio = 0;
1493 foreach my $biblionumber ( @biblionumbers ) {
1494 my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1495 next if !$marcrecord;
1497 foreach my $tagfield (@$tags_using_authtype) {
1498 my $countfrom = 0; # used in strict mode to remove duplicates
1499 foreach my $field ( $marcrecord->field($tagfield) ) {
1500 my $auth_number = $field->subfield("9"); # link to authority
1501 my $tag = $field->tag();
1502 next if !defined($auth_number) || $auth_number ne $mergefrom;
1504 if ( !$mergeto || !@record_to ||
1505 ( $overwrite && $countfrom > 1 ) ) {
1506 # !mergeto or !record_to indicates a delete
1507 # Other condition: remove this duplicate in strict mode
1508 $marcrecord->delete_field($field);
1512 my $newtag = $tags_new && @$tags_new
1513 ? _merge_newtag( $tag, $tags_new )
1515 my $field_to = MARC::Field->new(
1517 $field->indicator(1),
1518 $field->indicator(2),
1521 foreach my $subfield ( grep { $_->[0] ne '9' } @record_to ) {
1522 $field_to->add_subfields( $subfield->[0] => $subfield->[1] );
1524 if ( !$overwrite ) {
1525 # add subfields back in loose mode, check skip_subfields
1526 foreach my $subfield ( $field->subfields ) {
1527 next if $skip_subfields->{ $subfield->[0] };
1528 $field_to->add_subfields( $subfield->[0], $subfield->[1] );
1531 if ($tags_new && @$tags_new) {
1532 $marcrecord->delete_field($field);
1533 append_fields_ordered( $marcrecord, $field_to );
1535 $field->replace_with($field_to);
1541 ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1542 $counteditedbiblio++;
1544 return $counteditedbiblio;
1548 # Routine is only called for an (exceptional) authtypecode change
1549 # Fixes old behavior of returning the first tag found
1550 my ( $oldtag, $new_tags ) = @_;
1552 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1553 my $prefix = substr( $oldtag, 0, 1 );
1554 my $guess = $prefix . substr( $new_tags->[0], -2 );
1555 if( grep { $_ eq $guess } @$new_tags ) {
1558 # Otherwise return one from the same block e.g. 6XX for 650
1559 # If not there too, fall back to first new tag (old behavior!)
1560 my @same_block = grep { /^$prefix/ } @$new_tags;
1561 return @same_block ? $same_block[0] : $new_tags->[0];
1564 sub append_fields_ordered {
1565 # while we lack this function in MARC::Record
1566 # we do not want insert_fields_ordered since it inserts before
1567 my ( $record, $field ) = @_;
1568 if( my @flds = $record->field( $field->tag ) ) {
1569 $record->insert_fields_after( pop @flds, $field );
1570 } else { # now fallback to insert_fields_ordered
1571 $record->insert_fields_ordered( $field );
1575 =head2 get_auth_type_location
1577 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1579 Get the tag and subfield used to store the heading type
1580 for indexing purposes. The C<$auth_type> parameter is
1581 optional; if it is not supplied, assume ''.
1583 This routine searches the MARC authority framework
1584 for the tag and subfield whose kohafield is
1585 C<auth_header.authtypecode>; if no such field is
1586 defined in the framework, default to the hardcoded value
1587 specific to the MARC format.
1591 sub get_auth_type_location {
1592 my $auth_type_code = @_ ? shift : '';
1594 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1595 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1596 return ($tag, $subfield);
1598 if (C4::Context->preference('marcflavour') eq "MARC21") {
1599 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1601 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1606 END { } # module clean-up code here (global destructor)
1613 Koha Development Team <http://koha-community.org/>
1615 Paul POULAIN paul.poulain@free.fr