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 if ( $userenv && $userenv->{'branch'} ) {
612 $library = Koha::Libraries->find( $userenv->{'branch'} );
614 if (!$record->leader) {
615 $record->leader($leader);
617 if (!$record->field('003')) {
618 $record->insert_fields_ordered(
619 MARC::Field->new('003', $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode'))
622 my $date=POSIX::strftime("%y%m%d",localtime);
623 if (!$record->field('008')) {
624 # Get a valid default value for field 008
625 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
626 if(!$default_008 or length($default_008)<34) {
627 $default_008 = '|| aca||aabn | a|a d';
630 $default_008 = substr($default_008,0,34);
633 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
635 if (!$record->field('040')) {
636 $record->insert_fields_ordered(
637 MARC::Field->new('040','','',
638 'a' => $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode'),
639 'c' => $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode')
645 if ($format eq "UNIMARCAUTH") {
646 $record->leader(" nx j22 ") unless ($record->leader());
647 my $date=POSIX::strftime("%Y%m%d",localtime);
648 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
649 if (my $string=$record->subfield('100',"a")){
650 $string=~s/fre50/frey50/;
651 $record->field('100')->update('a'=>$string);
653 elsif ($record->field('100')){
654 $record->field('100')->update('a'=>$date.$defaultfield100);
656 $record->append_fields(
657 MARC::Field->new('100',' ',' '
658 ,'a'=>$date.$defaultfield100)
662 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
663 if (!$authid and $format eq "MARC21") {
664 # only need to do this fix when modifying an existing authority
665 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
667 if (my $field=$record->field($auth_type_tag)){
668 $field->update($auth_type_subfield=>$authtypecode);
671 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
674 # Save record into auth_header, update 001
676 # Save a blank record, get authid
677 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
678 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
679 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
681 # Insert/update the recordID in MARC record
682 $record->delete_field( $record->field('001') );
683 $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
685 $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;
686 ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
693 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
695 Deletes $authid and calls merge to cleanup linked biblio records.
696 Parameter skip_merge is used in authorities/merge.pl. You should normally not
703 my $authid = $params->{authid} || return;
704 my $skip_merge = $params->{skip_merge};
705 my $dbh = C4::Context->dbh;
706 merge({ mergefrom => $authid }) if !$skip_merge;
707 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
708 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
709 ModZebra( $authid, "recordDelete", "authorityserver", undef);
714 $authid= &ModAuthority($authid,$record,$authtypecode)
716 Modifies authority record, optionally updates attached biblios.
721 my ( $authid, $record, $authtypecode ) = @_;
722 my $oldrecord = GetAuthority($authid);
723 #Now rewrite the $record to table with an add
724 $authid = AddAuthority($record, $authid, $authtypecode);
725 merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
726 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
730 =head2 GetAuthorityXML
732 $marcxml= &GetAuthorityXML( $authid)
734 returns xml form of record $authid
738 sub GetAuthorityXML {
739 # Returns MARC::XML of the authority passed in parameter.
741 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
742 my $dbh=C4::Context->dbh;
743 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
744 $sth->execute($authid);
745 my ($marcxml)=$sth->fetchrow;
749 # for MARC21, call GetAuthority instead of
750 # getting the XML directly since we may
751 # need to fix up the location of the authority
752 # code -- note that this is reasonably safe
753 # because GetAuthorityXML is used only by the
754 # indexing processes like zebraqueue_start.pl
755 my $record = GetAuthority($authid);
756 return $record->as_xml_record('MARC21');
762 $record= &GetAuthority( $authid)
764 Returns MARC::Record of the authority passed in parameter.
770 my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
771 return unless $authority;
772 return ($authority->record);
775 =head2 FindDuplicateAuthority
777 $record= &FindDuplicateAuthority( $record, $authtypecode)
779 return $authid,Summary if duplicate is found.
781 Comments : an improvement would be to return All the records that match.
785 sub FindDuplicateAuthority {
787 my ($record,$authtypecode)=@_;
788 # warn "IN for ".$record->as_formatted;
789 my $dbh = C4::Context->dbh;
790 # warn "".$record->as_formatted;
791 my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
792 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
793 # build a request for SearchAuthorities
795 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
802 my $query='at:'.$authtypecode.' ';
803 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
804 if ($record->field($auth_tag_to_report)) {
805 foreach ($record->field($auth_tag_to_report)->subfields()) {
806 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
809 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
810 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1 );
811 # there is at least 1 result => return the 1st one
812 if (!defined $error && @{$results} ) {
813 my $marcrecord = C4::Search::new_record_from_zebra(
817 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
819 # no result, returns nothing
825 $summary= &BuildSummary( $record, $authid, $authtypecode)
827 Returns a hashref with a summary of the specified record.
829 Comment : authtypecode can be inferred from both record and authid.
830 Moreover, authid can also be inferred from $record.
831 Would it be interesting to delete those things.
836 ## give this a Marc record to return summary
837 my ($record,$authid,$authtypecode)=@_;
838 my $dbh=C4::Context->dbh;
840 my $summary_template;
841 # handle $authtypecode is NULL or eq ""
843 my $authref = Koha::Authority::Types->find($authtypecode);
845 $summary{authtypecode} = $authref->authtypecode;
846 $summary{type} = $authref->authtypetext;
847 $summary_template = $authref->summary;
848 # for MARC21, the authority type summary displays a label meant for
850 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
851 $summary{label} = $authref->summary;
853 $summary{summary} = $authref->summary;
857 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
858 my %marc21controlrefs = ( 'a' => 'earlier',
864 'n' => 'notapplicable',
868 my %unimarc_relation_from_code = (
874 $thesaurus{'1'}="Peuples";
875 $thesaurus{'2'}="Anthroponymes";
876 $thesaurus{'3'}="Oeuvres";
877 $thesaurus{'4'}="Chronologie";
878 $thesaurus{'5'}="Lieux";
879 $thesaurus{'6'}="Sujets";
882 # if the library has a summary defined, use it. Otherwise, build a standard one
883 # FIXME - it appears that the summary field in the authority frameworks
884 # can work as a display template. However, this doesn't
885 # suit the MARC21 version, so for now the "templating"
886 # feature will be enabled only for UNIMARC for backwards
888 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
889 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
890 my (@textbefore, @tag, @subtag, @textafter);
891 for(my $i = 0; $i < scalar @matches; $i++){
892 push @textbefore, $matches[$i] if($i%4 == 0);
893 push @tag, $matches[$i] if($i%4 == 1);
894 push @subtag, $matches[$i] if($i%4 == 2);
895 push @textafter, $matches[$i] if($i%4 == 3);
897 for(my $i = scalar @tag; $i >= 0; $i--){
898 my $textbefore = $textbefore[$i] || '';
899 my $tag = $tag[$i] || '';
900 my $subtag = $subtag[$i] || '';
901 my $textafter = $textafter[$i] || '';
903 my $field = $record->field($tag);
907 $value = $textbefore . $field->data() . $textafter;
910 my @subfields = $field->subfield($subtag);
912 $value = $textbefore . join (" - ", @subfields) . $textafter;
916 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
918 $summary{summary} =~ s/\\n/<br \/>/g;
925 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
926 # construct UNIMARC summary, that is quite different from MARC21 one
928 foreach my $field ($record->field('2..')) {
930 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
931 hemain => ( $field->subfield('a') // undef ),
932 field => $field->tag(),
936 foreach my $field ($record->field('3..')) {
937 push @notes, { note => $field->subfield('a'), field => $field->tag() };
939 foreach my $field ($record->field('4..')) {
940 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
942 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
943 hemain => ( $field->subfield('a') // undef ),
945 field => $field->tag(),
951 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
952 my $heading = $_->as_string('abcdefgjxyz');
957 hemain => ( $_->subfield('a') // undef ),
959 authid => ( $_->subfield('9') // undef ),
961 } $record->field('5..');
964 @otherscript = map { {
965 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
966 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
969 } } $record->field('7..');
972 # construct MARC21 summary
973 # FIXME - looping over 1XX is questionable
974 # since MARC21 authority should have only one 1XX
975 my $subfields_to_report;
976 foreach my $field ($record->field('1..')) {
977 my $tag = $field->tag();
978 next if "152" eq $tag;
979 # FIXME - 152 is not a good tag to use
980 # in MARC21 -- purely local tags really ought to be
983 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
984 } elsif ($tag eq '110') {
985 $subfields_to_report = 'abcdefghklmnoprstvxyz';
986 } elsif ($tag eq '111') {
987 $subfields_to_report = 'acdefghklnpqstvxyz';
988 } elsif ($tag eq '130') {
989 $subfields_to_report = 'adfghklmnoprstvxyz';
990 } elsif ($tag eq '148') {
991 $subfields_to_report = 'abvxyz';
992 } elsif ($tag eq '150') {
993 $subfields_to_report = 'abvxyz';
994 } elsif ($tag eq '151') {
995 $subfields_to_report = 'avxyz';
996 } elsif ($tag eq '155') {
997 $subfields_to_report = 'abvxyz';
998 } elsif ($tag eq '180') {
999 $subfields_to_report = 'vxyz';
1000 } elsif ($tag eq '181') {
1001 $subfields_to_report = 'vxyz';
1002 } elsif ($tag eq '182') {
1003 $subfields_to_report = 'vxyz';
1004 } elsif ($tag eq '185') {
1005 $subfields_to_report = 'vxyz';
1007 if ($subfields_to_report) {
1009 heading => $field->as_string($subfields_to_report),
1010 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1015 heading => $field->as_string(),
1016 hemain => ( $field->subfield( 'a' ) // undef ),
1021 foreach my $field ($record->field('4..')) { #See From
1022 my $type = 'seefrom';
1023 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1024 if ($type eq 'notapplicable') {
1025 $type = substr $field->subfield('w'), 2, 1;
1026 $type = 'earlier' if $type && $type ne 'n';
1028 if ($type eq 'subfi') {
1030 heading => $field->as_string($marc21subfields),
1031 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1032 type => ($field->subfield('i') || ''),
1033 field => $field->tag(),
1037 heading => $field->as_string($marc21subfields),
1038 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1040 field => $field->tag(),
1044 foreach my $field ($record->field('5..')) { #See Also
1045 my $type = 'seealso';
1046 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1047 if ($type eq 'notapplicable') {
1048 $type = substr $field->subfield('w'), 2, 1;
1049 $type = 'earlier' if $type && $type ne 'n';
1051 if ($type eq 'subfi') {
1053 heading => $field->as_string($marc21subfields),
1054 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1055 type => $field->subfield('i'),
1056 field => $field->tag(),
1057 search => $field->as_string($marc21subfields) || '',
1058 authid => $field->subfield('9') || ''
1062 heading => $field->as_string($marc21subfields),
1063 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1065 field => $field->tag(),
1066 search => $field->as_string($marc21subfields) || '',
1067 authid => $field->subfield('9') || ''
1071 foreach my $field ($record->field('6..')) {
1072 push @notes, { note => $field->as_string(), field => $field->tag() };
1074 foreach my $field ($record->field('880')) {
1075 my $linkage = $field->subfield('6');
1076 my $category = substr $linkage, 0, 1;
1077 if ($category eq '1') {
1078 $category = 'preferred';
1079 } elsif ($category eq '4') {
1080 $category = 'seefrom';
1081 } elsif ($category eq '5') {
1082 $category = 'seealso';
1085 if ($field->subfield('w')) {
1086 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1090 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1091 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1094 $summary{mainentry} = $authorized[0]->{heading};
1095 $summary{mainmainentry} = $authorized[0]->{hemain};
1096 $summary{authorized} = \@authorized;
1097 $summary{notes} = \@notes;
1098 $summary{seefrom} = \@seefrom;
1099 $summary{seealso} = \@seealso;
1100 $summary{otherscript} = \@otherscript;
1104 =head2 GetAuthorizedHeading
1106 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1108 Takes a MARC::Record object describing an authority record or an authid, and
1109 returns a string representation of the first authorized heading. This routine
1110 should be considered a temporary shim to ease the future migration of authority
1111 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1115 sub GetAuthorizedHeading {
1118 unless ($record = $args->{record}) {
1119 return unless $args->{authid};
1120 $record = GetAuthority($args->{authid});
1122 return unless (ref $record eq 'MARC::Record');
1123 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1124 # construct UNIMARC summary, that is quite different from MARC21 one
1126 foreach my $field ($record->field('2..')) {
1127 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1130 foreach my $field ($record->field('1..')) {
1131 my $tag = $field->tag();
1132 next if "152" eq $tag;
1133 # FIXME - 152 is not a good tag to use
1134 # in MARC21 -- purely local tags really ought to be
1136 if ($tag eq '100') {
1137 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1138 } elsif ($tag eq '110') {
1139 return $field->as_string('abcdefghklmnoprstvxyz68');
1140 } elsif ($tag eq '111') {
1141 return $field->as_string('acdefghklnpqstvxyz68');
1142 } elsif ($tag eq '130') {
1143 return $field->as_string('adfghklmnoprstvxyz68');
1144 } elsif ($tag eq '148') {
1145 return $field->as_string('abvxyz68');
1146 } elsif ($tag eq '150') {
1147 return $field->as_string('abvxyz68');
1148 } elsif ($tag eq '151') {
1149 return $field->as_string('avxyz68');
1150 } elsif ($tag eq '155') {
1151 return $field->as_string('abvxyz68');
1152 } elsif ($tag eq '180') {
1153 return $field->as_string('vxyz68');
1154 } elsif ($tag eq '181') {
1155 return $field->as_string('vxyz68');
1156 } elsif ($tag eq '182') {
1157 return $field->as_string('vxyz68');
1158 } elsif ($tag eq '185') {
1159 return $field->as_string('vxyz68');
1161 return $field->as_string();
1168 =head2 BuildAuthHierarchies
1170 $text= &BuildAuthHierarchies( $authid, $force)
1172 return text containing trees for hierarchies
1173 for them to be stored in auth_header
1176 122,1314,2452;1324,2342,3,2452
1180 sub BuildAuthHierarchies{
1181 my $authid = shift @_;
1182 # warn "authid : $authid";
1183 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1185 my $dbh=C4::Context->dbh;
1187 my $data = GetHeaderAuthority($authid);
1188 if ($data->{'authtrees'} and not $force){
1189 return $data->{'authtrees'};
1190 # } elsif ($data->{'authtrees'}){
1191 # $hierarchies=$data->{'authtrees'};
1193 my $record = GetAuthority($authid);
1195 return unless $record;
1196 foreach my $field ($record->field('5..')){
1199 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1200 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1202 my $subfauthid=_get_authid_subfield($field) || '';
1203 next if ($subfauthid eq $authid);
1204 my $parentrecord = GetAuthority($subfauthid);
1205 next unless $parentrecord;
1206 my $localresult=$hierarchies;
1208 $trees = BuildAuthHierarchies($subfauthid);
1211 @trees = split(/;/,$trees);
1213 push @trees, $trees;
1218 @globalresult = (@globalresult,@trees);
1221 $hierarchies=join(";",@globalresult);
1223 #Unless there is no ancestor, I am alone.
1224 $hierarchies="$authid" unless ($hierarchies);
1226 AddAuthorityTrees($authid,$hierarchies);
1227 return $hierarchies;
1230 =head2 BuildAuthHierarchy
1232 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1234 return a hashref in order to display hierarchy for record and final Authid $authid
1245 sub BuildAuthHierarchy{
1246 my $record = shift @_;
1247 my $class = shift @_;
1248 my $authid_constructed = shift @_;
1249 return unless ($record && $record->field('001'));
1250 my $authid=$record->field('001')->data();
1252 my $parents=""; my $children="";
1253 my (@loopparents,@loopchildren);
1254 my $marcflavour = C4::Context->preference('marcflavour');
1255 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1256 foreach my $field ($record->field('5..')){
1257 my $subfauthid=_get_authid_subfield($field);
1258 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1259 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1260 if ($relationship eq 'h'){
1261 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1263 elsif ($relationship eq 'g'){
1264 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1266 # brothers could get in there with an else
1269 $cell{"parents"}=\@loopparents;
1270 $cell{"children"}=\@loopchildren;
1271 $cell{"class"}=$class;
1272 $cell{"authid"}=$authid;
1273 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1274 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1278 =head2 BuildAuthHierarchyBranch
1280 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1282 Return a data structure representing an authority hierarchy
1283 given a list of authorities representing a single branch in
1284 an authority hierarchy tree. $authid is the current node in
1285 the tree (which may or may not be somewhere in the middle).
1286 $cnt represents the level of the upper-most item, and is only
1287 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1288 don't ever pass in anything but zero to it).
1292 sub BuildAuthHierarchyBranch {
1293 my ($tree, $authid, $cnt) = @_;
1295 my $elementdata = GetAuthority(shift @$tree);
1296 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1297 if (scalar @$tree > 0) {
1298 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1299 my $nextAuthid = $nextBranch->{authid};
1301 # If we already have the next branch listed as a child, let's
1302 # replace the old listing with the new one. If not, we will add
1303 # the branch at the end.
1304 foreach my $cell (@{$branch->{children}}) {
1305 if ($cell->{authid} eq $nextAuthid) {
1306 $cell = $nextBranch;
1311 push @{$branch->{children}}, $nextBranch unless $found;
1316 =head2 GenerateHierarchy
1318 $hierarchy = &GenerateHierarchy($authid);
1320 Return an arrayref holding one or more "trees" representing
1321 authority hierarchies.
1325 sub GenerateHierarchy {
1327 my $trees = BuildAuthHierarchies($authid);
1328 my @trees = split /;/,$trees ;
1329 push @trees,$trees unless (@trees);
1330 my @loophierarchies;
1331 foreach my $tree (@trees){
1332 my @tree=split /,/,$tree;
1333 push @tree, $tree unless (@tree);
1334 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1335 push @loophierarchies, [ $branch ];
1337 return \@loophierarchies;
1340 sub _get_authid_subfield{
1342 return $field->subfield('9')||$field->subfield('3');
1345 =head2 GetHeaderAuthority
1347 $ref= &GetHeaderAuthority( $authid)
1349 return a hashref in order auth_header table data
1353 sub GetHeaderAuthority{
1354 my $authid = shift @_;
1355 my $sql= "SELECT * from auth_header WHERE authid = ?";
1356 my $dbh=C4::Context->dbh;
1357 my $rq= $dbh->prepare($sql);
1358 $rq->execute($authid);
1359 my $data= $rq->fetchrow_hashref;
1363 =head2 AddAuthorityTrees
1365 $ref= &AddAuthorityTrees( $authid, $trees)
1367 return success or failure
1371 sub AddAuthorityTrees{
1372 my $authid = shift @_;
1373 my $trees = shift @_;
1374 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1375 my $dbh=C4::Context->dbh;
1376 my $rq= $dbh->prepare($sql);
1377 return $rq->execute($trees,$authid);
1383 mergefrom => $mergefrom,
1384 [ MARCfrom => $MARCfrom, ]
1385 [ mergeto => $mergeto, ]
1386 [ MARCto => $MARCto, ]
1387 [ biblionumbers => [ $a, $b, $c ], ]
1388 [ override_limit => 1, ]
1391 Merge biblios linked to authority $mergefrom (mandatory parameter).
1392 If $mergeto equals mergefrom, the linked biblio field is updated.
1393 If $mergeto is different, the biblio field will be linked to $mergeto.
1394 If $mergeto is missing, the biblio field is deleted.
1396 MARCfrom is used to determine if a cleared subfield in the authority record
1397 should be removed from a biblio. MARCto is used to populate the biblio
1398 record with the updated values; if you do not pass it, the biblio field
1399 will be deleted (same as missing mergeto).
1401 Normally all biblio records linked to $mergefrom, will be considered. But
1402 you can pass specific numbers via the biblionumbers parameter.
1404 The parameter override_limit is used by the cron job to force larger
1407 Note: Although $mergefrom and $mergeto will normally be of the same
1408 authority type, merge also supports moving to another authority type.
1413 my ( $params ) = @_;
1414 my $mergefrom = $params->{mergefrom} || return;
1415 my $MARCfrom = $params->{MARCfrom};
1416 my $mergeto = $params->{mergeto};
1417 my $MARCto = $params->{MARCto};
1418 my $override_limit = $params->{override_limit};
1420 # If we do not have biblionumbers, we get all linked biblios if the
1421 # number of linked records does not exceed the limit UNLESS we override.
1423 if( $params->{biblionumbers} ) {
1424 @biblionumbers = @{ $params->{biblionumbers} };
1425 } elsif( $override_limit ) {
1426 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1427 } else { # now first check number of linked records
1428 my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1429 my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1430 if( $hits > 0 && $hits <= $max ) {
1431 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1432 } elsif( $hits > $max ) { #postpone this merge to the cron job
1433 Koha::Authority::MergeRequest->new({
1434 authid => $mergefrom,
1435 oldrecord => $MARCfrom,
1436 authid_new => $mergeto,
1440 return 0 if !@biblionumbers;
1442 # Search authtypes and reporting tags
1443 my $authfrom = Koha::Authorities->find($mergefrom);
1444 my $authto = Koha::Authorities->find($mergeto);
1445 my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1446 my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1447 my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1448 my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1451 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1452 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1453 # is empty, make sure that $9 and $a remain (instead of clearing the
1454 # reference) in order to allow for data recovery.
1455 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1456 if( $MARCto && $authtypeto && !@record_to ) {
1457 push @record_to, [ 'a', ' ' ]; # do not remove the space
1461 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1462 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1463 # 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
1464 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1465 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1466 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1469 # Get all candidate tags for the change
1470 # (This will reduce the search scope in marc records).
1471 # For a deleted authority record, we scan all auth controlled fields
1472 my $dbh = C4::Context->dbh;
1473 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1474 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<>''" );
1476 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1477 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1480 my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1481 my $skip_subfields = $overwrite
1482 # This hash contains all subfields from the authority report fields
1483 # Including $MARCfrom as well as $MARCto
1484 # We only need it in loose merge mode; replaces the former $exclude
1486 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1487 # And we need to add $9 in order not to duplicate
1488 $skip_subfields->{9} = 1 if !$overwrite;
1490 my $counteditedbiblio = 0;
1491 foreach my $biblionumber ( @biblionumbers ) {
1492 my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1493 next if !$marcrecord;
1495 foreach my $tagfield (@$tags_using_authtype) {
1496 my $countfrom = 0; # used in strict mode to remove duplicates
1497 foreach my $field ( $marcrecord->field($tagfield) ) {
1498 my $auth_number = $field->subfield("9"); # link to authority
1499 my $tag = $field->tag();
1500 next if !defined($auth_number) || $auth_number ne $mergefrom;
1502 if ( !$mergeto || !@record_to ||
1503 ( $overwrite && $countfrom > 1 ) ) {
1504 # !mergeto or !record_to indicates a delete
1505 # Other condition: remove this duplicate in strict mode
1506 $marcrecord->delete_field($field);
1510 my $newtag = $tags_new && @$tags_new
1511 ? _merge_newtag( $tag, $tags_new )
1513 my $field_to = MARC::Field->new(
1515 $field->indicator(1),
1516 $field->indicator(2),
1519 foreach my $subfield ( grep { $_->[0] ne '9' } @record_to ) {
1520 $field_to->add_subfields( $subfield->[0] => $subfield->[1] );
1522 if ( !$overwrite ) {
1523 # add subfields back in loose mode, check skip_subfields
1524 foreach my $subfield ( $field->subfields ) {
1525 next if $skip_subfields->{ $subfield->[0] };
1526 $field_to->add_subfields( $subfield->[0], $subfield->[1] );
1529 if ($tags_new && @$tags_new) {
1530 $marcrecord->delete_field($field);
1531 append_fields_ordered( $marcrecord, $field_to );
1533 $field->replace_with($field_to);
1539 ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1540 $counteditedbiblio++;
1542 return $counteditedbiblio;
1546 # Routine is only called for an (exceptional) authtypecode change
1547 # Fixes old behavior of returning the first tag found
1548 my ( $oldtag, $new_tags ) = @_;
1550 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1551 my $prefix = substr( $oldtag, 0, 1 );
1552 my $guess = $prefix . substr( $new_tags->[0], -2 );
1553 if( grep { $_ eq $guess } @$new_tags ) {
1556 # Otherwise return one from the same block e.g. 6XX for 650
1557 # If not there too, fall back to first new tag (old behavior!)
1558 my @same_block = grep { /^$prefix/ } @$new_tags;
1559 return @same_block ? $same_block[0] : $new_tags->[0];
1562 sub append_fields_ordered {
1563 # while we lack this function in MARC::Record
1564 # we do not want insert_fields_ordered since it inserts before
1565 my ( $record, $field ) = @_;
1566 if( my @flds = $record->field( $field->tag ) ) {
1567 $record->insert_fields_after( pop @flds, $field );
1568 } else { # now fallback to insert_fields_ordered
1569 $record->insert_fields_ordered( $field );
1573 =head2 get_auth_type_location
1575 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1577 Get the tag and subfield used to store the heading type
1578 for indexing purposes. The C<$auth_type> parameter is
1579 optional; if it is not supplied, assume ''.
1581 This routine searches the MARC authority framework
1582 for the tag and subfield whose kohafield is
1583 C<auth_header.authtypecode>; if no such field is
1584 defined in the framework, default to the hardcoded value
1585 specific to the MARC format.
1589 sub get_auth_type_location {
1590 my $auth_type_code = @_ ? shift : '';
1592 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1593 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1594 return ($tag, $subfield);
1596 if (C4::Context->preference('marcflavour') eq "MARC21") {
1597 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1599 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1604 END { } # module clean-up code here (global destructor)
1611 Koha Development Team <http://koha-community.org/>
1613 Paul POULAIN paul.poulain@free.fr