1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
29 use Koha::MetadataRecord::Authority;
30 use Koha::Authorities;
31 use Koha::Authority::MergeRequest;
32 use Koha::Authority::Types;
34 use Koha::SearchEngine;
35 use Koha::SearchEngine::Search;
37 use vars qw(@ISA @EXPORT);
45 &GetAuthMARCFromKohaField
63 &FindDuplicateAuthority
75 =head2 GetAuthMARCFromKohaField
77 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
79 returns tag and subfield linked to kohafield
82 Suppose Kohafield is only linked to ONE subfield
86 sub GetAuthMARCFromKohaField {
87 #AUTHfind_marc_from_kohafield
88 my ( $kohafield,$authtypecode ) = @_;
89 my $dbh=C4::Context->dbh;
90 return 0, 0 unless $kohafield;
91 $authtypecode="" unless $authtypecode;
92 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
93 $sth->execute($kohafield,$authtypecode);
94 my ($tagfield,$tagsubfield) = $sth->fetchrow;
96 return ($tagfield,$tagsubfield);
99 =head2 SearchAuthorities
101 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
102 $excluding, $operator, $value, $offset,$length,$authtypecode,
103 $sortby[, $skipmetadata])
105 returns ref to array result and count of results returned
109 sub SearchAuthorities {
110 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
111 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
112 my $dbh=C4::Context->dbh;
113 $sortby="" unless $sortby;
117 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
119 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
120 # the authtypecode. Then, search on $a of this tag_to_report
121 # also store main entry MARC tag, to extract it at end of search
123 ##first set the authtype search and may be multiple authorities
127 my @auths=split / /,$authtypecode ;
128 foreach my $auth (@auths){
129 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
130 push @authtypecode ,$auth;
134 while ($n>1){$query= "\@or ".$query;$n--;}
137 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
145 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
148 if ( @$tags[$i] eq "mainmainentry" ) {
149 $attr = " \@attr 1=Heading-Main ";
151 elsif ( @$tags[$i] eq "mainentry" ) {
152 $attr = " \@attr 1=Heading ";
154 elsif ( @$tags[$i] eq "match" ) {
155 $attr = " \@attr 1=Match ";
157 elsif ( @$tags[$i] eq "match-heading" ) {
158 $attr = " \@attr 1=Match-heading ";
160 elsif ( @$tags[$i] eq "see-from" ) {
161 $attr = " \@attr 1=Match-heading-see-from ";
163 elsif ( @$tags[$i] eq "thesaurus" ) {
164 $attr = " \@attr 1=Subject-heading-thesaurus ";
166 else { # Assume any if no index was specified
167 $attr = " \@attr 1=Any ";
170 else { # Assume any if no index was specified
171 $attr = " \@attr 1=Any ";
174 my $operator = @$operator[$i];
175 if ( $operator and $operator eq 'is' ) {
176 $attr .= " \@attr 4=1 \@attr 5=100 "
177 ; ##Phrase, No truncation,all of subfield field must match
179 elsif ( $operator and $operator eq "=" ) {
180 $attr .= " \@attr 4=107 "; #Number Exact match
182 elsif ( $operator and $operator eq "start" ) {
183 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
184 ; #Firstinfield Phrase, Right truncated
186 elsif ( $operator and $operator eq "exact" ) {
187 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
188 ; ##Phrase, No truncation,all of subfield field must match
191 $attr .= " \@attr 5=1 \@attr 4=6 "
192 ; ## Word list, right truncated, anywhere
193 if ( $sortby eq 'Relevance' ) {
194 $attr .= "\@attr 2=102 ";
198 s/"/\\"/g; # Escape the double-quotes in the search value
199 $attr = $attr . "\"" . @$value[$i] . "\"";
204 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
208 ##Add how many queries generated
209 if (defined $query && $query=~/\S+/){
210 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
215 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
217 if ($sortby eq 'HeadingAsc') {
218 $orderstring = '@attr 7=1 @attr 1=Heading 0';
219 } elsif ($sortby eq 'HeadingDsc') {
220 $orderstring = '@attr 7=2 @attr 1=Heading 0';
221 } elsif ($sortby eq 'AuthidAsc') {
222 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
223 } elsif ($sortby eq 'AuthidDsc') {
224 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
227 $qpquery .= ' all:all' unless $value->[0];
229 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
233 $qpquery .= " #$sortby" unless $sortby eq '';
235 $QParser->parse( $qpquery );
236 $query = $QParser->target_syntax('authorityserver');
238 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
239 $query="\@or $orderstring $query" if $orderstring;
242 $offset=0 unless $offset;
243 my $counter = $offset;
244 $length=10 unless $length;
247 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
248 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
250 $oAResult= $oAuth[0]->search($Anewq) ;
251 while (($i = ZOOM::event(\@oAuth)) != 0) {
252 my $ev = $oAuth[$i-1]->last_event();
253 last if $ev == ZOOM::Event::ZEND;
255 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
257 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
262 $nbresults=$oAResult->size();
263 my $nremains=$nbresults;
265 my @finalresult = ();
269 ##Find authid and linkid fields
270 ##we may be searching multiple authoritytypes.
271 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
272 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
273 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
274 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
276 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
277 my $rec=$oAResult->record($counter);
278 my $separator=C4::Context->preference('AuthoritySeparator');
279 my $authrecord = C4::Search::new_record_from_zebra(
284 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
289 SetUTF8Flag( $authrecord );
291 my $authid=$authrecord->field('001')->data();
293 $newline{authid} = $authid;
294 if ( !$skipmetadata ) {
295 my $auth_tag_to_report;
296 $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report
299 my $mainentry = $authrecord->field($auth_tag_to_report);
301 foreach ( $mainentry->subfields() ) {
302 $reported_tag .= '$' . $_->[0] . $_->[1];
306 my ( $thisauthtype, $thisauthtypecode );
307 if ( my $authority = Koha::Authorities->find($authid) ) {
308 $thisauthtypecode = $authority->authtypecode;
309 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
311 unless (defined $thisauthtype) {
312 $thisauthtypecode = $authtypecode;
313 $thisauthtype = Koha::Authority::Types->find($thisauthtypecode);
315 my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
317 $newline{authtype} = defined($thisauthtype) ?
318 $thisauthtype->authtypetext : '';
319 $newline{summary} = $summary;
320 $newline{even} = $counter % 2;
321 $newline{reported_tag} = $reported_tag;
324 push @finalresult, \%newline;
327 if (! $skipmetadata) {
328 for (my $z=0; $z<@finalresult; $z++){
329 my $count=CountUsage($finalresult[$z]{authid});
330 $finalresult[$z]{used}=$count;
336 $oAResult->destroy();
337 # $oAuth[0]->destroy();
339 return (\@finalresult, $nbresults);
344 $count= &CountUsage($authid)
346 counts Usage of Authid in bibliorecords.
354 $query= "an:".$authid;
355 # Should really be replaced with a real count call, this is a
357 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
358 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,1);
360 warn "Error: $err from search $query";
367 =head2 CountUsageChildren
369 $count= &CountUsageChildren($authid)
371 counts Usage of narrower terms of Authid in bibliorecords.
375 sub CountUsageChildren {
379 =head2 GuessAuthTypeCode
381 my $authtypecode = GuessAuthTypeCode($record);
383 Get the record and tries to guess the adequate authtypecode from its content.
387 sub GuessAuthTypeCode {
388 my ($record, $heading_fields) = @_;
389 return unless defined $record;
390 $heading_fields //= {
392 '100'=>{authtypecode=>'PERSO_NAME'},
393 '110'=>{authtypecode=>'CORPO_NAME'},
394 '111'=>{authtypecode=>'MEETI_NAME'},
395 '130'=>{authtypecode=>'UNIF_TITLE'},
396 '148'=>{authtypecode=>'CHRON_TERM'},
397 '150'=>{authtypecode=>'TOPIC_TERM'},
398 '151'=>{authtypecode=>'GEOGR_NAME'},
399 '155'=>{authtypecode=>'GENRE/FORM'},
400 '180'=>{authtypecode=>'GEN_SUBDIV'},
401 '181'=>{authtypecode=>'GEO_SUBDIV'},
402 '182'=>{authtypecode=>'CHRON_SUBD'},
403 '185'=>{authtypecode=>'FORM_SUBD'},
405 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
406 # 604 with embedded 700, 701, 702
407 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
408 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
409 #216 Trademark 716 [Reserved for future use]
410 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
411 #230 Title 500 4-- with embedded 500 605
412 #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
413 #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
414 #250 Topical subject 606
415 #260 Place access 620
416 #280 Form, genre or physical characteristics 608
419 # Could also be represented with :
421 #a = personal name entry
422 #b = corporate name entry
423 #c = territorial or geographical name
427 #g = collective uniform title
429 #i = name/collective uniform title
432 #l = form, genre or physical characteristics
434 '200'=>{authtypecode=>'NP'},
435 '210'=>{authtypecode=>'CO'},
436 '215'=>{authtypecode=>'SNG'},
437 '216'=>{authtypecode=>'TM'},
438 '220'=>{authtypecode=>'FAM'},
439 '230'=>{authtypecode=>'TU'},
440 '235'=>{authtypecode=>'CO_UNI_TI'},
441 '240'=>{authtypecode=>'SAUTTIT'},
442 '245'=>{authtypecode=>'NAME_COL'},
443 '250'=>{authtypecode=>'SNC'},
444 '260'=>{authtypecode=>'PA'},
445 '280'=>{authtypecode=>'GENRE/FORM'},
448 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
449 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
456 my $authtid = GuessAuthId($record);
458 Get the record and tries to guess the adequate authtypecode from its content.
464 return unless ($record && $record->field('001'));
465 # my $authtypecode=GuessAuthTypeCode($record);
466 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
467 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
468 # else {return $record->field($tag)->data}
469 return $record->field('001')->data;
474 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
476 returns a ref to hashref of authorities tag and subfield structure.
480 $tagslabel->{$tag}->{$subfield}->{'attribute'}
482 where attribute takes values in :
500 my ($forlibrarian,$authtypecode)= @_;
501 my $dbh=C4::Context->dbh;
502 $authtypecode="" unless $authtypecode;
504 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
507 # check that authority exists
508 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
509 $sth->execute($authtypecode);
510 my ($total) = $sth->fetchrow;
511 $authtypecode="" unless ($total >0);
513 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
514 FROM auth_tag_structure
519 $sth->execute($authtypecode);
520 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
522 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
523 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
524 $res->{$tag}->{tab} = " "; # XXX
525 $res->{$tag}->{mandatory} = $mandatory;
526 $res->{$tag}->{repeatable} = $repeatable;
529 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
530 FROM auth_subfield_structure
532 ORDER BY tagfield,tagsubfield"
534 $sth->execute($authtypecode);
537 my $authorised_value;
547 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
548 $mandatory, $repeatable, $authorised_value, $authtypecode,
549 $value_builder, $kohafield, $seealso, $hidden,
550 $isurl, $defaultvalue, $link )
554 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
555 $res->{$tag}->{$subfield}->{tab} = $tab;
556 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
557 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
558 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
559 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
560 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
561 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
562 $res->{$tag}->{$subfield}->{seealso} = $seealso;
563 $res->{$tag}->{$subfield}->{hidden} = $hidden;
564 $res->{$tag}->{$subfield}->{isurl} = $isurl;
565 $res->{$tag}->{$subfield}->{link} = $link;
566 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
573 $authid= &AddAuthority($record, $authid,$authtypecode)
575 Either Create Or Modify existing authority.
576 returns authid of the newly created authority
581 # pass the MARC::Record to this function, and it will create the records in the authority table
582 my ($record,$authid,$authtypecode) = @_;
583 my $dbh=C4::Context->dbh;
584 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
586 # if authid empty => true add, find a new authid number
588 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
589 $format= 'UNIMARCAUTH';
595 #update date/time to 005 for marc and unimarc
596 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
597 my $f5=$record->field('005');
599 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
602 $f5->update($time.".0");
605 SetUTF8Flag($record);
606 if ($format eq "MARC21") {
607 if (!$record->leader) {
608 $record->leader($leader);
610 if (!$record->field('003')) {
611 $record->insert_fields_ordered(
612 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
615 my $date=POSIX::strftime("%y%m%d",localtime);
616 if (!$record->field('008')) {
617 # Get a valid default value for field 008
618 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
619 if(!$default_008 or length($default_008)<34) {
620 $default_008 = '|| aca||aabn | a|a d';
623 $default_008 = substr($default_008,0,34);
626 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
628 if (!$record->field('040')) {
629 $record->insert_fields_ordered(
630 MARC::Field->new('040','','',
631 'a' => C4::Context->preference('MARCOrgCode'),
632 'c' => C4::Context->preference('MARCOrgCode')
638 if ($format eq "UNIMARCAUTH") {
639 $record->leader(" nx j22 ") unless ($record->leader());
640 my $date=POSIX::strftime("%Y%m%d",localtime);
641 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
642 if (my $string=$record->subfield('100',"a")){
643 $string=~s/fre50/frey50/;
644 $record->field('100')->update('a'=>$string);
646 elsif ($record->field('100')){
647 $record->field('100')->update('a'=>$date.$defaultfield100);
649 $record->append_fields(
650 MARC::Field->new('100',' ',' '
651 ,'a'=>$date.$defaultfield100)
655 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
656 if (!$authid and $format eq "MARC21") {
657 # only need to do this fix when modifying an existing authority
658 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
660 if (my $field=$record->field($auth_type_tag)){
661 $field->update($auth_type_subfield=>$authtypecode);
664 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
667 # Save record into auth_header, update 001
669 # Save a blank record, get authid
670 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
671 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
672 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
674 # Insert/update the recordID in MARC record
675 $record->delete_field( $record->field('001') );
676 $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) );
678 $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;
679 ModZebra( $authid, 'specialUpdate', 'authorityserver', $record );
686 DelAuthority({ authid => $authid });
688 Deletes $authid and calls merge to cleanup in linked biblio records
694 my $authid = $params->{authid} || return;
695 my $dbh=C4::Context->dbh;
696 merge({ mergefrom => $authid, MARCfrom => GetAuthority($authid) });
697 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
698 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
699 ModZebra( $authid, "recordDelete", "authorityserver", undef);
704 $authid= &ModAuthority($authid,$record,$authtypecode)
706 Modifies authority record, optionally updates attached biblios.
711 my ( $authid, $record, $authtypecode ) = @_;
712 my $oldrecord = GetAuthority($authid);
713 #Now rewrite the $record to table with an add
714 $authid = AddAuthority($record, $authid, $authtypecode);
715 merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
716 logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
720 =head2 GetAuthorityXML
722 $marcxml= &GetAuthorityXML( $authid)
724 returns xml form of record $authid
728 sub GetAuthorityXML {
729 # Returns MARC::XML of the authority passed in parameter.
731 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
732 my $dbh=C4::Context->dbh;
733 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
734 $sth->execute($authid);
735 my ($marcxml)=$sth->fetchrow;
739 # for MARC21, call GetAuthority instead of
740 # getting the XML directly since we may
741 # need to fix up the location of the authority
742 # code -- note that this is reasonably safe
743 # because GetAuthorityXML is used only by the
744 # indexing processes like zebraqueue_start.pl
745 my $record = GetAuthority($authid);
746 return $record->as_xml_record('MARC21');
752 $record= &GetAuthority( $authid)
754 Returns MARC::Record of the authority passed in parameter.
760 my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
761 return unless $authority;
762 return ($authority->record);
765 =head2 FindDuplicateAuthority
767 $record= &FindDuplicateAuthority( $record, $authtypecode)
769 return $authid,Summary if duplicate is found.
771 Comments : an improvement would be to return All the records that match.
775 sub FindDuplicateAuthority {
777 my ($record,$authtypecode)=@_;
778 # warn "IN for ".$record->as_formatted;
779 my $dbh = C4::Context->dbh;
780 # warn "".$record->as_formatted;
781 my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
782 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
783 # build a request for SearchAuthorities
785 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
792 my $query='at:'.$authtypecode.' ';
793 my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
794 if ($record->field($auth_tag_to_report)) {
795 foreach ($record->field($auth_tag_to_report)->subfields()) {
796 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
799 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
800 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1 );
801 # there is at least 1 result => return the 1st one
802 if (!defined $error && @{$results} ) {
803 my $marcrecord = C4::Search::new_record_from_zebra(
807 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
809 # no result, returns nothing
815 $summary= &BuildSummary( $record, $authid, $authtypecode)
817 Returns a hashref with a summary of the specified record.
819 Comment : authtypecode can be inferred from both record and authid.
820 Moreover, authid can also be inferred from $record.
821 Would it be interesting to delete those things.
826 ## give this a Marc record to return summary
827 my ($record,$authid,$authtypecode)=@_;
828 my $dbh=C4::Context->dbh;
830 my $summary_template;
831 # handle $authtypecode is NULL or eq ""
833 my $authref = Koha::Authority::Types->find($authtypecode);
835 $summary{authtypecode} = $authref->authtypecode;
836 $summary{type} = $authref->authtypetext;
837 $summary_template = $authref->summary;
838 # for MARC21, the authority type summary displays a label meant for
840 if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
841 $summary{label} = $authref->summary;
843 $summary{summary} = $authref->summary;
847 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
848 my %marc21controlrefs = ( 'a' => 'earlier',
854 'n' => 'notapplicable',
858 my %unimarc_relation_from_code = (
864 $thesaurus{'1'}="Peuples";
865 $thesaurus{'2'}="Anthroponymes";
866 $thesaurus{'3'}="Oeuvres";
867 $thesaurus{'4'}="Chronologie";
868 $thesaurus{'5'}="Lieux";
869 $thesaurus{'6'}="Sujets";
872 # if the library has a summary defined, use it. Otherwise, build a standard one
873 # FIXME - it appears that the summary field in the authority frameworks
874 # can work as a display template. However, this doesn't
875 # suit the MARC21 version, so for now the "templating"
876 # feature will be enabled only for UNIMARC for backwards
878 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
879 my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
880 my (@textbefore, @tag, @subtag, @textafter);
881 for(my $i = 0; $i < scalar @matches; $i++){
882 push @textbefore, $matches[$i] if($i%4 == 0);
883 push @tag, $matches[$i] if($i%4 == 1);
884 push @subtag, $matches[$i] if($i%4 == 2);
885 push @textafter, $matches[$i] if($i%4 == 3);
887 for(my $i = scalar @tag; $i >= 0; $i--){
888 my $textbefore = $textbefore[$i] || '';
889 my $tag = $tag[$i] || '';
890 my $subtag = $subtag[$i] || '';
891 my $textafter = $textafter[$i] || '';
893 my $field = $record->field($tag);
897 $value = $textbefore . $field->data() . $textafter;
900 my @subfields = $field->subfield($subtag);
902 $value = $textbefore . join (" - ", @subfields) . $textafter;
906 $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
908 $summary{summary} =~ s/\\n/<br \/>/g;
915 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
916 # construct UNIMARC summary, that is quite different from MARC21 one
918 foreach my $field ($record->field('2..')) {
920 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
921 hemain => ( $field->subfield('a') // undef ),
922 field => $field->tag(),
926 foreach my $field ($record->field('3..')) {
927 push @notes, { note => $field->subfield('a'), field => $field->tag() };
929 foreach my $field ($record->field('4..')) {
930 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
932 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
933 hemain => ( $field->subfield('a') // undef ),
935 field => $field->tag(),
941 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
942 my $heading = $_->as_string('abcdefgjxyz');
947 hemain => ( $_->subfield('a') // undef ),
949 authid => ( $_->subfield('9') // undef ),
951 } $record->field('5..');
954 @otherscript = map { {
955 lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
956 term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
959 } } $record->field('7..');
962 # construct MARC21 summary
963 # FIXME - looping over 1XX is questionable
964 # since MARC21 authority should have only one 1XX
965 my $subfields_to_report;
966 foreach my $field ($record->field('1..')) {
967 my $tag = $field->tag();
968 next if "152" eq $tag;
969 # FIXME - 152 is not a good tag to use
970 # in MARC21 -- purely local tags really ought to be
973 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
974 } elsif ($tag eq '110') {
975 $subfields_to_report = 'abcdefghklmnoprstvxyz';
976 } elsif ($tag eq '111') {
977 $subfields_to_report = 'acdefghklnpqstvxyz';
978 } elsif ($tag eq '130') {
979 $subfields_to_report = 'adfghklmnoprstvxyz';
980 } elsif ($tag eq '148') {
981 $subfields_to_report = 'abvxyz';
982 } elsif ($tag eq '150') {
983 $subfields_to_report = 'abvxyz';
984 } elsif ($tag eq '151') {
985 $subfields_to_report = 'avxyz';
986 } elsif ($tag eq '155') {
987 $subfields_to_report = 'abvxyz';
988 } elsif ($tag eq '180') {
989 $subfields_to_report = 'vxyz';
990 } elsif ($tag eq '181') {
991 $subfields_to_report = 'vxyz';
992 } elsif ($tag eq '182') {
993 $subfields_to_report = 'vxyz';
994 } elsif ($tag eq '185') {
995 $subfields_to_report = 'vxyz';
997 if ($subfields_to_report) {
999 heading => $field->as_string($subfields_to_report),
1000 hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1005 heading => $field->as_string(),
1006 hemain => ( $field->subfield( 'a' ) // undef ),
1011 foreach my $field ($record->field('4..')) { #See From
1012 my $type = 'seefrom';
1013 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1014 if ($type eq 'notapplicable') {
1015 $type = substr $field->subfield('w'), 2, 1;
1016 $type = 'earlier' if $type && $type ne 'n';
1018 if ($type eq 'subfi') {
1020 heading => $field->as_string($marc21subfields),
1021 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1022 type => ($field->subfield('i') || ''),
1023 field => $field->tag(),
1027 heading => $field->as_string($marc21subfields),
1028 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1030 field => $field->tag(),
1034 foreach my $field ($record->field('5..')) { #See Also
1035 my $type = 'seealso';
1036 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1037 if ($type eq 'notapplicable') {
1038 $type = substr $field->subfield('w'), 2, 1;
1039 $type = 'earlier' if $type && $type ne 'n';
1041 if ($type eq 'subfi') {
1043 heading => $field->as_string($marc21subfields),
1044 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1045 type => $field->subfield('i'),
1046 field => $field->tag(),
1047 search => $field->as_string($marc21subfields) || '',
1048 authid => $field->subfield('9') || ''
1052 heading => $field->as_string($marc21subfields),
1053 hemain => $field->subfield( substr($marc21subfields, 0, 1) ),
1055 field => $field->tag(),
1056 search => $field->as_string($marc21subfields) || '',
1057 authid => $field->subfield('9') || ''
1061 foreach my $field ($record->field('6..')) {
1062 push @notes, { note => $field->as_string(), field => $field->tag() };
1064 foreach my $field ($record->field('880')) {
1065 my $linkage = $field->subfield('6');
1066 my $category = substr $linkage, 0, 1;
1067 if ($category eq '1') {
1068 $category = 'preferred';
1069 } elsif ($category eq '4') {
1070 $category = 'seefrom';
1071 } elsif ($category eq '5') {
1072 $category = 'seealso';
1075 if ($field->subfield('w')) {
1076 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1080 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1081 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1084 $summary{mainentry} = $authorized[0]->{heading};
1085 $summary{mainmainentry} = $authorized[0]->{hemain};
1086 $summary{authorized} = \@authorized;
1087 $summary{notes} = \@notes;
1088 $summary{seefrom} = \@seefrom;
1089 $summary{seealso} = \@seealso;
1090 $summary{otherscript} = \@otherscript;
1094 =head2 GetAuthorizedHeading
1096 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1098 Takes a MARC::Record object describing an authority record or an authid, and
1099 returns a string representation of the first authorized heading. This routine
1100 should be considered a temporary shim to ease the future migration of authority
1101 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1105 sub GetAuthorizedHeading {
1108 unless ($record = $args->{record}) {
1109 return unless $args->{authid};
1110 $record = GetAuthority($args->{authid});
1112 return unless (ref $record eq 'MARC::Record');
1113 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1114 # construct UNIMARC summary, that is quite different from MARC21 one
1116 foreach my $field ($record->field('2..')) {
1117 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1120 foreach my $field ($record->field('1..')) {
1121 my $tag = $field->tag();
1122 next if "152" eq $tag;
1123 # FIXME - 152 is not a good tag to use
1124 # in MARC21 -- purely local tags really ought to be
1126 if ($tag eq '100') {
1127 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1128 } elsif ($tag eq '110') {
1129 return $field->as_string('abcdefghklmnoprstvxyz68');
1130 } elsif ($tag eq '111') {
1131 return $field->as_string('acdefghklnpqstvxyz68');
1132 } elsif ($tag eq '130') {
1133 return $field->as_string('adfghklmnoprstvxyz68');
1134 } elsif ($tag eq '148') {
1135 return $field->as_string('abvxyz68');
1136 } elsif ($tag eq '150') {
1137 return $field->as_string('abvxyz68');
1138 } elsif ($tag eq '151') {
1139 return $field->as_string('avxyz68');
1140 } elsif ($tag eq '155') {
1141 return $field->as_string('abvxyz68');
1142 } elsif ($tag eq '180') {
1143 return $field->as_string('vxyz68');
1144 } elsif ($tag eq '181') {
1145 return $field->as_string('vxyz68');
1146 } elsif ($tag eq '182') {
1147 return $field->as_string('vxyz68');
1148 } elsif ($tag eq '185') {
1149 return $field->as_string('vxyz68');
1151 return $field->as_string();
1158 =head2 BuildAuthHierarchies
1160 $text= &BuildAuthHierarchies( $authid, $force)
1162 return text containing trees for hierarchies
1163 for them to be stored in auth_header
1166 122,1314,2452;1324,2342,3,2452
1170 sub BuildAuthHierarchies{
1171 my $authid = shift @_;
1172 # warn "authid : $authid";
1173 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1175 my $dbh=C4::Context->dbh;
1177 my $data = GetHeaderAuthority($authid);
1178 if ($data->{'authtrees'} and not $force){
1179 return $data->{'authtrees'};
1180 # } elsif ($data->{'authtrees'}){
1181 # $hierarchies=$data->{'authtrees'};
1183 my $record = GetAuthority($authid);
1185 return unless $record;
1186 foreach my $field ($record->field('5..')){
1189 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1190 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1192 my $subfauthid=_get_authid_subfield($field) || '';
1193 next if ($subfauthid eq $authid);
1194 my $parentrecord = GetAuthority($subfauthid);
1195 next unless $parentrecord;
1196 my $localresult=$hierarchies;
1198 $trees = BuildAuthHierarchies($subfauthid);
1201 @trees = split(/;/,$trees);
1203 push @trees, $trees;
1208 @globalresult = (@globalresult,@trees);
1211 $hierarchies=join(";",@globalresult);
1213 #Unless there is no ancestor, I am alone.
1214 $hierarchies="$authid" unless ($hierarchies);
1216 AddAuthorityTrees($authid,$hierarchies);
1217 return $hierarchies;
1220 =head2 BuildAuthHierarchy
1222 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1224 return a hashref in order to display hierarchy for record and final Authid $authid
1235 sub BuildAuthHierarchy{
1236 my $record = shift @_;
1237 my $class = shift @_;
1238 my $authid_constructed = shift @_;
1239 return unless ($record && $record->field('001'));
1240 my $authid=$record->field('001')->data();
1242 my $parents=""; my $children="";
1243 my (@loopparents,@loopchildren);
1244 my $marcflavour = C4::Context->preference('marcflavour');
1245 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1246 foreach my $field ($record->field('5..')){
1247 my $subfauthid=_get_authid_subfield($field);
1248 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1249 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1250 if ($relationship eq 'h'){
1251 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1253 elsif ($relationship eq 'g'){
1254 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1256 # brothers could get in there with an else
1259 $cell{"parents"}=\@loopparents;
1260 $cell{"children"}=\@loopchildren;
1261 $cell{"class"}=$class;
1262 $cell{"authid"}=$authid;
1263 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1264 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1268 =head2 BuildAuthHierarchyBranch
1270 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1272 Return a data structure representing an authority hierarchy
1273 given a list of authorities representing a single branch in
1274 an authority hierarchy tree. $authid is the current node in
1275 the tree (which may or may not be somewhere in the middle).
1276 $cnt represents the level of the upper-most item, and is only
1277 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1278 don't ever pass in anything but zero to it).
1282 sub BuildAuthHierarchyBranch {
1283 my ($tree, $authid, $cnt) = @_;
1285 my $elementdata = GetAuthority(shift @$tree);
1286 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1287 if (scalar @$tree > 0) {
1288 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1289 my $nextAuthid = $nextBranch->{authid};
1291 # If we already have the next branch listed as a child, let's
1292 # replace the old listing with the new one. If not, we will add
1293 # the branch at the end.
1294 foreach my $cell (@{$branch->{children}}) {
1295 if ($cell->{authid} eq $nextAuthid) {
1296 $cell = $nextBranch;
1301 push @{$branch->{children}}, $nextBranch unless $found;
1306 =head2 GenerateHierarchy
1308 $hierarchy = &GenerateHierarchy($authid);
1310 Return an arrayref holding one or more "trees" representing
1311 authority hierarchies.
1315 sub GenerateHierarchy {
1317 my $trees = BuildAuthHierarchies($authid);
1318 my @trees = split /;/,$trees ;
1319 push @trees,$trees unless (@trees);
1320 my @loophierarchies;
1321 foreach my $tree (@trees){
1322 my @tree=split /,/,$tree;
1323 push @tree, $tree unless (@tree);
1324 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1325 push @loophierarchies, [ $branch ];
1327 return \@loophierarchies;
1330 sub _get_authid_subfield{
1332 return $field->subfield('9')||$field->subfield('3');
1335 =head2 GetHeaderAuthority
1337 $ref= &GetHeaderAuthority( $authid)
1339 return a hashref in order auth_header table data
1343 sub GetHeaderAuthority{
1344 my $authid = shift @_;
1345 my $sql= "SELECT * from auth_header WHERE authid = ?";
1346 my $dbh=C4::Context->dbh;
1347 my $rq= $dbh->prepare($sql);
1348 $rq->execute($authid);
1349 my $data= $rq->fetchrow_hashref;
1353 =head2 AddAuthorityTrees
1355 $ref= &AddAuthorityTrees( $authid, $trees)
1357 return success or failure
1361 sub AddAuthorityTrees{
1362 my $authid = shift @_;
1363 my $trees = shift @_;
1364 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1365 my $dbh=C4::Context->dbh;
1366 my $rq= $dbh->prepare($sql);
1367 return $rq->execute($trees,$authid);
1373 mergefrom => mergefrom,
1374 MARCfrom => $MARCfrom,
1375 [ mergeto => $mergeto, ]
1376 [ MARCto => $MARCto, ]
1377 [ biblionumbers => [ $a, $b, $c ], ]
1378 [ override_limit => 1, ]
1381 Merge biblios linked to authority $mergefrom.
1382 If $mergeto equals mergefrom, the linked biblio field is updated.
1383 If $mergeto is different, the biblio field will be linked to $mergeto.
1384 If $mergeto is missing, the biblio field is deleted.
1386 Normally all biblio records linked to $mergefrom, will be considered. But
1387 you can pass specific numbers via the biblionumbers parameter.
1389 The parameter override_limit is used by the cron job to force larger
1392 Note: Although $mergefrom and $mergeto will normally be of the same
1393 authority type, merge also supports moving to another authority type.
1398 my ( $params ) = @_;
1399 my $mergefrom = $params->{mergefrom} || return;
1400 my $MARCfrom = $params->{MARCfrom};
1401 my $mergeto = $params->{mergeto};
1402 my $MARCto = $params->{MARCto};
1403 my $override_limit = $params->{override_limit};
1405 # If we do not have biblionumbers, we get all linked biblios if the
1406 # number of linked records does not exceed the limit UNLESS we override.
1408 if( $params->{biblionumbers} ) {
1409 @biblionumbers = @{ $params->{biblionumbers} };
1410 } elsif( $override_limit ) {
1411 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1412 } else { # now first check number of linked records
1413 my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1414 my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1415 if( $hits > 0 && $hits <= $max ) {
1416 @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1417 } elsif( $hits > $max ) { #postpone this merge to the cron job
1418 Koha::Authority::MergeRequest->new({
1419 authid => $mergefrom,
1420 oldrecord => $MARCfrom,
1421 authid_new => $mergeto,
1425 return 0 if !@biblionumbers;
1427 # Search authtypes and reporting tags
1428 my $authfrom = Koha::Authorities->find($mergefrom);
1429 my $authto = Koha::Authorities->find($mergeto);
1430 my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1431 my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1432 my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1433 my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1436 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1438 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from);
1440 # Get All candidate Tags for the change
1441 # (This will reduce the search scope in marc records).
1442 # For a deleted authority record, we scan all auth controlled fields
1443 my $dbh = C4::Context->dbh;
1444 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1445 my $tags_using_authtype = $authtypefrom ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode )) : $dbh->selectcol_arrayref( "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''" );
1447 if( $authtypefrom && $authtypeto && $authtypeto->authtypecode ne $authtypefrom->authtypecode ) {
1448 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1451 my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1452 my $skip_subfields = $overwrite
1453 # This hash contains all subfields from the authority report fields
1454 # Including $MARCfrom as well as $MARCto
1455 # We only need it in loose merge mode; replaces the former $exclude
1457 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1458 # And we need to add $9 in order not to duplicate
1459 $skip_subfields->{9} = 1 if !$overwrite;
1461 my $counteditedbiblio = 0;
1462 foreach my $biblionumber ( @biblionumbers ) {
1463 my $marcrecord = GetMarcBiblio( $biblionumber );
1464 next if !$marcrecord;
1466 foreach my $tagfield (@$tags_using_authtype) {
1467 my $countfrom = 0; # used in strict mode to remove duplicates
1468 foreach my $field ( $marcrecord->field($tagfield) ) {
1469 my $auth_number = $field->subfield("9"); # link to authority
1470 my $tag = $field->tag();
1471 next if !defined($auth_number) || $auth_number ne $mergefrom;
1473 if ( !$mergeto || ( $overwrite && $countfrom > 1 ) ) {
1474 # if mergeto is missing, this indicates a delete
1475 # Or: remove this duplicate in strict mode
1476 $marcrecord->delete_field($field);
1480 my $newtag = $tags_new
1481 ? _merge_newtag( $tag, $tags_new )
1483 my $field_to = MARC::Field->new(
1485 $field->indicator(1),
1486 $field->indicator(2),
1489 foreach my $subfield ( grep { $_->[0] ne '9' } @record_to ) {
1490 $field_to->add_subfields( $subfield->[0] => $subfield->[1] );
1492 if ( !$overwrite ) {
1493 # add subfields back in loose mode, check skip_subfields
1494 foreach my $subfield ( $field->subfields ) {
1495 next if $skip_subfields->{ $subfield->[0] };
1496 $field_to->add_subfields( $subfield->[0], $subfield->[1] );
1500 $marcrecord->delete_field($field);
1501 append_fields_ordered( $marcrecord, $field_to );
1503 $field->replace_with($field_to);
1509 ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1510 $counteditedbiblio++;
1512 return $counteditedbiblio;
1516 # Routine is only called for an (exceptional) authtypecode change
1517 # Fixes old behavior of returning the first tag found
1518 my ( $oldtag, $new_tags ) = @_;
1520 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1521 my $prefix = substr( $oldtag, 0, 1 );
1522 my $guess = $prefix . substr( $new_tags->[0], -2 );
1523 if( grep { $_ eq $guess } @$new_tags ) {
1526 # Otherwise return one from the same block e.g. 6XX for 650
1527 # If not there too, fall back to first new tag (old behavior!)
1528 my @same_block = grep { /^$prefix/ } @$new_tags;
1529 return @same_block ? $same_block[0] : $new_tags->[0];
1532 sub append_fields_ordered {
1533 # while we lack this function in MARC::Record
1534 # we do not want insert_fields_ordered since it inserts before
1535 my ( $record, $field ) = @_;
1536 if( my @flds = $record->field( $field->tag ) ) {
1537 $record->insert_fields_after( pop @flds, $field );
1538 } else { # now fallback to insert_fields_ordered
1539 $record->insert_fields_ordered( $field );
1543 =head2 get_auth_type_location
1545 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1547 Get the tag and subfield used to store the heading type
1548 for indexing purposes. The C<$auth_type> parameter is
1549 optional; if it is not supplied, assume ''.
1551 This routine searches the MARC authority framework
1552 for the tag and subfield whose kohafield is
1553 C<auth_header.authtypecode>; if no such field is
1554 defined in the framework, default to the hardcoded value
1555 specific to the MARC format.
1559 sub get_auth_type_location {
1560 my $auth_type_code = @_ ? shift : '';
1562 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1563 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1564 return ($tag, $subfield);
1566 if (C4::Context->preference('marcflavour') eq "MARC21") {
1567 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1569 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1574 END { } # module clean-up code here (global destructor)
1581 Koha Development Team <http://koha-community.org/>
1583 Paul POULAIN paul.poulain@free.fr