1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
31 use vars qw($VERSION @ISA @EXPORT);
34 # set the version for version checking
35 $VERSION = 3.07.00.049;
43 &GetAuthMARCFromKohaField
61 &FindDuplicateAuthority
73 =head2 GetAuthMARCFromKohaField
75 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
77 returns tag and subfield linked to kohafield
80 Suppose Kohafield is only linked to ONE subfield
84 sub GetAuthMARCFromKohaField {
85 #AUTHfind_marc_from_kohafield
86 my ( $kohafield,$authtypecode ) = @_;
87 my $dbh=C4::Context->dbh;
88 return 0, 0 unless $kohafield;
89 $authtypecode="" unless $authtypecode;
90 my $marcfromkohafield;
91 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
92 $sth->execute($kohafield,$authtypecode);
93 my ($tagfield,$tagsubfield) = $sth->fetchrow;
95 return ($tagfield,$tagsubfield);
98 =head2 SearchAuthorities
100 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
101 $excluding, $operator, $value, $offset,$length,$authtypecode,
102 $sortby[, $skipmetadata])
104 returns ref to array result and count of results returned
108 sub SearchAuthorities {
109 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
110 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
111 my $dbh=C4::Context->dbh;
112 if (C4::Context->preference('NoZebra')) {
118 my @auths=split / /,$authtypecode ;
119 foreach my $auth (@auths){
120 $query .="AND auth_type= $auth ";
124 for(my $i = 0 ; $i <= $#{$value} ; $i++)
127 if (@$tags[$i] =~/mainentry|mainmainentry/) {
128 $query .= qq( AND @$tags[$i] );
132 if (@$operator[$i] eq 'is') {
133 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
134 }elsif (@$operator[$i] eq "="){
135 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
136 }elsif (@$operator[$i] eq "start"){
137 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
139 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
145 # do the query (if we had some search term
148 # warn "QUERY : $query";
149 my $result = C4::Search::NZanalyse($query,'authorityserver');
150 # warn "result : $result";
152 foreach (split /;/,$result) {
153 my ($authid,$title) = split /,/,$_;
154 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
155 # and we don't want to get only 1 result for each of them !!!
156 # hint & speed improvement : we can order without reading the record
157 # so order, and read records only for the requested page !
158 $result{$title.$authid}=$authid;
160 # sort the hash and return the same structure as GetRecords (Zebra querying)
163 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
164 foreach my $key (sort {$b cmp $a} (keys %result)) {
165 push @listresult, $result{$key};
166 # warn "push..."$#finalresult;
169 } else { # sort by mainmainentry ASC
170 foreach my $key (sort (keys %result)) {
171 push @listresult, $result{$key};
172 # warn "push..."$#finalresult;
176 # limit the $results_per_page to result size if it's more
177 $length = $numbers-$offset if $numbers < ($offset+$length);
178 # for the requested page, replace authid by the complete record
179 # speed improvement : avoid reading too much things
181 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
182 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
183 my $separator=C4::Context->preference('authoritysep');
184 my $authrecord =GetAuthority($listresult[$counter]);
185 my $authid=$listresult[$counter];
186 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
187 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
188 my $sth = $dbh->prepare($query_auth_tag);
189 $sth->execute($authtypecode);
190 my $auth_tag_to_report = $sth->fetchrow;
192 $newline{used}=CountUsage($authid);
193 $newline{summary} = $summary;
194 $newline{authid} = $authid;
195 $newline{even} = $counter % 2;
196 push @finalresult, \%newline;
198 return (\@finalresult, $numbers);
205 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
206 # the authtypecode. Then, search on $a of this tag_to_report
207 # also store main entry MARC tag, to extract it at end of search
209 ##first set the authtype search and may be multiple authorities
213 my @auths=split / /,$authtypecode ;
214 foreach my $auth (@auths){
215 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
216 push @authtypecode ,$auth;
220 while ($n>1){$query= "\@or ".$query;$n--;}
228 for(my $i = 0 ; $i <= $#{$value} ; $i++)
231 if ( @$tags[$i] eq "mainmainentry" ) {
232 $attr = " \@attr 1=Heading-Main ";
234 elsif ( @$tags[$i] eq "mainentry" ) {
235 $attr = " \@attr 1=Heading ";
237 elsif ( @$tags[$i] eq "match" ) {
238 $attr = " \@attr 1=Match ";
240 elsif ( @$tags[$i] eq "match-heading" ) {
241 $attr = " \@attr 1=Match-heading ";
243 elsif ( @$tags[$i] eq "see-from" ) {
244 $attr = " \@attr 1=Match-heading-see-from ";
246 elsif ( @$tags[$i] eq "thesaurus" ) {
247 $attr = " \@attr 1=Subject-heading-thesaurus ";
249 else { # Assume any if no index was specified
250 $attr = " \@attr 1=Any ";
252 if ( @$operator[$i] eq 'is' ) {
253 $attr .= " \@attr 4=1 \@attr 5=100 "
254 ; ##Phrase, No truncation,all of subfield field must match
256 elsif ( @$operator[$i] eq "=" ) {
257 $attr .= " \@attr 4=107 "; #Number Exact match
259 elsif ( @$operator[$i] eq "start" ) {
260 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
261 ; #Firstinfield Phrase, Right truncated
263 elsif ( @$operator[$i] eq "exact" ) {
264 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
265 ; ##Phrase, No truncation,all of subfield field must match
268 $attr .= " \@attr 5=1 \@attr 4=6 "
269 ; ## Word list, right truncated, anywhere
270 if ($sortby eq 'Relevance') {
271 $attr .= "\@attr 2=102 ";
274 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
275 $attr =$attr."\"".@$value[$i]."\"";
281 ##Add how many queries generated
282 if (defined $query && $query=~/\S+/){
283 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
288 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
290 if ($sortby eq 'HeadingAsc') {
291 $orderstring = '@attr 7=1 @attr 1=Heading 0';
292 } elsif ($sortby eq 'HeadingDsc') {
293 $orderstring = '@attr 7=2 @attr 1=Heading 0';
294 } elsif ($sortby eq 'AuthidAsc') {
295 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
296 } elsif ($sortby eq 'AuthidDsc') {
297 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
299 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
300 $query="\@or $orderstring $query" if $orderstring;
302 $offset=0 unless $offset;
303 my $counter = $offset;
304 $length=10 unless $length;
307 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
308 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
310 $oAResult= $oAuth[0]->search($Anewq) ;
311 while (($i = ZOOM::event(\@oAuth)) != 0) {
312 my $ev = $oAuth[$i-1]->last_event();
313 last if $ev == ZOOM::Event::ZEND;
315 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
317 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
322 $nbresults=$oAResult->size();
323 my $nremains=$nbresults;
325 my @finalresult = ();
329 ##Find authid and linkid fields
330 ##we may be searching multiple authoritytypes.
331 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
332 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
333 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
334 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
336 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
337 my $rec=$oAResult->record($counter);
338 my $marcdata=$rec->raw();
340 my $separator=C4::Context->preference('authoritysep');
341 $authrecord = MARC::File::USMARC::decode($marcdata);
342 my $authid=$authrecord->field('001')->data();
344 $newline{authid} = $authid;
345 if ( !$skipmetadata ) {
347 BuildSummary( $authrecord, $authid, $authtypecode );
349 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
350 my $sth = $dbh->prepare($query_auth_tag);
351 $sth->execute($authtypecode);
352 my $auth_tag_to_report = $sth->fetchrow;
354 my $mainentry = $authrecord->field($auth_tag_to_report);
357 foreach ( $mainentry->subfields() ) {
358 $reported_tag .= '$' . $_->[0] . $_->[1];
361 my $thisauthtype = GetAuthType(GetAuthTypeCode($authid));
362 unless (defined $thisauthtype) {
363 $thisauthtype = GetAuthType($authtypecode) if $authtypecode;
365 $newline{authtype} = defined($thisauthtype) ?
366 $thisauthtype->{'authtypetext'} : '';
367 $newline{summary} = $summary;
368 $newline{even} = $counter % 2;
369 $newline{reported_tag} = $reported_tag;
372 push @finalresult, \%newline;
375 if (! $skipmetadata) {
376 for (my $z=0; $z<@finalresult; $z++){
377 my $count=CountUsage($finalresult[$z]{authid});
378 $finalresult[$z]{used}=$count;
384 $oAResult->destroy();
385 # $oAuth[0]->destroy();
387 return (\@finalresult, $nbresults);
393 $count= &CountUsage($authid)
395 counts Usage of Authid in bibliorecords.
401 if (C4::Context->preference('NoZebra')) {
402 # Read the index Koha-Auth-Number for this authid and count the lines
403 my $result = C4::Search::NZanalyse("an=$authid");
404 my @tab = split /;/,$result;
409 $query= "an=".$authid;
410 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
412 warn "Error: $err from search $query";
420 =head2 CountUsageChildren
422 $count= &CountUsageChildren($authid)
424 counts Usage of narrower terms of Authid in bibliorecords.
428 sub CountUsageChildren {
432 =head2 GetAuthTypeCode
434 $authtypecode= &GetAuthTypeCode($authid)
436 returns authtypecode of an authid
440 sub GetAuthTypeCode {
441 #AUTHfind_authtypecode
443 my $dbh=C4::Context->dbh;
444 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
445 $sth->execute($authid);
446 my $authtypecode = $sth->fetchrow;
447 return $authtypecode;
450 =head2 GuessAuthTypeCode
452 my $authtypecode = GuessAuthTypeCode($record);
454 Get the record and tries to guess the adequate authtypecode from its content.
458 sub GuessAuthTypeCode {
460 return unless defined $record;
461 my $heading_fields = {
463 '100'=>{authtypecode=>'PERSO_NAME'},
464 '110'=>{authtypecode=>'CORPO_NAME'},
465 '111'=>{authtypecode=>'MEETI_NAME'},
466 '130'=>{authtypecode=>'UNIF_TITLE'},
467 '148'=>{authtypecode=>'CHRON_TERM'},
468 '150'=>{authtypecode=>'TOPIC_TERM'},
469 '151'=>{authtypecode=>'GEOGR_NAME'},
470 '155'=>{authtypecode=>'GENRE/FORM'},
471 '180'=>{authtypecode=>'GEN_SUBDIV'},
472 '181'=>{authtypecode=>'GEO_SUBDIV'},
473 '182'=>{authtypecode=>'CHRON_SUBD'},
474 '185'=>{authtypecode=>'FORM_SUBD'},
476 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
477 # 604 with embedded 700, 701, 702
478 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
479 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
480 #216 Trademark 716 [Reserved for future use]
481 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
482 #230 Title 500 4-- with embedded 500 605
483 #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
484 #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
485 #250 Topical subject 606
486 #260 Place access 620
487 #280 Form, genre or physical characteristics 608
490 # Could also be represented with :
492 #a = personal name entry
493 #b = corporate name entry
494 #c = territorial or geographical name
498 #g = collective uniform title
500 #i = name/collective uniform title
503 #l = form, genre or physical characteristics
505 '200'=>{authtypecode=>'NP'},
506 '210'=>{authtypecode=>'CO'},
507 '215'=>{authtypecode=>'SNG'},
508 '216'=>{authtypecode=>'TM'},
509 '220'=>{authtypecode=>'FAM'},
510 '230'=>{authtypecode=>'TU'},
511 '235'=>{authtypecode=>'CO_UNI_TI'},
512 '240'=>{authtypecode=>'SAUTTIT'},
513 '245'=>{authtypecode=>'NAME_COL'},
514 '250'=>{authtypecode=>'SNC'},
515 '260'=>{authtypecode=>'PA'},
516 '280'=>{authtypecode=>'GENRE/FORM'},
519 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
520 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
527 my $authtid = GuessAuthId($record);
529 Get the record and tries to guess the adequate authtypecode from its content.
535 return unless ($record && $record->field('001'));
536 # my $authtypecode=GuessAuthTypeCode($record);
537 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
538 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
539 # else {return $record->field($tag)->data}
540 return $record->field('001')->data;
545 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
547 returns a ref to hashref of authorities tag and subfield structure.
551 $tagslabel->{$tag}->{$subfield}->{'attribute'}
553 where attribute takes values in :
571 my ($forlibrarian,$authtypecode)= @_;
572 my $dbh=C4::Context->dbh;
573 $authtypecode="" unless $authtypecode;
575 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
578 # check that authority exists
579 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
580 $sth->execute($authtypecode);
581 my ($total) = $sth->fetchrow;
582 $authtypecode="" unless ($total >0);
584 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
585 FROM auth_tag_structure
590 $sth->execute($authtypecode);
591 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
593 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
594 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
595 $res->{$tag}->{tab} = " "; # XXX
596 $res->{$tag}->{mandatory} = $mandatory;
597 $res->{$tag}->{repeatable} = $repeatable;
600 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
601 FROM auth_subfield_structure
603 ORDER BY tagfield,tagsubfield"
605 $sth->execute($authtypecode);
608 my $authorised_value;
617 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
618 $mandatory, $repeatable, $authorised_value, $authtypecode,
619 $value_builder, $kohafield, $seealso, $hidden,
624 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
625 $res->{$tag}->{$subfield}->{tab} = $tab;
626 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
627 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
628 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
629 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
630 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
631 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
632 $res->{$tag}->{$subfield}->{seealso} = $seealso;
633 $res->{$tag}->{$subfield}->{hidden} = $hidden;
634 $res->{$tag}->{$subfield}->{isurl} = $isurl;
635 $res->{$tag}->{$subfield}->{link} = $link;
642 $authid= &AddAuthority($record, $authid,$authtypecode)
644 Either Create Or Modify existing authority.
645 returns authid of the newly created authority
650 # pass the MARC::Record to this function, and it will create the records in the authority table
651 my ($record,$authid,$authtypecode) = @_;
652 my $dbh=C4::Context->dbh;
653 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
655 # if authid empty => true add, find a new authid number
657 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
658 $format= 'UNIMARCAUTH';
664 #update date/time to 005 for marc and unimarc
665 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
666 my $f5=$record->field('005');
668 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
671 $f5->update($time.".0");
674 SetUTF8Flag($record);
675 if ($format eq "MARC21") {
676 if (!$record->leader) {
677 $record->leader($leader);
679 if (!$record->field('003')) {
680 $record->insert_fields_ordered(
681 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
684 my $date=POSIX::strftime("%y%m%d",localtime);
685 if (!$record->field('008')) {
686 # Get a valid default value for field 008
687 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
688 if(!$default_008 or length($default_008)<34) {
689 $default_008 = '|| aca||aabn | a|a d';
692 $default_008 = substr($default_008,0,34);
695 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
697 if (!$record->field('040')) {
698 $record->insert_fields_ordered(
699 MARC::Field->new('040','','',
700 'a' => C4::Context->preference('MARCOrgCode'),
701 'c' => C4::Context->preference('MARCOrgCode')
707 if ($format eq "UNIMARCAUTH") {
708 $record->leader(" nx j22 ") unless ($record->leader());
709 my $date=POSIX::strftime("%Y%m%d",localtime);
710 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
711 if (my $string=$record->subfield('100',"a")){
712 $string=~s/fre50/frey50/;
713 $record->field('100')->update('a'=>$string);
715 elsif ($record->field('100')){
716 $record->field('100')->update('a'=>$date.$defaultfield100);
718 $record->append_fields(
719 MARC::Field->new('100',' ',' '
720 ,'a'=>$date.$defaultfield100)
724 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
725 if (!$authid and $format eq "MARC21") {
726 # only need to do this fix when modifying an existing authority
727 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
729 if (my $field=$record->field($auth_type_tag)){
730 $field->update($auth_type_subfield=>$authtypecode);
733 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
739 my $sth=$dbh->prepare("select max(authid) from auth_header");
741 ($authid)=$sth->fetchrow;
743 ##Insert the recordID in MARC record
744 unless ($record->field('001') && $record->field('001')->data() eq $authid){
745 $record->delete_field($record->field('001'));
746 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
749 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
750 # warn "auth_exists = $auth_exists";
753 $oldRecord=GetAuthority($authid);
754 $record->add_fields('001',$authid) unless ($record->field('001'));
755 # warn "\n\n\n enregistrement".$record->as_formatted;
756 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
757 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
761 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
762 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
764 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
766 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
773 $authid= &DelAuthority($authid)
781 my $dbh=C4::Context->dbh;
783 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
784 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
785 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
786 $sth->execute($authid);
791 $authid= &ModAuthority($authid,$record,$authtypecode)
793 Modifies authority record, optionally updates attached biblios.
798 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
800 my $dbh=C4::Context->dbh;
801 #Now rewrite the $record to table with an add
802 my $oldrecord=GetAuthority($authid);
803 $authid=AddAuthority($record,$authid,$authtypecode);
805 # If a library thinks that updating all biblios is a long process and wishes
806 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
807 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
809 unless(C4::Context->preference('dontmerge') eq '1'){
810 &merge($authid,$oldrecord,$authid,$record);
812 # save a record in need_merge_authorities table
813 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
815 $dbh->do($sqlinsert,undef,($authid,0));
817 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
821 =head2 GetAuthorityXML
823 $marcxml= &GetAuthorityXML( $authid)
825 returns xml form of record $authid
829 sub GetAuthorityXML {
830 # Returns MARC::XML of the authority passed in parameter.
832 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
833 my $dbh=C4::Context->dbh;
834 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
835 $sth->execute($authid);
836 my ($marcxml)=$sth->fetchrow;
840 # for MARC21, call GetAuthority instead of
841 # getting the XML directly since we may
842 # need to fix up the location of the authority
843 # code -- note that this is reasonably safe
844 # because GetAuthorityXML is used only by the
845 # indexing processes like zebraqueue_start.pl
846 my $record = GetAuthority($authid);
847 return $record->as_xml_record('MARC21');
853 $record= &GetAuthority( $authid)
855 Returns MARC::Record of the authority passed in parameter.
861 my $authority = Koha::Authority->get_from_authid($authid);
862 return unless $authority;
863 return ($authority->record);
868 $result = &GetAuthType($authtypecode)
870 If the authority type specified by C<$authtypecode> exists,
871 returns a hashref of the type's fields. If the type
872 does not exist, returns undef.
877 my ($authtypecode) = @_;
878 my $dbh=C4::Context->dbh;
880 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
881 # type (FIXME but why?)
882 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
883 $sth->execute($authtypecode);
884 if (my $res = $sth->fetchrow_hashref) {
892 =head2 FindDuplicateAuthority
894 $record= &FindDuplicateAuthority( $record, $authtypecode)
896 return $authid,Summary if duplicate is found.
898 Comments : an improvement would be to return All the records that match.
902 sub FindDuplicateAuthority {
904 my ($record,$authtypecode)=@_;
905 # warn "IN for ".$record->as_formatted;
906 my $dbh = C4::Context->dbh;
907 # warn "".$record->as_formatted;
908 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
909 $sth->execute($authtypecode);
910 my ($auth_tag_to_report) = $sth->fetchrow;
912 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
913 # build a request for SearchAuthorities
914 my $query='at='.$authtypecode.' ';
915 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
916 if ($record->field($auth_tag_to_report)) {
917 foreach ($record->field($auth_tag_to_report)->subfields()) {
918 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
921 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
922 # there is at least 1 result => return the 1st one
923 if (!defined $error && @{$results} ) {
924 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
925 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
927 # no result, returns nothing
933 $summary= &BuildSummary( $record, $authid, $authtypecode)
935 Returns a hashref with a summary of the specified record.
937 Comment : authtypecode can be infered from both record and authid.
938 Moreover, authid can also be inferred from $record.
939 Would it be interesting to delete those things.
944 ## give this a Marc record to return summary
945 my ($record,$authid,$authtypecode)=@_;
946 my $dbh=C4::Context->dbh;
948 # handle $authtypecode is NULL or eq ""
950 my $authref = GetAuthType($authtypecode);
951 $summary{authtypecode} = $authref->{authtypecode};
952 $summary{type} = $authref->{authtypetext};
953 $summary{summary} = $authref->{summary};
955 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
956 my %marc21controlrefs = ( 'a' => 'earlier',
962 'n' => 'notapplicable',
966 my %unimarc_relation_from_code = (
972 $thesaurus{'1'}="Peuples";
973 $thesaurus{'2'}="Anthroponymes";
974 $thesaurus{'3'}="Oeuvres";
975 $thesaurus{'4'}="Chronologie";
976 $thesaurus{'5'}="Lieux";
977 $thesaurus{'6'}="Sujets";
980 # if the library has a summary defined, use it. Otherwise, build a standard one
981 # FIXME - it appears that the summary field in the authority frameworks
982 # can work as a display template. However, this doesn't
983 # suit the MARC21 version, so for now the "templating"
984 # feature will be enabled only for UNIMARC for backwards
986 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
987 my @fields = $record->fields();
988 # $reported_tag = '$9'.$result[$counter];
990 foreach my $field (@fields) {
991 my $tag = $field->tag();
992 my $tagvalue = $field->as_string();
993 my $localsummary= $summary{summary};
994 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
997 $reported_tag.='$3'.$field->data();
1000 my @subf = $field->subfields;
1001 for my $i (0..$#subf) {
1002 my $subfieldcode = $subf[$i][0];
1003 my $subfieldvalue = $subf[$i][1];
1004 my $tagsubf = $tag.$subfieldcode;
1005 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1008 push @stringssummary, $localsummary if ($localsummary ne $summary{summary});
1011 $resultstring = join(" -- ",@stringssummary);
1012 $resultstring =~ s/\[(.*?)\]//g;
1013 $resultstring =~ s/\n/<br>/g;
1014 $summary{summary} = $resultstring;
1021 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1022 # construct UNIMARC summary, that is quite different from MARC21 one
1024 foreach my $field ($record->field('2..')) {
1025 push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), field => $field->tag() };
1028 foreach my $field ($record->field('3..')) {
1029 push @notes, { note => $field->subfield('a'), field => $field->tag() };
1031 foreach my $field ($record->field('4..')) {
1032 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1033 push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), type => 'seefrom', field => $field->tag() };
1038 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1039 my $heading = $_->as_string('abcdefgjxyz');
1043 heading => $heading,
1045 authid => $_->subfield('9'),
1047 } $record->field('5..');
1050 @otherscript = map { {
1051 lang => $_->subfield('8') || '',
1052 term => $_->subfield('a'),
1055 } } $record->field('7..');
1058 # construct MARC21 summary
1059 # FIXME - looping over 1XX is questionable
1060 # since MARC21 authority should have only one 1XX
1061 my $subfields_to_report;
1062 foreach my $field ($record->field('1..')) {
1063 my $tag = $field->tag();
1064 next if "152" eq $tag;
1065 # FIXME - 152 is not a good tag to use
1066 # in MARC21 -- purely local tags really ought to be
1068 if ($tag eq '100') {
1069 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1070 } elsif ($tag eq '110') {
1071 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1072 } elsif ($tag eq '111') {
1073 $subfields_to_report = 'acdefghklnpqstvxyz';
1074 } elsif ($tag eq '130') {
1075 $subfields_to_report = 'adfghklmnoprstvxyz';
1076 } elsif ($tag eq '148') {
1077 $subfields_to_report = 'abvxyz';
1078 } elsif ($tag eq '150') {
1079 $subfields_to_report = 'abvxyz';
1080 } elsif ($tag eq '151') {
1081 $subfields_to_report = 'avxyz';
1082 } elsif ($tag eq '155') {
1083 $subfields_to_report = 'abvxyz';
1084 } elsif ($tag eq '180') {
1085 $subfields_to_report = 'vxyz';
1086 } elsif ($tag eq '181') {
1087 $subfields_to_report = 'vxyz';
1088 } elsif ($tag eq '182') {
1089 $subfields_to_report = 'vxyz';
1090 } elsif ($tag eq '185') {
1091 $subfields_to_report = 'vxyz';
1093 if ($subfields_to_report) {
1094 push @authorized, { heading => $field->as_string($subfields_to_report), field => $tag };
1096 push @authorized, { heading => $field->as_string(), field => $tag };
1099 foreach my $field ($record->field('4..')) { #See From
1100 my $type = 'seefrom';
1101 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1102 if ($type eq 'notapplicable') {
1103 $type = substr $field->subfield('w'), 2, 1;
1104 $type = 'earlier' if $type && $type ne 'n';
1106 if ($type eq 'subfi') {
1107 push @seefrom, { heading => $field->as_string($marc21subfields), type => ($field->subfield('i') || ''), field => $field->tag() };
1109 push @seefrom, { heading => $field->as_string($marc21subfields), type => $type, field => $field->tag() };
1112 foreach my $field ($record->field('5..')) { #See Also
1113 my $type = 'seealso';
1114 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1115 if ($type eq 'notapplicable') {
1116 $type = substr $field->subfield('w'), 2, 1;
1117 $type = 'earlier' if $type && $type ne 'n';
1119 if ($type eq 'subfi') {
1121 heading => $field->as_string($marc21subfields),
1122 type => $field->subfield('i'),
1123 field => $field->tag(),
1124 search => $field->as_string($marc21subfields) || '',
1125 authid => $field->subfield('9') || ''
1129 heading => $field->as_string($marc21subfields),
1131 field => $field->tag(),
1132 search => $field->as_string($marc21subfields) || '',
1133 authid => $field->subfield('9') || ''
1137 foreach my $field ($record->field('6..')) {
1138 push @notes, { note => $field->as_string(), field => $field->tag() };
1140 foreach my $field ($record->field('880')) {
1141 my $linkage = $field->subfield('6');
1142 my $category = substr $linkage, 0, 1;
1143 if ($category eq '1') {
1144 $category = 'preferred';
1145 } elsif ($category eq '4') {
1146 $category = 'seefrom';
1147 } elsif ($category eq '5') {
1148 $category = 'seealso';
1151 if ($field->subfield('w')) {
1152 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1156 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1157 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1160 $summary{mainentry} = $authorized[0]->{heading};
1161 $summary{authorized} = \@authorized;
1162 $summary{notes} = \@notes;
1163 $summary{seefrom} = \@seefrom;
1164 $summary{seealso} = \@seealso;
1165 $summary{otherscript} = \@otherscript;
1169 =head2 GetAuthorizedHeading
1171 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1173 Takes a MARC::Record object describing an authority record or an authid, and
1174 returns a string representation of the first authorized heading. This routine
1175 should be considered a temporary shim to ease the future migration of authority
1176 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1180 sub GetAuthorizedHeading {
1183 unless ($record = $args->{record}) {
1184 return unless $args->{authid};
1185 $record = GetAuthority($args->{authid});
1187 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1188 # construct UNIMARC summary, that is quite different from MARC21 one
1190 foreach my $field ($record->field('2..')) {
1191 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1194 foreach my $field ($record->field('1..')) {
1195 my $tag = $field->tag();
1196 next if "152" eq $tag;
1197 # FIXME - 152 is not a good tag to use
1198 # in MARC21 -- purely local tags really ought to be
1200 if ($tag eq '100') {
1201 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1202 } elsif ($tag eq '110') {
1203 return $field->as_string('abcdefghklmnoprstvxyz68');
1204 } elsif ($tag eq '111') {
1205 return $field->as_string('acdefghklnpqstvxyz68');
1206 } elsif ($tag eq '130') {
1207 return $field->as_string('adfghklmnoprstvxyz68');
1208 } elsif ($tag eq '148') {
1209 return $field->as_string('abvxyz68');
1210 } elsif ($tag eq '150') {
1211 return $field->as_string('abvxyz68');
1212 } elsif ($tag eq '151') {
1213 return $field->as_string('avxyz68');
1214 } elsif ($tag eq '155') {
1215 return $field->as_string('abvxyz68');
1216 } elsif ($tag eq '180') {
1217 return $field->as_string('vxyz68');
1218 } elsif ($tag eq '181') {
1219 return $field->as_string('vxyz68');
1220 } elsif ($tag eq '182') {
1221 return $field->as_string('vxyz68');
1222 } elsif ($tag eq '185') {
1223 return $field->as_string('vxyz68');
1225 return $field->as_string();
1232 =head2 BuildAuthHierarchies
1234 $text= &BuildAuthHierarchies( $authid, $force)
1236 return text containing trees for hierarchies
1237 for them to be stored in auth_header
1240 122,1314,2452;1324,2342,3,2452
1244 sub BuildAuthHierarchies{
1245 my $authid = shift @_;
1246 # warn "authid : $authid";
1247 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1249 my $dbh=C4::Context->dbh;
1251 my $data = GetHeaderAuthority($authid);
1252 if ($data->{'authtrees'} and not $force){
1253 return $data->{'authtrees'};
1254 # } elsif ($data->{'authtrees'}){
1255 # $hierarchies=$data->{'authtrees'};
1257 my $record = GetAuthority($authid);
1259 return unless $record;
1260 foreach my $field ($record->field('5..')){
1263 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1264 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1266 my $subfauthid=_get_authid_subfield($field) || '';
1267 next if ($subfauthid eq $authid);
1268 my $parentrecord = GetAuthority($subfauthid);
1269 next unless $parentrecord;
1270 my $localresult=$hierarchies;
1272 $trees = BuildAuthHierarchies($subfauthid);
1275 @trees = split(/;/,$trees);
1277 push @trees, $trees;
1282 @globalresult = (@globalresult,@trees);
1285 $hierarchies=join(";",@globalresult);
1287 #Unless there is no ancestor, I am alone.
1288 $hierarchies="$authid" unless ($hierarchies);
1290 AddAuthorityTrees($authid,$hierarchies);
1291 return $hierarchies;
1294 =head2 BuildAuthHierarchy
1296 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1298 return a hashref in order to display hierarchy for record and final Authid $authid
1309 sub BuildAuthHierarchy{
1310 my $record = shift @_;
1311 my $class = shift @_;
1312 my $authid_constructed = shift @_;
1313 return unless ($record && $record->field('001'));
1314 my $authid=$record->field('001')->data();
1316 my $parents=""; my $children="";
1317 my (@loopparents,@loopchildren);
1318 my $marcflavour = C4::Context->preference('marcflavour');
1319 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1320 foreach my $field ($record->field('5..')){
1321 my $subfauthid=_get_authid_subfield($field);
1322 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1323 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1324 if ($relationship eq 'h'){
1325 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1327 elsif ($relationship eq 'g'){
1328 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1330 # brothers could get in there with an else
1333 $cell{"parents"}=\@loopparents;
1334 $cell{"children"}=\@loopchildren;
1335 $cell{"class"}=$class;
1336 $cell{"authid"}=$authid;
1337 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1338 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1342 =head2 BuildAuthHierarchyBranch
1344 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1346 Return a data structure representing an authority hierarchy
1347 given a list of authorities representing a single branch in
1348 an authority hierarchy tree. $authid is the current node in
1349 the tree (which may or may not be somewhere in the middle).
1350 $cnt represents the level of the upper-most item, and is only
1351 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1352 don't ever pass in anything but zero to it).
1356 sub BuildAuthHierarchyBranch {
1357 my ($tree, $authid, $cnt) = @_;
1359 my $elementdata = GetAuthority(shift @$tree);
1360 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1361 if (scalar @$tree > 0) {
1362 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1363 my $nextAuthid = $nextBranch->{authid};
1365 # If we already have the next branch listed as a child, let's
1366 # replace the old listing with the new one. If not, we will add
1367 # the branch at the end.
1368 foreach my $cell (@{$branch->{children}}) {
1369 if ($cell->{authid} eq $nextAuthid) {
1370 $cell = $nextBranch;
1375 push @{$branch->{children}}, $nextBranch unless $found;
1380 =head2 GenerateHierarchy
1382 $hierarchy = &GenerateHierarchy($authid);
1384 Return an arrayref holding one or more "trees" representing
1385 authority hierarchies.
1389 sub GenerateHierarchy {
1391 my $trees = BuildAuthHierarchies($authid);
1392 my @trees = split /;/,$trees ;
1393 push @trees,$trees unless (@trees);
1394 my @loophierarchies;
1395 foreach my $tree (@trees){
1396 my @tree=split /,/,$tree;
1397 push @tree, $tree unless (@tree);
1398 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1399 push @loophierarchies, [ $branch ];
1401 return \@loophierarchies;
1404 sub _get_authid_subfield{
1406 return $field->subfield('9')||$field->subfield('3');
1408 =head2 GetHeaderAuthority
1410 $ref= &GetHeaderAuthority( $authid)
1412 return a hashref in order auth_header table data
1416 sub GetHeaderAuthority{
1417 my $authid = shift @_;
1418 my $sql= "SELECT * from auth_header WHERE authid = ?";
1419 my $dbh=C4::Context->dbh;
1420 my $rq= $dbh->prepare($sql);
1421 $rq->execute($authid);
1422 my $data= $rq->fetchrow_hashref;
1426 =head2 AddAuthorityTrees
1428 $ref= &AddAuthorityTrees( $authid, $trees)
1430 return success or failure
1434 sub AddAuthorityTrees{
1435 my $authid = shift @_;
1436 my $trees = shift @_;
1437 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1438 my $dbh=C4::Context->dbh;
1439 my $rq= $dbh->prepare($sql);
1440 return $rq->execute($trees,$authid);
1445 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1447 Could add some feature : Migrating from a typecode to an other for instance.
1448 Then we should add some new parameter : bibliotargettag, authtargettag
1453 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1454 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1455 my $dbh=C4::Context->dbh;
1456 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1457 my $authtypecodeto = GetAuthTypeCode($mergeto);
1458 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1459 # return if authority does not exist
1460 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1461 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1462 # search the tag to report
1463 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1464 $sth->execute($authtypecodefrom);
1465 my ($auth_tag_to_report_from) = $sth->fetchrow;
1466 $sth->execute($authtypecodeto);
1467 my ($auth_tag_to_report_to) = $sth->fetchrow;
1470 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1472 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1475 # search all biblio tags using this authority.
1476 #Getting marcbiblios impacted by the change.
1477 if (C4::Context->preference('NoZebra')) {
1479 my $dbh=C4::Context->dbh;
1480 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1482 while (my $biblionumbers=$rq->fetchrow){
1483 my @biblionumbers=split /;/,$biblionumbers;
1484 foreach (@biblionumbers) {
1485 if ($_=~/(\d+),.*/) {
1486 my $marc=GetMarcBiblio($1);
1487 push @reccache,$marc;
1493 my $oConnection=C4::Context->Zconn("biblioserver",0);
1494 # We used to use XML syntax here, but that no longer works.
1495 # Thankfully, we don't need it.
1497 $query= "an=".$mergefrom;
1498 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1501 $count=$oResult->size();
1504 while ( $z<$count ) {
1506 $rec=$oResult->record($z);
1507 my $marcdata = $rec->raw();
1508 my $marcrecordzebra= MARC::Record->new_from_usmarc($marcdata);
1509 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1510 my $i = ($biblionumbertagfield < 10) ? $marcrecordzebra->field($biblionumbertagfield)->data : $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1511 my $marcrecorddb=GetMarcBiblio($i);
1512 push @reccache, $marcrecorddb;
1515 $oResult->destroy();
1517 #warn scalar(@reccache)." biblios to update";
1518 # Get All candidate Tags for the change
1519 # (This will reduce the search scope in marc records).
1520 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1521 $sth->execute($authtypecodefrom);
1522 my @tags_using_authtype;
1523 while (my ($tagfield) = $sth->fetchrow) {
1524 push @tags_using_authtype,$tagfield ;
1527 if ($authtypecodeto ne $authtypecodefrom){
1528 # If many tags, take the first
1529 $sth->execute($authtypecodeto);
1530 $tag_to=$sth->fetchrow;
1533 # BulkEdit marc records
1534 # May be used as a template for a bulkedit field
1535 foreach my $marcrecord(@reccache){
1537 foreach my $tagfield (@tags_using_authtype){
1538 # warn "tagfield : $tagfield ";
1539 foreach my $field ($marcrecord->field($tagfield)){
1540 # biblio is linked to authority with $9 subfield containing authid
1541 my $auth_number=$field->subfield("9");
1542 my $tag=$field->tag();
1543 if ($auth_number==$mergefrom) {
1544 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1546 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1547 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1548 $exclude.= $subfield->[0];
1550 $exclude='['.$exclude.']';
1551 # add subfields in $field not included in @record_to
1552 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1553 foreach my $subfield (@restore) {
1554 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1556 $marcrecord->delete_field($field);
1557 $marcrecord->insert_grouped_field($field_to);
1562 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1565 $biblionumber=$marcrecord->field($bibliotag)->data;
1568 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1570 unless ($biblionumber){
1571 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1575 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1576 $counteditedbiblio++;
1577 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1580 return $counteditedbiblio;
1581 # now, find every other authority linked with this authority
1582 # now, find every other authority linked with this authority
1583 # my $oConnection=C4::Context->Zconn("authorityserver");
1585 # # att 9210 Auth-Internal-authtype
1586 # # att 9220 Auth-Internal-LN
1587 # # ccl.properties to add for authorities
1588 # $query= "= ".$mergefrom;
1589 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1590 # my $count=$oResult->size() if ($oResult);
1593 # while ( $z<$count ) {
1595 # $rec=$oResult->record($z);
1596 # my $marcdata = $rec->raw();
1597 # push @reccache, $marcdata;
1600 # $oResult->destroy();
1601 # foreach my $marc(@reccache){
1604 # $marcrecord = MARC::File::USMARC::decode($marc);
1605 # foreach my $tagfield (@tags_using_authtype){
1606 # $tagfield=substr($tagfield,0,3);
1607 # my @tags = $marcrecord->field($tagfield);
1608 # foreach my $tag (@tags){
1609 # my $tagsubs=$tag->subfield("9");
1610 # #warn "$tagfield:$tagsubs:$mergefrom";
1611 # if ($tagsubs== $mergefrom) {
1612 # $tag->update("9" =>$mergeto);
1613 # foreach my $subfield (@record_to) {
1614 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1615 # $tag->update($subfield->[0] =>$subfield->[1]);
1618 # $marcrecord->delete_field($tag);
1619 # $marcrecord->add_fields($tag);
1622 # }#foreach tagfield
1623 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1625 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1631 =head2 get_auth_type_location
1633 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1635 Get the tag and subfield used to store the heading type
1636 for indexing purposes. The C<$auth_type> parameter is
1637 optional; if it is not supplied, assume ''.
1639 This routine searches the MARC authority framework
1640 for the tag and subfield whose kohafield is
1641 C<auth_header.authtypecode>; if no such field is
1642 defined in the framework, default to the hardcoded value
1643 specific to the MARC format.
1647 sub get_auth_type_location {
1648 my $auth_type_code = @_ ? shift : '';
1650 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1651 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1652 return ($tag, $subfield);
1654 if (C4::Context->preference('marcflavour') eq "MARC21") {
1655 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1657 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1662 END { } # module clean-up code here (global destructor)
1669 Koha Development Team <http://koha-community.org/>
1671 Paul POULAIN paul.poulain@free.fr