1 package C4
::AuthoritiesMarc
;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26 use C4
::AuthoritiesMarc
::MARC21
;
27 use C4
::AuthoritiesMarc
::UNIMARC
;
30 use Koha
::MetadataRecord
::Authority
;
31 use Koha
::Authorities
;
32 use Koha
::Authority
::MergeRequests
;
33 use Koha
::Authority
::Types
;
36 use Koha
::SearchEngine
;
37 use Koha
::SearchEngine
::Indexer
;
38 use Koha
::SearchEngine
::Search
;
40 use vars
qw(@ISA @EXPORT);
48 &GetAuthMARCFromKohaField
64 &FindDuplicateAuthority
76 =head2 GetAuthMARCFromKohaField
78 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
80 returns tag and subfield linked to kohafield
83 Suppose Kohafield is only linked to ONE subfield
87 sub GetAuthMARCFromKohaField
{
88 #AUTHfind_marc_from_kohafield
89 my ( $kohafield,$authtypecode ) = @_;
90 my $dbh=C4
::Context
->dbh;
91 return 0, 0 unless $kohafield;
92 $authtypecode="" unless $authtypecode;
93 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
94 $sth->execute($kohafield,$authtypecode);
95 my ($tagfield,$tagsubfield) = $sth->fetchrow;
97 return ($tagfield,$tagsubfield);
100 =head2 SearchAuthorities
102 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
103 $excluding, $operator, $value, $offset,$length,$authtypecode,
104 $sortby[, $skipmetadata])
106 returns ref to array result and count of results returned
110 sub SearchAuthorities
{
111 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
112 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
113 my $dbh=C4
::Context
->dbh;
114 $sortby="" unless $sortby;
118 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
119 # the authtypecode. Then, search on $a of this tag_to_report
120 # 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= ZOOM
::Query
::PQF
->new($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 my $indexer = Koha
::SearchEngine
::Indexer
->new({ index => $Koha::SearchEngine
::AUTHORITIES_INDEX
});
633 $indexer->index_records( $authid, "specialUpdate", "authorityserver", $record );
640 DelAuthority({ authid => $authid, [ skip_merge => 1 ] });
642 Deletes $authid and calls merge to cleanup linked biblio records.
643 Parameter skip_merge is used in authorities/merge.pl. You should normally not
650 my $authid = $params->{authid
} || return;
651 my $skip_merge = $params->{skip_merge
};
652 my $dbh = C4
::Context
->dbh;
654 # Remove older pending merge requests for $authid to itself. (See bug 22437)
655 my $condition = { authid
=> $authid, authid_new
=> [undef, 0, $authid], done
=> 0 };
656 Koha
::Authority
::MergeRequests
->search($condition)->delete;
658 merge
({ mergefrom
=> $authid }) if !$skip_merge;
659 $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
660 logaction
( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4
::Context
->preference("AuthoritiesLog");
661 my $indexer = Koha
::SearchEngine
::Indexer
->new({ index => $Koha::SearchEngine
::AUTHORITIES_INDEX
});
662 $indexer->index_records( $authid, "recordDelete", "authorityserver", undef );
667 $authid= &ModAuthority($authid,$record,$authtypecode)
669 Modifies authority record, optionally updates attached biblios.
674 my ( $authid, $record, $authtypecode ) = @_;
675 my $oldrecord = GetAuthority
($authid);
676 #Now rewrite the $record to table with an add
677 $authid = AddAuthority
($record, $authid, $authtypecode);
678 merge
({ mergefrom
=> $authid, MARCfrom
=> $oldrecord, mergeto
=> $authid, MARCto
=> $record });
679 logaction
( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4
::Context
->preference("AuthoritiesLog");
683 =head2 GetAuthorityXML
685 $marcxml= &GetAuthorityXML( $authid)
687 returns xml form of record $authid
691 sub GetAuthorityXML
{
692 # Returns MARC::XML of the authority passed in parameter.
694 if (uc(C4
::Context
->preference('marcflavour')) eq 'UNIMARC') {
695 my $dbh=C4
::Context
->dbh;
696 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
697 $sth->execute($authid);
698 my ($marcxml)=$sth->fetchrow;
702 # for MARC21, call GetAuthority instead of
703 # getting the XML directly since we may
704 # need to fix up the location of the authority
705 # code -- note that this is reasonably safe
706 # because GetAuthorityXML is used only by the
707 # indexing processes like zebraqueue_start.pl
708 my $record = GetAuthority
($authid);
709 return $record->as_xml_record('MARC21');
715 $record= &GetAuthority( $authid)
717 Returns MARC::Record of the authority passed in parameter.
723 my $authority = Koha
::MetadataRecord
::Authority
->get_from_authid($authid);
724 return unless $authority;
725 return ($authority->record);
728 =head2 FindDuplicateAuthority
730 $record= &FindDuplicateAuthority( $record, $authtypecode)
732 return $authid,Summary if duplicate is found.
734 Comments : an improvement would be to return All the records that match.
738 sub FindDuplicateAuthority
{
740 my ($record,$authtypecode)=@_;
741 # warn "IN for ".$record->as_formatted;
742 my $dbh = C4
::Context
->dbh;
743 # warn "".$record->as_formatted;
744 my $auth_tag_to_report = Koha
::Authority
::Types
->find($authtypecode)->auth_tag_to_report;
745 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
746 # build a request for SearchAuthorities
748 $authtypecode =~ s
#/#\\/#; # GENRE/FORM contains forward slash which is a reserved character
749 my $query='at:'.$authtypecode.' ';
750 my $filtervalues=qr
([\001-\040\Q
!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
751 if ($record->field($auth_tag_to_report)) {
752 foreach ($record->field($auth_tag_to_report)->subfields()) {
753 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
756 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
757 my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver
' ] );
758 # there is at least 1 result => return the 1st one
759 if (!defined $error && @{$results} ) {
760 my $marcrecord = C4::Search::new_record_from_zebra(
764 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
766 # no result, returns nothing
772 $summary= &BuildSummary( $record, $authid, $authtypecode)
774 Returns a hashref with a summary of the specified record.
776 Comment : authtypecode can be inferred from both record and authid.
777 Moreover, authid can also be inferred from $record.
778 Would it be interesting to delete those things.
783 ## give this a Marc record to return summary
784 my ($record,$authid,$authtypecode)=@_;
785 my $dbh=C4::Context->dbh;
787 my $summary_template;
788 # handle $authtypecode is NULL or eq ""
790 my $authref = Koha::Authority::Types->find($authtypecode);
792 $summary{authtypecode} = $authref->authtypecode;
793 $summary{type} = $authref->authtypetext;
794 $summary_template = $authref->summary;
795 # for MARC21, the authority type summary displays a label meant for
797 if (C4::Context->preference('marcflavour
') ne 'UNIMARC
') {
798 $summary{label} = $authref->summary;
800 $summary{summary} = $authref->summary;
804 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68
';
805 my %marc21controlrefs = ( 'a
' => 'earlier
',
811 'n
' => 'notapplicable
',
815 my %unimarc_relation_from_code = (
821 $thesaurus{'1'}="Peuples";
822 $thesaurus{'2'}="Anthroponymes";
823 $thesaurus{'3'}="Oeuvres";
824 $thesaurus{'4'}="Chronologie";
825 $thesaurus{'5'}="Lieux";
826 $thesaurus{'6'}="Sujets";
829 # if the library has a summary defined, use it. Otherwise, build a standard one
830 # FIXME - it appears that the summary field in the authority frameworks
831 # can work as a display template. However, this doesn't
832 # suit the MARC21 version, so for now the "templating"
833 # feature will be enabled only for UNIMARC for backwards
835 if ($summary{summary
} and C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
836 my @matches = ($summary{summary
} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
837 my (@textbefore, @tag, @subtag, @textafter);
838 for(my $i = 0; $i < scalar @matches; $i++){
839 push @textbefore, $matches[$i] if($i%4 == 0);
840 push @tag, $matches[$i] if($i%4 == 1);
841 push @subtag, $matches[$i] if($i%4 == 2);
842 push @textafter, $matches[$i] if($i%4 == 3);
844 for(my $i = scalar @tag; $i >= 0; $i--){
845 my $textbefore = $textbefore[$i] || '';
846 my $tag = $tag[$i] || '';
847 my $subtag = $subtag[$i] || '';
848 my $textafter = $textafter[$i] || '';
850 my $field = $record->field($tag);
854 $value = $textbefore . $field->data() . $textafter;
857 my @subfields = $field->subfield($subtag);
859 $value = $textbefore . join (" - ", @subfields) . $textafter;
863 $summary{summary
} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
865 $summary{summary
} =~ s/\\n/<br \/>/g
;
872 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
873 # construct UNIMARC summary, that is quite different from MARC21 one
875 foreach my $field ($record->field('2..')) {
877 heading
=> $field->as_string('abcdefghijlmnopqrstuvwxyz'),
878 hemain
=> ( $field->subfield('a') // undef ),
879 field
=> $field->tag(),
883 foreach my $field ($record->field('3..')) {
884 push @notes, { note
=> $field->subfield('a'), field
=> $field->tag() };
886 foreach my $field ($record->field('4..')) {
887 my $thesaurus = $field->subfield('2') ?
"thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
889 heading
=> $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
890 hemain
=> ( $field->subfield('a') // undef ),
892 field
=> $field->tag(),
898 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
899 my $heading = $_->as_string('abcdefgjxyz');
904 hemain
=> ( $_->subfield('a') // undef ),
906 authid
=> ( $_->subfield('9') // undef ),
908 } $record->field('5..');
911 @otherscript = map { {
912 lang
=> length ($_->subfield('8')) == 6 ?
substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
913 term
=> $_->subfield('a') . ($_->subfield('b') ?
', ' . $_->subfield('b') : ''),
916 } } $record->field('7..');
919 # construct MARC21 summary
920 # FIXME - looping over 1XX is questionable
921 # since MARC21 authority should have only one 1XX
922 my $subfields_to_report;
923 foreach my $field ($record->field('1..')) {
924 my $tag = $field->tag();
925 next if "152" eq $tag;
926 # FIXME - 152 is not a good tag to use
927 # in MARC21 -- purely local tags really ought to be
930 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
931 } elsif ($tag eq '110') {
932 $subfields_to_report = 'abcdefghklmnoprstvxyz';
933 } elsif ($tag eq '111') {
934 $subfields_to_report = 'acdefghklnpqstvxyz';
935 } elsif ($tag eq '130') {
936 $subfields_to_report = 'adfghklmnoprstvxyz';
937 } elsif ($tag eq '148') {
938 $subfields_to_report = 'abvxyz';
939 } elsif ($tag eq '150') {
940 $subfields_to_report = 'abvxyz';
941 } elsif ($tag eq '151') {
942 $subfields_to_report = 'avxyz';
943 } elsif ($tag eq '155') {
944 $subfields_to_report = 'abvxyz';
945 } elsif ($tag eq '180') {
946 $subfields_to_report = 'vxyz';
947 } elsif ($tag eq '181') {
948 $subfields_to_report = 'vxyz';
949 } elsif ($tag eq '182') {
950 $subfields_to_report = 'vxyz';
951 } elsif ($tag eq '185') {
952 $subfields_to_report = 'vxyz';
954 if ($subfields_to_report) {
956 heading
=> $field->as_string($subfields_to_report),
957 hemain
=> ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
962 heading
=> $field->as_string(),
963 hemain
=> ( $field->subfield( 'a' ) // undef ),
968 foreach my $field ($record->field('4..')) { #See From
969 my $type = 'seefrom';
970 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
971 if ($type eq 'notapplicable') {
972 $type = substr $field->subfield('w'), 2, 1;
973 $type = 'earlier' if $type && $type ne 'n';
975 if ($type eq 'subfi') {
977 heading
=> $field->as_string($marc21subfields),
978 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
979 type
=> ($field->subfield('i') || ''),
980 field
=> $field->tag(),
984 heading
=> $field->as_string($marc21subfields),
985 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
987 field
=> $field->tag(),
991 foreach my $field ($record->field('5..')) { #See Also
992 my $type = 'seealso';
993 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
994 if ($type eq 'notapplicable') {
995 $type = substr $field->subfield('w'), 2, 1;
996 $type = 'earlier' if $type && $type ne 'n';
998 if ($type eq 'subfi') {
1000 heading
=> $field->as_string($marc21subfields),
1001 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1002 type
=> scalar $field->subfield('i'),
1003 field
=> $field->tag(),
1004 search
=> $field->as_string($marc21subfields) || '',
1005 authid
=> $field->subfield('9') || ''
1009 heading
=> $field->as_string($marc21subfields),
1010 hemain
=> scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1012 field
=> $field->tag(),
1013 search
=> $field->as_string($marc21subfields) || '',
1014 authid
=> $field->subfield('9') || ''
1018 foreach my $field ($record->field('6..')) {
1019 push @notes, { note
=> $field->as_string(), field
=> $field->tag() };
1021 foreach my $field ($record->field('880')) {
1022 my $linkage = $field->subfield('6');
1023 my $category = substr $linkage, 0, 1;
1024 if ($category eq '1') {
1025 $category = 'preferred';
1026 } elsif ($category eq '4') {
1027 $category = 'seefrom';
1028 } elsif ($category eq '5') {
1029 $category = 'seealso';
1032 if ($field->subfield('w')) {
1033 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1037 my $direction = $linkage =~ m
#/r$# ? 'rtl' : 'ltr';
1038 push @otherscript, { term
=> $field->as_string($subfields_to_report), category
=> $category, type
=> $type, direction
=> $direction, linkage
=> $linkage };
1041 $summary{mainentry
} = $authorized[0]->{heading
};
1042 $summary{mainmainentry
} = $authorized[0]->{hemain
};
1043 $summary{authorized
} = \
@authorized;
1044 $summary{notes
} = \
@notes;
1045 $summary{seefrom
} = \
@seefrom;
1046 $summary{seealso
} = \
@seealso;
1047 $summary{otherscript
} = \
@otherscript;
1051 =head2 GetAuthorizedHeading
1053 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1055 Takes a MARC::Record object describing an authority record or an authid, and
1056 returns a string representation of the first authorized heading. This routine
1057 should be considered a temporary shim to ease the future migration of authority
1058 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1062 sub GetAuthorizedHeading
{
1065 unless ($record = $args->{record
}) {
1066 return unless $args->{authid
};
1067 $record = GetAuthority
($args->{authid
});
1069 return unless (ref $record eq 'MARC::Record');
1070 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
1071 # construct UNIMARC summary, that is quite different from MARC21 one
1073 foreach my $field ($record->field('2..')) {
1074 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1077 foreach my $field ($record->field('1..')) {
1078 my $tag = $field->tag();
1079 next if "152" eq $tag;
1080 # FIXME - 152 is not a good tag to use
1081 # in MARC21 -- purely local tags really ought to be
1083 if ($tag eq '100') {
1084 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1085 } elsif ($tag eq '110') {
1086 return $field->as_string('abcdefghklmnoprstvxyz68');
1087 } elsif ($tag eq '111') {
1088 return $field->as_string('acdefghklnpqstvxyz68');
1089 } elsif ($tag eq '130') {
1090 return $field->as_string('adfghklmnoprstvxyz68');
1091 } elsif ($tag eq '148') {
1092 return $field->as_string('abvxyz68');
1093 } elsif ($tag eq '150') {
1094 return $field->as_string('abvxyz68');
1095 } elsif ($tag eq '151') {
1096 return $field->as_string('avxyz68');
1097 } elsif ($tag eq '155') {
1098 return $field->as_string('abvxyz68');
1099 } elsif ($tag eq '180') {
1100 return $field->as_string('vxyz68');
1101 } elsif ($tag eq '181') {
1102 return $field->as_string('vxyz68');
1103 } elsif ($tag eq '182') {
1104 return $field->as_string('vxyz68');
1105 } elsif ($tag eq '185') {
1106 return $field->as_string('vxyz68');
1108 return $field->as_string();
1115 =head2 BuildAuthHierarchies
1117 $text= &BuildAuthHierarchies( $authid, $force)
1119 return text containing trees for hierarchies
1120 for them to be stored in auth_header
1123 122,1314,2452;1324,2342,3,2452
1127 sub BuildAuthHierarchies
{
1128 my $authid = shift @_;
1129 # warn "authid : $authid";
1130 my $force = shift @_ || (C4
::Context
->preference('marcflavour') eq 'UNIMARC' ?
0 : 1);
1132 my $dbh=C4
::Context
->dbh;
1134 my $data = GetHeaderAuthority
($authid);
1135 if ($data->{'authtrees'} and not $force){
1136 return $data->{'authtrees'};
1137 # } elsif ($data->{'authtrees'}){
1138 # $hierarchies=$data->{'authtrees'};
1140 my $record = GetAuthority
($authid);
1142 return unless $record;
1143 foreach my $field ($record->field('5..')){
1146 (C4
::Context
->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1147 (C4
::Context
->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1149 my $subfauthid=_get_authid_subfield
($field) || '';
1150 next if ($subfauthid eq $authid);
1151 my $parentrecord = GetAuthority
($subfauthid);
1152 next unless $parentrecord;
1153 my $localresult=$hierarchies;
1155 $trees = BuildAuthHierarchies
($subfauthid);
1158 @trees = split(/;/,$trees);
1160 push @trees, $trees;
1165 @globalresult = (@globalresult,@trees);
1168 $hierarchies=join(";",@globalresult);
1170 #Unless there is no ancestor, I am alone.
1171 $hierarchies="$authid" unless ($hierarchies);
1173 AddAuthorityTrees
($authid,$hierarchies);
1174 return $hierarchies;
1177 =head2 BuildAuthHierarchy
1179 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1181 return a hashref in order to display hierarchy for record and final Authid $authid
1192 sub BuildAuthHierarchy
{
1193 my $record = shift @_;
1194 my $class = shift @_;
1195 my $authid_constructed = shift @_;
1196 return unless ($record && $record->field('001'));
1197 my $authid=$record->field('001')->data();
1199 my $parents=""; my $children="";
1200 my (@loopparents,@loopchildren);
1201 my $marcflavour = C4
::Context
->preference('marcflavour');
1202 my $relationshipsf = $marcflavour eq 'UNIMARC' ?
'5' : 'w';
1203 foreach my $field ($record->field('5..')){
1204 my $subfauthid=_get_authid_subfield
($field);
1205 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1206 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1207 if ($relationship eq 'h'){
1208 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1210 elsif ($relationship eq 'g'){
1211 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1213 # brothers could get in there with an else
1216 $cell{"parents"}=\
@loopparents;
1217 $cell{"children"}=\
@loopchildren;
1218 $cell{"class"}=$class;
1219 $cell{"authid"}=$authid;
1220 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1221 $cell{"value"}=C4
::Context
->preference('marcflavour') eq 'UNIMARC' ?
$record->subfield('2..',"a") : $record->subfield('1..', 'a');
1225 =head2 BuildAuthHierarchyBranch
1227 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1229 Return a data structure representing an authority hierarchy
1230 given a list of authorities representing a single branch in
1231 an authority hierarchy tree. $authid is the current node in
1232 the tree (which may or may not be somewhere in the middle).
1233 $cnt represents the level of the upper-most item, and is only
1234 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1235 don't ever pass in anything but zero to it).
1239 sub BuildAuthHierarchyBranch
{
1240 my ($tree, $authid, $cnt) = @_;
1242 my $elementdata = GetAuthority
(shift @
$tree);
1243 my $branch = BuildAuthHierarchy
($elementdata,"child".$cnt, $authid);
1244 if (scalar @
$tree > 0) {
1245 my $nextBranch = BuildAuthHierarchyBranch
($tree, $authid, ++$cnt);
1246 my $nextAuthid = $nextBranch->{authid
};
1248 # If we already have the next branch listed as a child, let's
1249 # replace the old listing with the new one. If not, we will add
1250 # the branch at the end.
1251 foreach my $cell (@
{$branch->{children
}}) {
1252 if ($cell->{authid
} eq $nextAuthid) {
1253 $cell = $nextBranch;
1258 push @
{$branch->{children
}}, $nextBranch unless $found;
1263 =head2 GenerateHierarchy
1265 $hierarchy = &GenerateHierarchy($authid);
1267 Return an arrayref holding one or more "trees" representing
1268 authority hierarchies.
1272 sub GenerateHierarchy
{
1274 my $trees = BuildAuthHierarchies
($authid);
1275 my @trees = split /;/,$trees ;
1276 push @trees,$trees unless (@trees);
1277 my @loophierarchies;
1278 foreach my $tree (@trees){
1279 my @tree=split /,/,$tree;
1280 push @tree, $tree unless (@tree);
1281 my $branch = BuildAuthHierarchyBranch
(\
@tree, $authid);
1282 push @loophierarchies, [ $branch ];
1284 return \
@loophierarchies;
1287 sub _get_authid_subfield
{
1289 return $field->subfield('9')||$field->subfield('3');
1292 =head2 GetHeaderAuthority
1294 $ref= &GetHeaderAuthority( $authid)
1296 return a hashref in order auth_header table data
1300 sub GetHeaderAuthority
{
1301 my $authid = shift @_;
1302 my $sql= "SELECT * from auth_header WHERE authid = ?";
1303 my $dbh=C4
::Context
->dbh;
1304 my $rq= $dbh->prepare($sql);
1305 $rq->execute($authid);
1306 my $data= $rq->fetchrow_hashref;
1310 =head2 AddAuthorityTrees
1312 $ref= &AddAuthorityTrees( $authid, $trees)
1314 return success or failure
1318 sub AddAuthorityTrees
{
1319 my $authid = shift @_;
1320 my $trees = shift @_;
1321 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1322 my $dbh=C4
::Context
->dbh;
1323 my $rq= $dbh->prepare($sql);
1324 return $rq->execute($trees,$authid);
1330 mergefrom => $mergefrom,
1331 [ MARCfrom => $MARCfrom, ]
1332 [ mergeto => $mergeto, ]
1333 [ MARCto => $MARCto, ]
1334 [ biblionumbers => [ $a, $b, $c ], ]
1335 [ override_limit => 1, ]
1338 Merge biblios linked to authority $mergefrom (mandatory parameter).
1339 If $mergeto equals mergefrom, the linked biblio field is updated.
1340 If $mergeto is different, the biblio field will be linked to $mergeto.
1341 If $mergeto is missing, the biblio field is deleted.
1343 MARCfrom is used to determine if a cleared subfield in the authority record
1344 should be removed from a biblio. MARCto is used to populate the biblio
1345 record with the updated values; if you do not pass it, the biblio field
1346 will be deleted (same as missing mergeto).
1348 Normally all biblio records linked to $mergefrom, will be considered. But
1349 you can pass specific numbers via the biblionumbers parameter.
1351 The parameter override_limit is used by the cron job to force larger
1354 Note: Although $mergefrom and $mergeto will normally be of the same
1355 authority type, merge also supports moving to another authority type.
1360 my ( $params ) = @_;
1361 my $mergefrom = $params->{mergefrom
} || return;
1362 my $MARCfrom = $params->{MARCfrom
};
1363 my $mergeto = $params->{mergeto
};
1364 my $MARCto = $params->{MARCto
};
1365 my $override_limit = $params->{override_limit
};
1367 # If we do not have biblionumbers, we get all linked biblios if the
1368 # number of linked records does not exceed the limit UNLESS we override.
1370 if( $params->{biblionumbers
} ) {
1371 @biblionumbers = @
{ $params->{biblionumbers
} };
1372 } elsif( $override_limit ) {
1373 @biblionumbers = Koha
::Authorities
->linked_biblionumbers({ authid
=> $mergefrom });
1374 } else { # now first check number of linked records
1375 my $max = C4
::Context
->preference('AuthorityMergeLimit') // 0;
1376 my $hits = Koha
::Authorities
->get_usage_count({ authid
=> $mergefrom });
1377 if( $hits > 0 && $hits <= $max ) {
1378 @biblionumbers = Koha
::Authorities
->linked_biblionumbers({ authid
=> $mergefrom });
1379 } elsif( $hits > $max ) { #postpone this merge to the cron job
1380 Koha
::Authority
::MergeRequest
->new({
1381 authid
=> $mergefrom,
1382 oldrecord
=> $MARCfrom,
1383 authid_new
=> $mergeto,
1387 return 0 if !@biblionumbers;
1389 # Search authtypes and reporting tags
1390 my $authfrom = Koha
::Authorities
->find($mergefrom);
1391 my $authto = Koha
::Authorities
->find($mergeto);
1392 my $authtypefrom = $authfrom ? Koha
::Authority
::Types
->find($authfrom->authtypecode) : undef;
1393 my $authtypeto = $authto ? Koha
::Authority
::Types
->find($authto->authtypecode) : undef;
1394 my $auth_tag_to_report_from = $authtypefrom ?
$authtypefrom->auth_tag_to_report : '';
1395 my $auth_tag_to_report_to = $authtypeto ?
$authtypeto->auth_tag_to_report : '';
1398 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1399 # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1400 # is empty, make sure that $9 and $a remain (instead of clearing the
1401 # reference) in order to allow for data recovery.
1402 # Note: We need $a too, since a single $9 does not pass ModBiblio.
1403 if( $MARCto && $authtypeto && !@record_to ) {
1404 push @record_to, [ 'a', ' ' ]; # do not remove the space
1408 if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1409 # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1410 # 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
1411 @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1412 } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1413 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1416 # Get all candidate tags for the change
1417 # (This will reduce the search scope in marc records).
1418 # For a deleted authority record, we scan all auth controlled fields
1419 my $dbh = C4
::Context
->dbh;
1420 my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1421 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<>''" );
1423 if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1424 $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1427 my $overwrite = C4
::Context
->preference( 'AuthorityMergeMode' ) eq 'strict';
1428 my $skip_subfields = $overwrite
1429 # This hash contains all subfields from the authority report fields
1430 # Including $MARCfrom as well as $MARCto
1431 # We only need it in loose merge mode; replaces the former $exclude
1433 : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1435 my $counteditedbiblio = 0;
1436 foreach my $biblionumber ( @biblionumbers ) {
1437 my $marcrecord = GetMarcBiblio
({ biblionumber
=> $biblionumber });
1438 next if !$marcrecord;
1440 foreach my $tagfield (@
$tags_using_authtype) {
1441 my $countfrom = 0; # used in strict mode to remove duplicates
1442 foreach my $field ( $marcrecord->field($tagfield) ) {
1443 my $auth_number = $field->subfield("9"); # link to authority
1444 my $tag = $field->tag();
1445 next if !defined($auth_number) || $auth_number ne $mergefrom;
1447 if ( !$mergeto || !@record_to ||
1448 ( $overwrite && $countfrom > 1 ) ) {
1449 # !mergeto or !record_to indicates a delete
1450 # Other condition: remove this duplicate in strict mode
1451 $marcrecord->delete_field($field);
1455 my $newtag = $tags_new && @
$tags_new
1456 ? _merge_newtag
( $tag, $tags_new )
1458 my $controlled_ind = $authto->controlled_indicators({ record
=> $MARCto, biblio_tag
=> $newtag });
1459 my $field_to = MARC
::Field
->new(
1461 $controlled_ind->{ind1
} // $field->indicator(1),
1462 $controlled_ind->{ind2
} // $field->indicator(2),
1463 9 => $mergeto, # Needed to create field, will be moved
1465 my ( @prefix, @postfix );
1466 if ( !$overwrite ) {
1467 # add subfields back in loose mode, check skip_subfields
1468 # The first extra subfields will be in front of the
1469 # controlled block, the rest at the end.
1470 my $prefix_flag = 1;
1471 foreach my $subfield ( $field->subfields ) {
1472 next if $subfield->[0] eq '9'; # skip but leave flag
1473 if ( $skip_subfields->{ $subfield->[0] } ) {
1474 # This marks the beginning of the controlled block
1479 push @prefix, [ $subfield->[0], $subfield->[1] ];
1481 push @postfix, [ $subfield->[0], $subfield->[1] ];
1485 foreach my $subfield ( @prefix, @record_to, @postfix ) {
1486 $field_to->add_subfields($subfield->[0] => $subfield->[1]);
1488 if( exists $controlled_ind->{sub2
} ) { # thesaurus info
1489 if( defined $controlled_ind->{sub2
} ) {
1491 $field_to->update( 2 => $controlled_ind->{sub2
} );
1493 # Key alerts us here to remove $2
1494 $field_to->delete_subfield( code
=> '2' );
1497 # Move $9 to the end
1498 $field_to->delete_subfield( code
=> '9' );
1499 $field_to->add_subfields( 9 => $mergeto );
1501 if ($tags_new && @
$tags_new) {
1502 $marcrecord->delete_field($field);
1503 append_fields_ordered
( $marcrecord, $field_to );
1505 $field->replace_with($field_to);
1511 ModBiblio
($marcrecord, $biblionumber, GetFrameworkCode
($biblionumber));
1512 $counteditedbiblio++;
1514 return $counteditedbiblio;
1518 # Routine is only called for an (exceptional) authtypecode change
1519 # Fixes old behavior of returning the first tag found
1520 my ( $oldtag, $new_tags ) = @_;
1522 # If we e.g. have 650 and 151,651,751 try 651 and check presence
1523 my $prefix = substr( $oldtag, 0, 1 );
1524 my $guess = $prefix . substr( $new_tags->[0], -2 );
1525 if( grep { $_ eq $guess } @
$new_tags ) {
1528 # Otherwise return one from the same block e.g. 6XX for 650
1529 # If not there too, fall back to first new tag (old behavior!)
1530 my @same_block = grep { /^$prefix/ } @
$new_tags;
1531 return @same_block ?
$same_block[0] : $new_tags->[0];
1534 sub append_fields_ordered
{
1535 # while we lack this function in MARC::Record
1536 # we do not want insert_fields_ordered since it inserts before
1537 my ( $record, $field ) = @_;
1538 if( my @flds = $record->field( $field->tag ) ) {
1539 $record->insert_fields_after( pop @flds, $field );
1540 } else { # now fallback to insert_fields_ordered
1541 $record->insert_fields_ordered( $field );
1545 =head2 get_auth_type_location
1547 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1549 Get the tag and subfield used to store the heading type
1550 for indexing purposes. The C<$auth_type> parameter is
1551 optional; if it is not supplied, assume ''.
1553 This routine searches the MARC authority framework
1554 for the tag and subfield whose kohafield is
1555 C<auth_header.authtypecode>; if no such field is
1556 defined in the framework, default to the hardcoded value
1557 specific to the MARC format.
1561 sub get_auth_type_location
{
1562 my $auth_type_code = @_ ?
shift : '';
1564 my ($tag, $subfield) = GetAuthMARCFromKohaField
('auth_header.authtypecode', $auth_type_code);
1565 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1566 return ($tag, $subfield);
1568 if (C4
::Context
->preference('marcflavour') eq "MARC21") {
1569 return C4
::AuthoritiesMarc
::MARC21
::default_auth_type_location
();
1571 return C4
::AuthoritiesMarc
::UNIMARC
::default_auth_type_location
();
1576 END { } # module clean-up code here (global destructor)
1583 Koha Development Team <http://koha-community.org/>
1585 Paul POULAIN paul.poulain@free.fr