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
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 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
118 # the authtypecode. Then, search on $a of this tag_to_report
119 # also store main entry MARC tag, to extract it at end of search
121 ##first set the authtype search and may be multiple authorities
125 my @auths=split / /,$authtypecode ;
126 foreach my $auth (@auths){
127 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
128 push @authtypecode ,$auth;
132 while ($n>1){$query= "\@or ".$query;$n--;}
140 for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
143 if ( @
$tags[$i] eq "mainmainentry" ) {
144 $attr = " \@attr 1=Heading-Main ";
146 elsif ( @
$tags[$i] eq "mainentry" ) {
147 $attr = " \@attr 1=Heading ";
149 elsif ( @
$tags[$i] eq "match" ) {
150 $attr = " \@attr 1=Match ";
152 elsif ( @
$tags[$i] eq "match-heading" ) {
153 $attr = " \@attr 1=Match-heading ";
155 elsif ( @
$tags[$i] eq "see-from" ) {
156 $attr = " \@attr 1=Match-heading-see-from ";
158 elsif ( @
$tags[$i] eq "thesaurus" ) {
159 $attr = " \@attr 1=Subject-heading-thesaurus ";
161 elsif ( @
$tags[$i] eq "all" ) {
162 $attr = " \@attr 1=Any ";
164 else { # Use the index passed in params
165 $attr = " \@attr 1=" . @
$tags[$i] . " ";
168 else { # Assume any if no index was specified
169 $attr = " \@attr 1=Any ";
172 my $operator = @
$operator[$i];
173 if ( $operator and $operator eq 'is' ) {
174 $attr .= " \@attr 4=1 \@attr 5=100 "
175 ; ##Phrase, No truncation,all of subfield field must match
177 elsif ( $operator and $operator eq "=" ) {
178 $attr .= " \@attr 4=107 "; #Number Exact match
180 elsif ( $operator and $operator eq "start" ) {
181 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
182 ; #Firstinfield Phrase, Right truncated
184 elsif ( $operator and $operator eq "exact" ) {
185 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
186 ; ##Phrase, No truncation,all of subfield field must match
189 $attr .= " \@attr 5=1 \@attr 4=6 "
190 ; ## Word list, right truncated, anywhere
191 if ( $sortby eq 'Relevance' ) {
192 $attr .= "\@attr 2=102 ";
196 s/"/\\"/g; # Escape the double-quotes in the search value
197 $attr = $attr . "\"" . @
$value[$i] . "\"";
203 ##Add how many queries generated
204 if (defined $query && $query=~/\S+/){
205 $query= $and x
$attr_cnt . $query . (defined $q2 ?
$q2 : '');
210 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
212 if ($sortby eq 'HeadingAsc') {
213 $orderstring = '@attr 7=1 @attr 1=Heading 0';
214 } elsif ($sortby eq 'HeadingDsc') {
215 $orderstring = '@attr 7=2 @attr 1=Heading 0';
216 } elsif ($sortby eq 'AuthidAsc') {
217 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
218 } elsif ($sortby eq 'AuthidDsc') {
219 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
221 $query=($query?
$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
222 $query="\@or $orderstring $query" if $orderstring;
224 $offset = 0 if not defined $offset or $offset < 0;
225 my $counter = $offset;
226 $length=10 unless $length;
229 $oAuth[0]=C4
::Context
->Zconn("authorityserver" , 1);
230 my $Anewq= new ZOOM
::Query
::PQF
($query,$oAuth[0]);
232 $oAResult= $oAuth[0]->search($Anewq) ;
233 while (($i = ZOOM
::event
(\
@oAuth)) != 0) {
234 my $ev = $oAuth[$i-1]->last_event();
235 last if $ev == ZOOM
::Event
::ZEND
;
237 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
239 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
244 $nbresults=$oAResult->size();
245 my $nremains=$nbresults;
247 my @finalresult = ();
251 ##Find authid and linkid fields
252 ##we may be searching multiple authoritytypes.
253 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
254 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
255 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
256 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
258 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
259 my $rec=$oAResult->record($counter);
260 my $separator=C4
::Context
->preference('AuthoritySeparator');
261 my $authrecord = C4
::Search
::new_record_from_zebra
(
266 if ( !defined $authrecord or !defined $authrecord->field('001') ) {
271 SetUTF8Flag
( $authrecord );
273 my $authid=$authrecord->field('001')->data();
275 $newline{authid
} = $authid;
276 if ( !$skipmetadata ) {
277 my $auth_tag_to_report;
278 $auth_tag_to_report = Koha
::Authority
::Types
->find($authtypecode)->auth_tag_to_report
281 my $mainentry = $authrecord->field($auth_tag_to_report);
283 foreach ( $mainentry->subfields() ) {
284 $reported_tag .= '$' . $_->[0] . $_->[1];
288 my ( $thisauthtype, $thisauthtypecode );
289 if ( my $authority = Koha
::Authorities
->find($authid) ) {
290 $thisauthtypecode = $authority->authtypecode;
291 $thisauthtype = Koha
::Authority
::Types
->find($thisauthtypecode);
293 unless (defined $thisauthtype) {
294 $thisauthtypecode = $authtypecode;
295 $thisauthtype = Koha
::Authority
::Types
->find($thisauthtypecode);
297 my $summary = BuildSummary
( $authrecord, $authid, $thisauthtypecode );
299 $newline{authtype
} = defined($thisauthtype) ?
300 $thisauthtype->authtypetext : '';
301 $newline{summary
} = $summary;
302 $newline{even
} = $counter % 2;
303 $newline{reported_tag
} = $reported_tag;
306 push @finalresult, \
%newline;
309 if (! $skipmetadata) {
310 for (my $z=0; $z<@finalresult; $z++){
311 my $count = Koha
::Authorities
->get_usage_count({ authid
=> $finalresult[$z]{authid
} });
312 $finalresult[$z]{used
}=$count;
318 $oAResult->destroy();
319 # $oAuth[0]->destroy();
321 return (\
@finalresult, $nbresults);
324 =head2 GuessAuthTypeCode
326 my $authtypecode = GuessAuthTypeCode($record);
328 Get the record and tries to guess the adequate authtypecode from its content.
332 sub GuessAuthTypeCode
{
333 my ($record, $heading_fields) = @_;
334 return unless defined $record;
335 $heading_fields //= {
337 '100'=>{authtypecode
=>'PERSO_NAME'},
338 '110'=>{authtypecode
=>'CORPO_NAME'},
339 '111'=>{authtypecode
=>'MEETI_NAME'},
340 '130'=>{authtypecode
=>'UNIF_TITLE'},
341 '148'=>{authtypecode
=>'CHRON_TERM'},
342 '150'=>{authtypecode
=>'TOPIC_TERM'},
343 '151'=>{authtypecode
=>'GEOGR_NAME'},
344 '155'=>{authtypecode
=>'GENRE/FORM'},
345 '180'=>{authtypecode
=>'GEN_SUBDIV'},
346 '181'=>{authtypecode
=>'GEO_SUBDIV'},
347 '182'=>{authtypecode
=>'CHRON_SUBD'},
348 '185'=>{authtypecode
=>'FORM_SUBD'},
350 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
351 # 604 with embedded 700, 701, 702
352 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
353 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
354 #216 Trademark 716 [Reserved for future use]
355 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
356 #230 Title 500 4-- with embedded 500 605
357 #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
358 #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
359 #250 Topical subject 606
360 #260 Place access 620
361 #280 Form, genre or physical characteristics 608
364 # Could also be represented with :
366 #a = personal name entry
367 #b = corporate name entry
368 #c = territorial or geographical name
372 #g = collective uniform title
374 #i = name/collective uniform title
377 #l = form, genre or physical characteristics
379 '200'=>{authtypecode
=>'NP'},
380 '210'=>{authtypecode
=>'CO'},
381 '215'=>{authtypecode
=>'SNG'},
382 '216'=>{authtypecode
=>'TM'},
383 '220'=>{authtypecode
=>'FAM'},
384 '230'=>{authtypecode
=>'TU'},
385 '235'=>{authtypecode
=>'CO_UNI_TI'},
386 '240'=>{authtypecode
=>'SAUTTIT'},
387 '245'=>{authtypecode
=>'NAME_COL'},
388 '250'=>{authtypecode
=>'SNC'},
389 '260'=>{authtypecode
=>'PA'},
390 '280'=>{authtypecode
=>'GENRE/FORM'},
393 foreach my $field (keys %{$heading_fields->{uc(C4
::Context
->preference('marcflavour'))} }) {
394 return $heading_fields->{uc(C4
::Context
->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
401 my $authtid = GuessAuthId($record);
403 Get the record and tries to guess the adequate authtypecode from its content.
409 return unless ($record && $record->field('001'));
410 # my $authtypecode=GuessAuthTypeCode($record);
411 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
412 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
413 # else {return $record->field($tag)->data}
414 return $record->field('001')->data;
419 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
421 returns a ref to hashref of authorities tag and subfield structure.
425 $tagslabel->{$tag}->{$subfield}->{'attribute'}
427 where attribute takes values in :
445 my ($forlibrarian,$authtypecode)= @_;
446 my $dbh=C4
::Context
->dbh;
447 $authtypecode="" unless $authtypecode;
449 my $libfield = ($forlibrarian == 1)?
'liblibrarian' : 'libopac';
452 # check that authority exists
453 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
454 $sth->execute($authtypecode);
455 my ($total) = $sth->fetchrow;
456 $authtypecode="" unless ($total >0);
458 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
459 FROM auth_tag_structure
464 $sth->execute($authtypecode);
465 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
467 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
468 $res->{$tag}->{lib
} = ($forlibrarian or !$libopac)?
$liblibrarian:$libopac;
469 $res->{$tag}->{tab
} = " "; # XXX
470 $res->{$tag}->{mandatory
} = $mandatory;
471 $res->{$tag}->{repeatable
} = $repeatable;
474 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
475 FROM auth_subfield_structure
477 ORDER BY tagfield,tagsubfield"
479 $sth->execute($authtypecode);
482 my $authorised_value;
492 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
493 $mandatory, $repeatable, $authorised_value, $authtypecode,
494 $value_builder, $kohafield, $seealso, $hidden,
495 $isurl, $defaultvalue, $link )
499 $res->{$tag}->{$subfield}->{lib
} = ($forlibrarian or !$libopac)?
$liblibrarian:$libopac;
500 $res->{$tag}->{$subfield}->{tab
} = $tab;
501 $res->{$tag}->{$subfield}->{mandatory
} = $mandatory;
502 $res->{$tag}->{$subfield}->{repeatable
} = $repeatable;
503 $res->{$tag}->{$subfield}->{authorised_value
} = $authorised_value;
504 $res->{$tag}->{$subfield}->{authtypecode
} = $authtypecode;
505 $res->{$tag}->{$subfield}->{value_builder
} = $value_builder;
506 $res->{$tag}->{$subfield}->{kohafield
} = $kohafield;
507 $res->{$tag}->{$subfield}->{seealso
} = $seealso;
508 $res->{$tag}->{$subfield}->{hidden
} = $hidden;
509 $res->{$tag}->{$subfield}->{isurl
} = $isurl;
510 $res->{$tag}->{$subfield}->{link} = $link;
511 $res->{$tag}->{$subfield}->{defaultvalue
} = $defaultvalue;
518 $authid= &AddAuthority($record, $authid,$authtypecode)
520 Either Create Or Modify existing authority.
521 returns authid of the newly created authority
526 # pass the MARC::Record to this function, and it will create the records in the authority table
527 my ($record,$authid,$authtypecode) = @_;
528 my $dbh=C4
::Context
->dbh;
529 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
531 # if authid empty => true add, find a new authid number
533 if (uc(C4
::Context
->preference('marcflavour')) eq 'UNIMARC') {
534 $format= 'UNIMARCAUTH';
540 #update date/time to 005 for marc and unimarc
541 my $time=POSIX
::strftime
("%Y%m%d%H%M%S",localtime);
542 my $f5=$record->field('005');
544 $record->insert_fields_ordered( MARC
::Field
->new('005',$time.".0") );
547 $f5->update($time.".0");
550 SetUTF8Flag
($record);
551 if ($format eq "MARC21") {
552 my $userenv = C4
::Context
->userenv;
554 my $marcorgcode = C4
::Context
->preference('MARCOrgCode');
555 if ( $userenv && $userenv->{'branch'} ) {
556 $library = Koha
::Libraries
->find( $userenv->{'branch'} );
557 # userenv's library could not exist because of a trick in misc/commit_file.pl (see FIXME and set_userenv statement)
558 $marcorgcode = $library ?
$library->get_effective_marcorgcode : $marcorgcode;
560 if (!$record->leader) {
561 $record->leader($leader);
563 if (!$record->field('003')) {
564 $record->insert_fields_ordered(
565 MARC
::Field
->new('003', $marcorgcode),
568 my $date=POSIX
::strftime
("%y%m%d",localtime);
569 if (!$record->field('008')) {
570 # Get a valid default value for field 008
571 my $default_008 = C4
::Context
->preference('MARCAuthorityControlField008');
572 if(!$default_008 or length($default_008)<34) {
573 $default_008 = '|| aca||aabn | a|a d';
576 $default_008 = substr($default_008,0,34);
579 $record->insert_fields_ordered( MARC
::Field
->new('008',$date.$default_008) );
581 if (!$record->field('040')) {
582 $record->insert_fields_ordered(
583 MARC
::Field
->new('040','','',
591 if ($format eq "UNIMARCAUTH") {
592 $record->leader(" nx j22 ") unless ($record->leader());
593 my $date=POSIX
::strftime
("%Y%m%d",localtime);
594 my $defaultfield100 = C4
::Context
->preference('UNIMARCAuthorityField100');
595 if (my $string=$record->subfield('100',"a")){
596 $string=~s/fre50/frey50/;
597 $record->field('100')->update('a'=>$string);
599 elsif ($record->field('100')){
600 $record->field('100')->update('a'=>$date.$defaultfield100);
602 $record->append_fields(
603 MARC
::Field
->new('100',' ',' '
604 ,'a'=>$date.$defaultfield100)
608 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location
($authtypecode);
609 if (!$authid and $format eq "MARC21") {
610 # only need to do this fix when modifying an existing authority
611 C4
::AuthoritiesMarc
::MARC21
::fix_marc21_auth_type_location
($record, $auth_type_tag, $auth_type_subfield);
613 if (my $field=$record->field($auth_type_tag)){
614 $field->update($auth_type_subfield=>$authtypecode);
617 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
620 # Save record into auth_header, update 001
622 # Save a blank record, get authid
623 $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, '' );
624 $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' );
625 logaction
( "AUTHORITIES", "ADD", $authid, "authority" ) if C4
::Context
->preference("AuthoritiesLog");
627 # Insert/update the recordID in MARC record
628 $record->delete_field( $record->field('001') );
629 $record->insert_fields_ordered( MARC
::Field
->new( '001', $authid ) );
631 $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
;
632 ModZebra
( $authid, 'specialUpdate', 'authorityserver', $record );
639 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
641 Deletes $authid and calls merge to cleanup linked biblio records.
642 Parameter skip_merge is used in authorities/merge.pl. You should normally not
649 my $authid = $params->{authid
} || return;
650 my $skip_merge = $params->{skip_merge
};
651 my $dbh = C4
::Context
->dbh;
652 merge
({ mergefrom
=> $authid }) if !$skip_merge;
653 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
654 logaction
( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4
::Context
->preference("AuthoritiesLog");
655 ModZebra
( $authid, "recordDelete", "authorityserver", undef);
660 $authid= &ModAuthority($authid,$record,$authtypecode)
662 Modifies authority record, optionally updates attached biblios.
667 my ( $authid, $record, $authtypecode ) = @_;
668 my $oldrecord = GetAuthority
($authid);
669 #Now rewrite the $record to table with an add
670 $authid = AddAuthority
($record, $authid, $authtypecode);
671 merge
({ mergefrom
=> $authid, MARCfrom
=> $oldrecord, mergeto
=> $authid, MARCto
=> $record });
672 logaction
( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4
::Context
->preference("AuthoritiesLog");
676 =head2 GetAuthorityXML
678 $marcxml= &GetAuthorityXML( $authid)
680 returns xml form of record $authid
684 sub GetAuthorityXML
{
685 # Returns MARC::XML of the authority passed in parameter.
687 if (uc(C4
::Context
->preference('marcflavour')) eq 'UNIMARC') {
688 my $dbh=C4
::Context
->dbh;
689 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
690 $sth->execute($authid);
691 my ($marcxml)=$sth->fetchrow;
695 # for MARC21, call GetAuthority instead of
696 # getting the XML directly since we may
697 # need to fix up the location of the authority
698 # code -- note that this is reasonably safe
699 # because GetAuthorityXML is used only by the
700 # indexing processes like zebraqueue_start.pl
701 my $record = GetAuthority
($authid);
702 return $record->as_xml_record('MARC21');
708 $record= &GetAuthority( $authid)
710 Returns MARC::Record of the authority passed in parameter.
716 my $authority = Koha
::MetadataRecord
::Authority
->get_from_authid($authid);
717 return unless $authority;
718 return ($authority->record);
721 =head2 FindDuplicateAuthority
723 $record= &FindDuplicateAuthority( $record, $authtypecode)
725 return $authid,Summary if duplicate is found.
727 Comments : an improvement would be to return All the records that match.
731 sub FindDuplicateAuthority
{
733 my ($record,$authtypecode)=@_;
734 # warn "IN for ".$record->as_formatted;
735 my $dbh = C4
::Context
->dbh;
736 # warn "".$record->as_formatted;
737 my $auth_tag_to_report = Koha
::Authority
::Types
->find($authtypecode)->auth_tag_to_report;
738 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
739 # build a request for SearchAuthorities
741 $authtypecode =~ s
#/#\\/#; # GENRE/FORM contains forward slash which is a reserved character
742 my $query='at:'.$authtypecode.' ';
743 my $filtervalues=qr
([\001-\040\Q
!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
744 if ($record->field($auth_tag_to_report)) {
745 foreach ($record->field($auth_tag_to_report)->subfields()) {
746 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
749 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
750 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver
' ] );
751 # there is at least 1 result => return the 1st one
752 if (!defined $error && @{$results} ) {
753 my $marcrecord = C4::Search::new_record_from_zebra(
757 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
759 # no result, returns nothing
765 $summary= &BuildSummary( $record, $authid, $authtypecode)
767 Returns a hashref with a summary of the specified record.
769 Comment : authtypecode can be inferred from both record and authid.
770 Moreover, authid can also be inferred from $record.
771 Would it be interesting to delete those things.
776 ## give this a Marc record to return summary
777 my ($record,$authid,$authtypecode)=@_;
778 my $dbh=C4::Context->dbh;
780 my $summary_template;
781 # handle $authtypecode is NULL or eq ""
783 my $authref = Koha::Authority::Types->find($authtypecode);
785 $summary{authtypecode} = $authref->authtypecode;
786 $summary{type} = $authref->authtypetext;
787 $summary_template = $authref->summary;
788 # for MARC21, the authority type summary displays a label meant for
790 if (C4::Context->preference('marcflavour
') ne 'UNIMARC
') {
791 $summary{label} = $authref->summary;
793 $summary{summary} = $authref->summary;
797 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68
';
798 my %marc21controlrefs = ( 'a
' => 'earlier
',
804 'n
' => 'notapplicable
',
808 my %unimarc_relation_from_code = (
814 $thesaurus{'1'}="Peuples";
815 $thesaurus{'2'}="Anthroponymes";
816 $thesaurus{'3'}="Oeuvres";
817 $thesaurus{'4'}="Chronologie";
818 $thesaurus{'5'}="Lieux";
819 $thesaurus{'6'}="Sujets";
822 # if the library has a summary defined, use it. Otherwise, build a standard one
823 # FIXME - it appears that the summary field in the authority frameworks
824 # can work as a display template. However, this doesn't
825 # suit the MARC21 version, so for now the "templating"
826 # feature will be enabled only for UNIMARC for backwards
828 if ($summary{summary
} and C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
829 my @matches = ($summary{summary
} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
830 my (@textbefore, @tag, @subtag, @textafter);
831 for(my $i = 0; $i < scalar @matches; $i++){
832 push @textbefore, $matches[$i] if($i%4 == 0);
833 push @tag, $matches[$i] if($i%4 == 1);
834 push @subtag, $matches[$i] if($i%4 == 2);
835 push @textafter, $matches[$i] if($i%4 == 3);
837 for(my $i = scalar @tag; $i >= 0; $i--){
838 my $textbefore = $textbefore[$i] || '';
839 my $tag = $tag[$i] || '';
840 my $subtag = $subtag[$i] || '';
841 my $textafter = $textafter[$i] || '';
843 my $field = $record->field($tag);
847 $value = $textbefore . $field->data() . $textafter;
850 my @subfields = $field->subfield($subtag);
852 $value = $textbefore . join (" - ", @subfields) . $textafter;
856 $summary{summary
} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
858 $summary{summary
} =~ s/\\n/<br \/>/g
;
865 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
866 # construct UNIMARC summary, that is quite different from MARC21 one
868 foreach my $field ($record->field('2..')) {
870 heading
=> $field->as_string('abcdefghijlmnopqrstuvwxyz'),
871 hemain
=> ( $field->subfield('a') // undef ),
872 field
=> $field->tag(),
876 foreach my $field ($record->field('3..')) {
877 push @notes, { note
=> $field->subfield('a'), field
=> $field->tag() };
879 foreach my $field ($record->field('4..')) {
880 my $thesaurus = $field->subfield('2') ?
"thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
882 heading
=> $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
883 hemain
=> ( $field->subfield('a') // undef ),
885 field
=> $field->tag(),
891 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
892 my $heading = $_->as_string('abcdefgjxyz');
897 hemain
=> ( $_->subfield('a') // undef ),
899 authid
=> ( $_->subfield('9') // undef ),
901 } $record->field('5..');
904 @otherscript = map { {
905 lang
=> length ($_->subfield('8')) == 6 ?
substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
906 term
=> $_->subfield('a') . ($_->subfield('b') ?
', ' . $_->subfield('b') : ''),
909 } } $record->field('7..');
912 # construct MARC21 summary
913 # FIXME - looping over 1XX is questionable
914 # since MARC21 authority should have only one 1XX
915 my $subfields_to_report;
916 foreach my $field ($record->field('1..')) {
917 my $tag = $field->tag();
918 next if "152" eq $tag;
919 # FIXME - 152 is not a good tag to use
920 # in MARC21 -- purely local tags really ought to be
923 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
924 } elsif ($tag eq '110') {
925 $subfields_to_report = 'abcdefghklmnoprstvxyz';
926 } elsif ($tag eq '111') {
927 $subfields_to_report = 'acdefghklnpqstvxyz';
928 } elsif ($tag eq '130') {
929 $subfields_to_report = 'adfghklmnoprstvxyz';
930 } elsif ($tag eq '148') {
931 $subfields_to_report = 'abvxyz';
932 } elsif ($tag eq '150') {
933 $subfields_to_report = 'abvxyz';
934 } elsif ($tag eq '151') {
935 $subfields_to_report = 'avxyz';
936 } elsif ($tag eq '155') {
937 $subfields_to_report = 'abvxyz';
938 } elsif ($tag eq '180') {
939 $subfields_to_report = 'vxyz';
940 } elsif ($tag eq '181') {
941 $subfields_to_report = 'vxyz';
942 } elsif ($tag eq '182') {
943 $subfields_to_report = 'vxyz';
944 } elsif ($tag eq '185') {
945 $subfields_to_report = 'vxyz';
947 if ($subfields_to_report) {
949 heading
=> $field->as_string($subfields_to_report),
950 hemain
=> ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
955 heading
=> $field->as_string(),
956 hemain
=> ( $field->subfield( 'a' ) // undef ),
961 foreach my $field ($record->field('4..')) { #See From
962 my $type = 'seefrom';
963 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
964 if ($type eq 'notapplicable') {
965 $type = substr $field->subfield('w'), 2, 1;
966 $type = 'earlier' if $type && $type ne 'n';
968 if ($type eq 'subfi') {
970 heading
=> $field->as_string($marc21subfields),
971 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
972 type
=> ($field->subfield('i') || ''),
973 field
=> $field->tag(),
977 heading
=> $field->as_string($marc21subfields),
978 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
980 field
=> $field->tag(),
984 foreach my $field ($record->field('5..')) { #See Also
985 my $type = 'seealso';
986 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
987 if ($type eq 'notapplicable') {
988 $type = substr $field->subfield('w'), 2, 1;
989 $type = 'earlier' if $type && $type ne 'n';
991 if ($type eq 'subfi') {
993 heading
=> $field->as_string($marc21subfields),
994 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
995 type
=> scalar $field->subfield('i'),
996 field
=> $field->tag(),
997 search
=> $field->as_string($marc21subfields) || '',
998 authid
=> $field->subfield('9') || ''
1002 heading
=> $field->as_string($marc21subfields),
1003 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1005 field
=> $field->tag(),
1006 search
=> $field->as_string($marc21subfields) || '',
1007 authid
=> $field->subfield('9') || ''
1011 foreach my $field ($record->field('6..')) {
1012 push @notes, { note
=> $field->as_string(), field
=> $field->tag() };
1014 foreach my $field ($record->field('880')) {
1015 my $linkage = $field->subfield('6');
1016 my $category = substr $linkage, 0, 1;
1017 if ($category eq '1') {
1018 $category = 'preferred';
1019 } elsif ($category eq '4') {
1020 $category = 'seefrom';
1021 } elsif ($category eq '5') {
1022 $category = 'seealso';
1025 if ($field->subfield('w')) {
1026 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1030 my $direction = $linkage =~ m
#/r$# ? 'rtl' : 'ltr';
1031 push @otherscript, { term
=> $field->as_string($subfields_to_report), category
=> $category, type
=> $type, direction
=> $direction, linkage
=> $linkage };
1034 $summary{mainentry
} = $authorized[0]->{heading
};
1035 $summary{mainmainentry
} = $authorized[0]->{hemain
};
1036 $summary{authorized
} = \
@authorized;
1037 $summary{notes
} = \
@notes;
1038 $summary{seefrom
} = \
@seefrom;
1039 $summary{seealso
} = \
@seealso;
1040 $summary{otherscript
} = \
@otherscript;
1044 =head2 GetAuthorizedHeading
1046 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1048 Takes a MARC::Record object describing an authority record or an authid, and
1049 returns a string representation of the first authorized heading. This routine
1050 should be considered a temporary shim to ease the future migration of authority
1051 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1055 sub GetAuthorizedHeading
{
1058 unless ($record = $args->{record
}) {
1059 return unless $args->{authid
};
1060 $record = GetAuthority
($args->{authid
});
1062 return unless (ref $record eq 'MARC::Record');
1063 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
1064 # construct UNIMARC summary, that is quite different from MARC21 one
1066 foreach my $field ($record->field('2..')) {
1067 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1070 foreach my $field ($record->field('1..')) {
1071 my $tag = $field->tag();
1072 next if "152" eq $tag;
1073 # FIXME - 152 is not a good tag to use
1074 # in MARC21 -- purely local tags really ought to be
1076 if ($tag eq '100') {
1077 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1078 } elsif ($tag eq '110') {
1079 return $field->as_string('abcdefghklmnoprstvxyz68');
1080 } elsif ($tag eq '111') {
1081 return $field->as_string('acdefghklnpqstvxyz68');
1082 } elsif ($tag eq '130') {
1083 return $field->as_string('adfghklmnoprstvxyz68');
1084 } elsif ($tag eq '148') {
1085 return $field->as_string('abvxyz68');
1086 } elsif ($tag eq '150') {
1087 return $field->as_string('abvxyz68');
1088 } elsif ($tag eq '151') {
1089 return $field->as_string('avxyz68');
1090 } elsif ($tag eq '155') {
1091 return $field->as_string('abvxyz68');
1092 } elsif ($tag eq '180') {
1093 return $field->as_string('vxyz68');
1094 } elsif ($tag eq '181') {
1095 return $field->as_string('vxyz68');
1096 } elsif ($tag eq '182') {
1097 return $field->as_string('vxyz68');
1098 } elsif ($tag eq '185') {
1099 return $field->as_string('vxyz68');
1101 return $field->as_string();
1108 =head2 BuildAuthHierarchies
1110 $text= &BuildAuthHierarchies( $authid, $force)
1112 return text containing trees for hierarchies
1113 for them to be stored in auth_header
1116 122,1314,2452;1324,2342,3,2452
1120 sub BuildAuthHierarchies
{
1121 my $authid = shift @_;
1122 # warn "authid : $authid";
1123 my $force = shift @_ || (C4
::Context
->preference('marcflavour') eq 'UNIMARC' ?
0 : 1);
1125 my $dbh=C4
::Context
->dbh;
1127 my $data = GetHeaderAuthority
($authid);
1128 if ($data->{'authtrees'} and not $force){
1129 return $data->{'authtrees'};
1130 # } elsif ($data->{'authtrees'}){
1131 # $hierarchies=$data->{'authtrees'};
1133 my $record = GetAuthority
($authid);
1135 return unless $record;
1136 foreach my $field ($record->field('5..')){
1139 (C4
::Context
->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1140 (C4
::Context
->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1142 my $subfauthid=_get_authid_subfield
($field) || '';
1143 next if ($subfauthid eq $authid);
1144 my $parentrecord = GetAuthority
($subfauthid);
1145 next unless $parentrecord;
1146 my $localresult=$hierarchies;
1148 $trees = BuildAuthHierarchies
($subfauthid);
1151 @trees = split(/;/,$trees);
1153 push @trees, $trees;
1158 @globalresult = (@globalresult,@trees);
1161 $hierarchies=join(";",@globalresult);
1163 #Unless there is no ancestor, I am alone.
1164 $hierarchies="$authid" unless ($hierarchies);
1166 AddAuthorityTrees
($authid,$hierarchies);
1167 return $hierarchies;
1170 =head2 BuildAuthHierarchy
1172 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1174 return a hashref in order to display hierarchy for record and final Authid $authid
1185 sub BuildAuthHierarchy
{
1186 my $record = shift @_;
1187 my $class = shift @_;
1188 my $authid_constructed = shift @_;
1189 return unless ($record && $record->field('001'));
1190 my $authid=$record->field('001')->data();
1192 my $parents=""; my $children="";
1193 my (@loopparents,@loopchildren);
1194 my $marcflavour = C4
::Context
->preference('marcflavour');
1195 my $relationshipsf = $marcflavour eq 'UNIMARC' ?
'5' : 'w';
1196 foreach my $field ($record->field('5..')){
1197 my $subfauthid=_get_authid_subfield
($field);
1198 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1199 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1200 if ($relationship eq 'h'){
1201 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1203 elsif ($relationship eq 'g'){
1204 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1206 # brothers could get in there with an else
1209 $cell{"parents"}=\
@loopparents;
1210 $cell{"children"}=\
@loopchildren;
1211 $cell{"class"}=$class;
1212 $cell{"authid"}=$authid;
1213 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1214 $cell{"value"}=C4
::Context
->preference('marcflavour') eq 'UNIMARC' ?
$record->subfield('2..',"a") : $record->subfield('1..', 'a');
1218 =head2 BuildAuthHierarchyBranch
1220 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1222 Return a data structure representing an authority hierarchy
1223 given a list of authorities representing a single branch in
1224 an authority hierarchy tree. $authid is the current node in
1225 the tree (which may or may not be somewhere in the middle).
1226 $cnt represents the level of the upper-most item, and is only
1227 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1228 don't ever pass in anything but zero to it).
1232 sub BuildAuthHierarchyBranch
{
1233 my ($tree, $authid, $cnt) = @_;
1235 my $elementdata = GetAuthority
(shift @
$tree);
1236 my $branch = BuildAuthHierarchy
($elementdata,"child".$cnt, $authid);
1237 if (scalar @
$tree > 0) {
1238 my $nextBranch = BuildAuthHierarchyBranch
($tree, $authid, ++$cnt);
1239 my $nextAuthid = $nextBranch->{authid
};
1241 # If we already have the next branch listed as a child, let's
1242 # replace the old listing with the new one. If not, we will add
1243 # the branch at the end.
1244 foreach my $cell (@
{$branch->{children
}}) {
1245 if ($cell->{authid
} eq $nextAuthid) {
1246 $cell = $nextBranch;
1251 push @
{$branch->{children
}}, $nextBranch unless $found;
1256 =head2 GenerateHierarchy
1258 $hierarchy = &GenerateHierarchy($authid);
1260 Return an arrayref holding one or more "trees" representing
1261 authority hierarchies.
1265 sub GenerateHierarchy
{
1267 my $trees = BuildAuthHierarchies
($authid);
1268 my @trees = split /;/,$trees ;
1269 push @trees,$trees unless (@trees);
1270 my @loophierarchies;
1271 foreach my $tree (@trees){
1272 my @tree=split /,/,$tree;
1273 push @tree, $tree unless (@tree);
1274 my $branch = BuildAuthHierarchyBranch
(\
@tree, $authid);
1275 push @loophierarchies, [ $branch ];
1277 return \
@loophierarchies;
1280 sub _get_authid_subfield
{
1282 return $field->subfield('9')||$field->subfield('3');
1285 =head2 GetHeaderAuthority
1287 $ref= &GetHeaderAuthority( $authid)
1289 return a hashref in order auth_header table data
1293 sub GetHeaderAuthority
{
1294 my $authid = shift @_;
1295 my $sql= "SELECT * from auth_header WHERE authid = ?";
1296 my $dbh=C4
::Context
->dbh;
1297 my $rq= $dbh->prepare($sql);
1298 $rq->execute($authid);
1299 my $data= $rq->fetchrow_hashref;
1303 =head2 AddAuthorityTrees
1305 $ref= &AddAuthorityTrees( $authid, $trees)
1307 return success or failure
1311 sub AddAuthorityTrees
{
1312 my $authid = shift @_;
1313 my $trees = shift @_;
1314 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1315 my $dbh=C4
::Context
->dbh;
1316 my $rq= $dbh->prepare($sql);
1317 return $rq->execute($trees,$authid);
1323 mergefrom => $mergefrom,
1324 [ MARCfrom => $MARCfrom, ]
1325 [ mergeto => $mergeto, ]
1326 [ MARCto => $MARCto, ]
1327 [ biblionumbers => [ $a, $b, $c ], ]
1328 [ override_limit => 1, ]
1331 Merge biblios linked to authority $mergefrom (mandatory parameter).
1332 If $mergeto equals mergefrom, the linked biblio field is updated.
1333 If $mergeto is different, the biblio field will be linked to $mergeto.
1334 If $mergeto is missing, the biblio field is deleted.
1336 MARCfrom is used to determine if a cleared subfield in the authority record
1337 should be removed from a biblio. MARCto is used to populate the biblio
1338 record with the updated values; if you do not pass it, the biblio field
1339 will be deleted (same as missing mergeto).
1341 Normally all biblio records linked to $mergefrom, will be considered. But
1342 you can pass specific numbers via the biblionumbers parameter.
1344 The parameter override_limit is used by the cron job to force larger
1347 Note: Although $mergefrom and $mergeto will normally be of the same
1348 authority type, merge also supports moving to another authority type.
1353 my ( $params ) = @_;
1354 my $mergefrom = $params->{mergefrom
} || return;
1355 my $MARCfrom = $params->{MARCfrom
};
1356 my $mergeto = $params->{mergeto
};
1357 my $MARCto = $params->{MARCto
};
1358 my $override_limit = $params->{override_limit
};
1360 # If we do not have biblionumbers, we get all linked biblios if the
1361 # number of linked records does not exceed the limit UNLESS we override.
1363 if( $params->{biblionumbers
} ) {
1364 @biblionumbers = @
{ $params->{biblionumbers
} };
1365 } elsif( $override_limit ) {
1366 @biblionumbers = Koha
::Authorities
->linked_biblionumbers({ authid
=> $mergefrom });
1367 } else { # now first check number of linked records
1368 my $max = C4
::Context
->preference('AuthorityMergeLimit') // 0;
1369 my $hits = Koha
::Authorities
->get_usage_count({ authid
=> $mergefrom });
1370 if( $hits > 0 && $hits <= $max ) {
1371 @biblionumbers = Koha
::Authorities
->linked_biblionumbers({ authid
=> $mergefrom });
1372 } elsif( $hits > $max ) { #postpone this merge to the cron job
1373 Koha
::Authority
::MergeRequest
->new({
1374 authid
=> $mergefrom,
1375 oldrecord
=> $MARCfrom,
1376 authid_new
=> $mergeto,
1380 return 0 if !@biblionumbers;
1382 # Search authtypes and reporting tags
1383 my $authfrom = Koha
::Authorities
->find($mergefrom);
1384 my $authto = Koha
::Authorities
->find($mergeto);
1385 my $authtypefrom = $authfrom ? Koha
::Authority
::Types
->find($authfrom->authtypecode) : undef;
1386 my $authtypeto = $authto ? Koha
::Authority
::Types
->find($authto->authtypecode) : undef;
1387 my $auth_tag_to_report_from = $authtypefrom ?
$authtypefrom->auth_tag_to_report : '';
1388 my $auth_tag_to_report_to = $authtypeto ?
$authtypeto->auth_tag_to_report : '';
1391 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1392 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1393 # is empty, make sure that $9 and $a remain (instead of clearing the
1394 # reference) in order to allow for data recovery.
1395 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1396 if( $MARCto && $authtypeto && !@record_to ) {
1397 push @record_to, [ 'a', ' ' ]; # do not remove the space
1401 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1402 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1403 # 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
1404 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1405 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1406 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1409 # Get all candidate tags for the change
1410 # (This will reduce the search scope in marc records).
1411 # For a deleted authority record, we scan all auth controlled fields
1412 my $dbh = C4
::Context
->dbh;
1413 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1414 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<>''" );
1416 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1417 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1420 my $overwrite = C4
::Context
->preference( 'AuthorityMergeMode' ) eq 'strict';
1421 my $skip_subfields = $overwrite
1422 # This hash contains all subfields from the authority report fields
1423 # Including $MARCfrom as well as $MARCto
1424 # We only need it in loose merge mode; replaces the former $exclude
1426 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1428 my $counteditedbiblio = 0;
1429 foreach my $biblionumber ( @biblionumbers ) {
1430 my $marcrecord = GetMarcBiblio
({ biblionumber
=> $biblionumber });
1431 next if !$marcrecord;
1433 foreach my $tagfield (@
$tags_using_authtype) {
1434 my $countfrom = 0; # used in strict mode to remove duplicates
1435 foreach my $field ( $marcrecord->field($tagfield) ) {
1436 my $auth_number = $field->subfield("9"); # link to authority
1437 my $tag = $field->tag();
1438 next if !defined($auth_number) || $auth_number ne $mergefrom;
1440 if ( !$mergeto || !@record_to ||
1441 ( $overwrite && $countfrom > 1 ) ) {
1442 # !mergeto or !record_to indicates a delete
1443 # Other condition: remove this duplicate in strict mode
1444 $marcrecord->delete_field($field);
1448 my $newtag = $tags_new && @
$tags_new
1449 ? _merge_newtag
( $tag, $tags_new )
1451 my $controlled_ind = $authto->controlled_indicators({ record
=> $MARCto, biblio_tag
=> $newtag });
1452 my $field_to = MARC
::Field
->new(
1454 $controlled_ind->{ind1
} // $field->indicator(1),
1455 $controlled_ind->{ind2
} // $field->indicator(2),
1456 9 => $mergeto, # Needed to create field, will be moved
1458 my ( @prefix, @postfix );
1459 if ( !$overwrite ) {
1460 # add subfields back in loose mode, check skip_subfields
1461 # The first extra subfields will be in front of the
1462 # controlled block, the rest at the end.
1463 my $prefix_flag = 1;
1464 foreach my $subfield ( $field->subfields ) {
1465 next if $subfield->[0] eq '9'; # skip but leave flag
1466 if ( $skip_subfields->{ $subfield->[0] } ) {
1467 # This marks the beginning of the controlled block
1472 push @prefix, [ $subfield->[0], $subfield->[1] ];
1474 push @postfix, [ $subfield->[0], $subfield->[1] ];
1478 foreach my $subfield ( @prefix, @record_to, @postfix ) {
1479 $field_to->add_subfields($subfield->[0] => $subfield->[1]);
1481 if( exists $controlled_ind->{sub2
} ) { # thesaurus info
1482 if( defined $controlled_ind->{sub2
} ) {
1484 $field_to->update( 2 => $controlled_ind->{sub2
} );
1486 # Key alerts us here to remove $2
1487 $field_to->delete_subfield( code
=> '2' );
1490 # Move $9 to the end
1491 $field_to->delete_subfield( code
=> '9' );
1492 $field_to->add_subfields( 9 => $mergeto );
1494 if ($tags_new && @
$tags_new) {
1495 $marcrecord->delete_field($field);
1496 append_fields_ordered
( $marcrecord, $field_to );
1498 $field->replace_with($field_to);
1504 ModBiblio
($marcrecord, $biblionumber, GetFrameworkCode
($biblionumber));
1505 $counteditedbiblio++;
1507 return $counteditedbiblio;
1511 # Routine is only called for an (exceptional) authtypecode change
1512 # Fixes old behavior of returning the first tag found
1513 my ( $oldtag, $new_tags ) = @_;
1515 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1516 my $prefix = substr( $oldtag, 0, 1 );
1517 my $guess = $prefix . substr( $new_tags->[0], -2 );
1518 if( grep { $_ eq $guess } @
$new_tags ) {
1521 # Otherwise return one from the same block e.g. 6XX for 650
1522 # If not there too, fall back to first new tag (old behavior!)
1523 my @same_block = grep { /^$prefix/ } @
$new_tags;
1524 return @same_block ?
$same_block[0] : $new_tags->[0];
1527 sub append_fields_ordered
{
1528 # while we lack this function in MARC::Record
1529 # we do not want insert_fields_ordered since it inserts before
1530 my ( $record, $field ) = @_;
1531 if( my @flds = $record->field( $field->tag ) ) {
1532 $record->insert_fields_after( pop @flds, $field );
1533 } else { # now fallback to insert_fields_ordered
1534 $record->insert_fields_ordered( $field );
1538 =head2 get_auth_type_location
1540 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1542 Get the tag and subfield used to store the heading type
1543 for indexing purposes. The C<$auth_type> parameter is
1544 optional; if it is not supplied, assume ''.
1546 This routine searches the MARC authority framework
1547 for the tag and subfield whose kohafield is
1548 C<auth_header.authtypecode>; if no such field is
1549 defined in the framework, default to the hardcoded value
1550 specific to the MARC format.
1554 sub get_auth_type_location
{
1555 my $auth_type_code = @_ ?
shift : '';
1557 my ($tag, $subfield) = GetAuthMARCFromKohaField
('auth_header.authtypecode', $auth_type_code);
1558 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1559 return ($tag, $subfield);
1561 if (C4
::Context
->preference('marcflavour') eq "MARC21") {
1562 return C4
::AuthoritiesMarc
::MARC21
::default_auth_type_location
();
1564 return C4
::AuthoritiesMarc
::UNIMARC
::default_auth_type_location
();
1569 END { } # module clean-up code here (global destructor)
1576 Koha Development Team <http://koha-community.org/>
1578 Paul POULAIN paul.poulain@free.fr