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);
206 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
208 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
209 # the authtypecode. Then, search on $a of this tag_to_report
210 # also store main entry MARC tag, to extract it at end of search
212 ##first set the authtype search and may be multiple authorities
216 my @auths=split / /,$authtypecode ;
217 foreach my $auth (@auths){
218 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
219 push @authtypecode ,$auth;
223 while ($n>1){$query= "\@or ".$query;$n--;}
226 $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
234 for(my $i = 0 ; $i <= $#{$value} ; $i++)
237 if ( @$tags[$i] eq "mainmainentry" ) {
238 $attr = " \@attr 1=Heading-Main ";
240 elsif ( @$tags[$i] eq "mainentry" ) {
241 $attr = " \@attr 1=Heading ";
243 elsif ( @$tags[$i] eq "match" ) {
244 $attr = " \@attr 1=Match ";
246 elsif ( @$tags[$i] eq "match-heading" ) {
247 $attr = " \@attr 1=Match-heading ";
249 elsif ( @$tags[$i] eq "see-from" ) {
250 $attr = " \@attr 1=Match-heading-see-from ";
252 elsif ( @$tags[$i] eq "thesaurus" ) {
253 $attr = " \@attr 1=Subject-heading-thesaurus ";
255 else { # Assume any if no index was specified
256 $attr = " \@attr 1=Any ";
258 if ( @$operator[$i] eq 'is' ) {
259 $attr .= " \@attr 4=1 \@attr 5=100 "
260 ; ##Phrase, No truncation,all of subfield field must match
262 elsif ( @$operator[$i] eq "=" ) {
263 $attr .= " \@attr 4=107 "; #Number Exact match
265 elsif ( @$operator[$i] eq "start" ) {
266 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
267 ; #Firstinfield Phrase, Right truncated
269 elsif ( @$operator[$i] eq "exact" ) {
270 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
271 ; ##Phrase, No truncation,all of subfield field must match
274 $attr .= " \@attr 5=1 \@attr 4=6 "
275 ; ## Word list, right truncated, anywhere
276 if ($sortby eq 'Relevance') {
277 $attr .= "\@attr 2=102 ";
280 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
281 $attr =$attr."\"".@$value[$i]."\"";
286 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
290 ##Add how many queries generated
291 if (defined $query && $query=~/\S+/){
292 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
297 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
299 if ($sortby eq 'HeadingAsc') {
300 $orderstring = '@attr 7=1 @attr 1=Heading 0';
301 } elsif ($sortby eq 'HeadingDsc') {
302 $orderstring = '@attr 7=2 @attr 1=Heading 0';
303 } elsif ($sortby eq 'AuthidAsc') {
304 $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
305 } elsif ($sortby eq 'AuthidDsc') {
306 $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
309 $qpquery .= ' all:all' unless $value->[0];
311 if ( $value->[0] =~ m/^qp=(.*)$/ ) {
315 $qpquery .= " #$sortby";
317 $QParser->parse( $qpquery );
318 $query = $QParser->target_syntax('authorityserver');
320 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
321 $query="\@or $orderstring $query" if $orderstring;
324 $offset=0 unless $offset;
325 my $counter = $offset;
326 $length=10 unless $length;
329 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
330 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
332 $oAResult= $oAuth[0]->search($Anewq) ;
333 while (($i = ZOOM::event(\@oAuth)) != 0) {
334 my $ev = $oAuth[$i-1]->last_event();
335 last if $ev == ZOOM::Event::ZEND;
337 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
339 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
344 $nbresults=$oAResult->size();
345 my $nremains=$nbresults;
347 my @finalresult = ();
351 ##Find authid and linkid fields
352 ##we may be searching multiple authoritytypes.
353 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
354 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
355 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
356 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
358 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
359 my $rec=$oAResult->record($counter);
360 my $marcdata=$rec->raw();
362 my $separator=C4::Context->preference('authoritysep');
363 $authrecord = MARC::File::USMARC::decode($marcdata);
364 my $authid=$authrecord->field('001')->data();
366 $newline{authid} = $authid;
367 if ( !$skipmetadata ) {
369 BuildSummary( $authrecord, $authid, $authtypecode );
371 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
372 my $sth = $dbh->prepare($query_auth_tag);
373 $sth->execute($authtypecode);
374 my $auth_tag_to_report = $sth->fetchrow;
376 my $mainentry = $authrecord->field($auth_tag_to_report);
379 foreach ( $mainentry->subfields() ) {
380 $reported_tag .= '$' . $_->[0] . $_->[1];
383 my $thisauthtype = GetAuthType(GetAuthTypeCode($authid));
384 unless (defined $thisauthtype) {
385 $thisauthtype = GetAuthType($authtypecode) if $authtypecode;
387 $newline{authtype} = defined($thisauthtype) ?
388 $thisauthtype->{'authtypetext'} : '';
389 $newline{summary} = $summary;
390 $newline{even} = $counter % 2;
391 $newline{reported_tag} = $reported_tag;
394 push @finalresult, \%newline;
397 if (! $skipmetadata) {
398 for (my $z=0; $z<@finalresult; $z++){
399 my $count=CountUsage($finalresult[$z]{authid});
400 $finalresult[$z]{used}=$count;
406 $oAResult->destroy();
407 # $oAuth[0]->destroy();
409 return (\@finalresult, $nbresults);
415 $count= &CountUsage($authid)
417 counts Usage of Authid in bibliorecords.
423 if (C4::Context->preference('NoZebra')) {
424 # Read the index Koha-Auth-Number for this authid and count the lines
425 my $result = C4::Search::NZanalyse("an=$authid");
426 my @tab = split /;/,$result;
431 $query= "an:".$authid;
432 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
434 warn "Error: $err from search $query";
442 =head2 CountUsageChildren
444 $count= &CountUsageChildren($authid)
446 counts Usage of narrower terms of Authid in bibliorecords.
450 sub CountUsageChildren {
454 =head2 GetAuthTypeCode
456 $authtypecode= &GetAuthTypeCode($authid)
458 returns authtypecode of an authid
462 sub GetAuthTypeCode {
463 #AUTHfind_authtypecode
465 my $dbh=C4::Context->dbh;
466 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
467 $sth->execute($authid);
468 my $authtypecode = $sth->fetchrow;
469 return $authtypecode;
472 =head2 GuessAuthTypeCode
474 my $authtypecode = GuessAuthTypeCode($record);
476 Get the record and tries to guess the adequate authtypecode from its content.
480 sub GuessAuthTypeCode {
482 return unless defined $record;
483 my $heading_fields = {
485 '100'=>{authtypecode=>'PERSO_NAME'},
486 '110'=>{authtypecode=>'CORPO_NAME'},
487 '111'=>{authtypecode=>'MEETI_NAME'},
488 '130'=>{authtypecode=>'UNIF_TITLE'},
489 '148'=>{authtypecode=>'CHRON_TERM'},
490 '150'=>{authtypecode=>'TOPIC_TERM'},
491 '151'=>{authtypecode=>'GEOGR_NAME'},
492 '155'=>{authtypecode=>'GENRE/FORM'},
493 '180'=>{authtypecode=>'GEN_SUBDIV'},
494 '181'=>{authtypecode=>'GEO_SUBDIV'},
495 '182'=>{authtypecode=>'CHRON_SUBD'},
496 '185'=>{authtypecode=>'FORM_SUBD'},
498 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
499 # 604 with embedded 700, 701, 702
500 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
501 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
502 #216 Trademark 716 [Reserved for future use]
503 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
504 #230 Title 500 4-- with embedded 500 605
505 #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
506 #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
507 #250 Topical subject 606
508 #260 Place access 620
509 #280 Form, genre or physical characteristics 608
512 # Could also be represented with :
514 #a = personal name entry
515 #b = corporate name entry
516 #c = territorial or geographical name
520 #g = collective uniform title
522 #i = name/collective uniform title
525 #l = form, genre or physical characteristics
527 '200'=>{authtypecode=>'NP'},
528 '210'=>{authtypecode=>'CO'},
529 '215'=>{authtypecode=>'SNG'},
530 '216'=>{authtypecode=>'TM'},
531 '220'=>{authtypecode=>'FAM'},
532 '230'=>{authtypecode=>'TU'},
533 '235'=>{authtypecode=>'CO_UNI_TI'},
534 '240'=>{authtypecode=>'SAUTTIT'},
535 '245'=>{authtypecode=>'NAME_COL'},
536 '250'=>{authtypecode=>'SNC'},
537 '260'=>{authtypecode=>'PA'},
538 '280'=>{authtypecode=>'GENRE/FORM'},
541 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
542 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
549 my $authtid = GuessAuthId($record);
551 Get the record and tries to guess the adequate authtypecode from its content.
557 return unless ($record && $record->field('001'));
558 # my $authtypecode=GuessAuthTypeCode($record);
559 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
560 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
561 # else {return $record->field($tag)->data}
562 return $record->field('001')->data;
567 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
569 returns a ref to hashref of authorities tag and subfield structure.
573 $tagslabel->{$tag}->{$subfield}->{'attribute'}
575 where attribute takes values in :
593 my ($forlibrarian,$authtypecode)= @_;
594 my $dbh=C4::Context->dbh;
595 $authtypecode="" unless $authtypecode;
597 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
600 # check that authority exists
601 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
602 $sth->execute($authtypecode);
603 my ($total) = $sth->fetchrow;
604 $authtypecode="" unless ($total >0);
606 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
607 FROM auth_tag_structure
612 $sth->execute($authtypecode);
613 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
615 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
616 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
617 $res->{$tag}->{tab} = " "; # XXX
618 $res->{$tag}->{mandatory} = $mandatory;
619 $res->{$tag}->{repeatable} = $repeatable;
622 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
623 FROM auth_subfield_structure
625 ORDER BY tagfield,tagsubfield"
627 $sth->execute($authtypecode);
630 my $authorised_value;
639 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
640 $mandatory, $repeatable, $authorised_value, $authtypecode,
641 $value_builder, $kohafield, $seealso, $hidden,
646 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
647 $res->{$tag}->{$subfield}->{tab} = $tab;
648 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
649 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
650 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
651 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
652 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
653 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
654 $res->{$tag}->{$subfield}->{seealso} = $seealso;
655 $res->{$tag}->{$subfield}->{hidden} = $hidden;
656 $res->{$tag}->{$subfield}->{isurl} = $isurl;
657 $res->{$tag}->{$subfield}->{link} = $link;
664 $authid= &AddAuthority($record, $authid,$authtypecode)
666 Either Create Or Modify existing authority.
667 returns authid of the newly created authority
672 # pass the MARC::Record to this function, and it will create the records in the authority table
673 my ($record,$authid,$authtypecode) = @_;
674 my $dbh=C4::Context->dbh;
675 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
677 # if authid empty => true add, find a new authid number
679 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
680 $format= 'UNIMARCAUTH';
686 #update date/time to 005 for marc and unimarc
687 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
688 my $f5=$record->field('005');
690 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
693 $f5->update($time.".0");
696 SetUTF8Flag($record);
697 if ($format eq "MARC21") {
698 if (!$record->leader) {
699 $record->leader($leader);
701 if (!$record->field('003')) {
702 $record->insert_fields_ordered(
703 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
706 my $date=POSIX::strftime("%y%m%d",localtime);
707 if (!$record->field('008')) {
708 # Get a valid default value for field 008
709 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
710 if(!$default_008 or length($default_008)<34) {
711 $default_008 = '|| aca||aabn | a|a d';
714 $default_008 = substr($default_008,0,34);
717 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
719 if (!$record->field('040')) {
720 $record->insert_fields_ordered(
721 MARC::Field->new('040','','',
722 'a' => C4::Context->preference('MARCOrgCode'),
723 'c' => C4::Context->preference('MARCOrgCode')
729 if ($format eq "UNIMARCAUTH") {
730 $record->leader(" nx j22 ") unless ($record->leader());
731 my $date=POSIX::strftime("%Y%m%d",localtime);
732 my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
733 if (my $string=$record->subfield('100',"a")){
734 $string=~s/fre50/frey50/;
735 $record->field('100')->update('a'=>$string);
737 elsif ($record->field('100')){
738 $record->field('100')->update('a'=>$date.$defaultfield100);
740 $record->append_fields(
741 MARC::Field->new('100',' ',' '
742 ,'a'=>$date.$defaultfield100)
746 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
747 if (!$authid and $format eq "MARC21") {
748 # only need to do this fix when modifying an existing authority
749 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
751 if (my $field=$record->field($auth_type_tag)){
752 $field->update($auth_type_subfield=>$authtypecode);
755 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
761 my $sth=$dbh->prepare("select max(authid) from auth_header");
763 ($authid)=$sth->fetchrow;
765 ##Insert the recordID in MARC record
766 unless ($record->field('001') && $record->field('001')->data() eq $authid){
767 $record->delete_field($record->field('001'));
768 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
771 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
772 # warn "auth_exists = $auth_exists";
775 $oldRecord=GetAuthority($authid);
776 $record->add_fields('001',$authid) unless ($record->field('001'));
777 # warn "\n\n\n enregistrement".$record->as_formatted;
778 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
779 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
783 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
784 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
786 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
788 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
795 $authid= &DelAuthority($authid)
803 my $dbh=C4::Context->dbh;
805 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
806 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
807 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
808 $sth->execute($authid);
813 $authid= &ModAuthority($authid,$record,$authtypecode)
815 Modifies authority record, optionally updates attached biblios.
820 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
822 my $dbh=C4::Context->dbh;
823 #Now rewrite the $record to table with an add
824 my $oldrecord=GetAuthority($authid);
825 $authid=AddAuthority($record,$authid,$authtypecode);
827 # If a library thinks that updating all biblios is a long process and wishes
828 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
829 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
831 unless(C4::Context->preference('dontmerge') eq '1'){
832 &merge($authid,$oldrecord,$authid,$record);
834 # save a record in need_merge_authorities table
835 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
837 $dbh->do($sqlinsert,undef,($authid,0));
839 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
843 =head2 GetAuthorityXML
845 $marcxml= &GetAuthorityXML( $authid)
847 returns xml form of record $authid
851 sub GetAuthorityXML {
852 # Returns MARC::XML of the authority passed in parameter.
854 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
855 my $dbh=C4::Context->dbh;
856 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
857 $sth->execute($authid);
858 my ($marcxml)=$sth->fetchrow;
862 # for MARC21, call GetAuthority instead of
863 # getting the XML directly since we may
864 # need to fix up the location of the authority
865 # code -- note that this is reasonably safe
866 # because GetAuthorityXML is used only by the
867 # indexing processes like zebraqueue_start.pl
868 my $record = GetAuthority($authid);
869 return $record->as_xml_record('MARC21');
875 $record= &GetAuthority( $authid)
877 Returns MARC::Record of the authority passed in parameter.
883 my $authority = Koha::Authority->get_from_authid($authid);
884 return unless $authority;
885 return ($authority->record);
890 $result = &GetAuthType($authtypecode)
892 If the authority type specified by C<$authtypecode> exists,
893 returns a hashref of the type's fields. If the type
894 does not exist, returns undef.
899 my ($authtypecode) = @_;
900 my $dbh=C4::Context->dbh;
902 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
903 # type (FIXME but why?)
904 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
905 $sth->execute($authtypecode);
906 if (my $res = $sth->fetchrow_hashref) {
914 =head2 FindDuplicateAuthority
916 $record= &FindDuplicateAuthority( $record, $authtypecode)
918 return $authid,Summary if duplicate is found.
920 Comments : an improvement would be to return All the records that match.
924 sub FindDuplicateAuthority {
926 my ($record,$authtypecode)=@_;
927 # warn "IN for ".$record->as_formatted;
928 my $dbh = C4::Context->dbh;
929 # warn "".$record->as_formatted;
930 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
931 $sth->execute($authtypecode);
932 my ($auth_tag_to_report) = $sth->fetchrow;
934 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
935 # build a request for SearchAuthorities
937 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
944 my $query='at:'.$authtypecode.' ';
945 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
946 if ($record->field($auth_tag_to_report)) {
947 foreach ($record->field($auth_tag_to_report)->subfields()) {
948 $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
951 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
952 # there is at least 1 result => return the 1st one
953 if (!defined $error && @{$results} ) {
954 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
955 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
957 # no result, returns nothing
963 $summary= &BuildSummary( $record, $authid, $authtypecode)
965 Returns a hashref with a summary of the specified record.
967 Comment : authtypecode can be infered from both record and authid.
968 Moreover, authid can also be inferred from $record.
969 Would it be interesting to delete those things.
974 ## give this a Marc record to return summary
975 my ($record,$authid,$authtypecode)=@_;
976 my $dbh=C4::Context->dbh;
978 # handle $authtypecode is NULL or eq ""
980 my $authref = GetAuthType($authtypecode);
981 $summary{authtypecode} = $authref->{authtypecode};
982 $summary{type} = $authref->{authtypetext};
983 $summary{summary} = $authref->{summary};
985 my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
986 my %marc21controlrefs = ( 'a' => 'earlier',
992 'n' => 'notapplicable',
996 my %unimarc_relation_from_code = (
1002 $thesaurus{'1'}="Peuples";
1003 $thesaurus{'2'}="Anthroponymes";
1004 $thesaurus{'3'}="Oeuvres";
1005 $thesaurus{'4'}="Chronologie";
1006 $thesaurus{'5'}="Lieux";
1007 $thesaurus{'6'}="Sujets";
1008 #thesaurus a remplir
1010 # if the library has a summary defined, use it. Otherwise, build a standard one
1011 # FIXME - it appears that the summary field in the authority frameworks
1012 # can work as a display template. However, this doesn't
1013 # suit the MARC21 version, so for now the "templating"
1014 # feature will be enabled only for UNIMARC for backwards
1016 if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
1017 my @fields = $record->fields();
1018 # $reported_tag = '$9'.$result[$counter];
1020 foreach my $field (@fields) {
1021 my $tag = $field->tag();
1022 my $tagvalue = $field->as_string();
1023 my $localsummary= $summary{summary};
1024 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
1026 if ($tag eq '001') {
1027 $reported_tag.='$3'.$field->data();
1030 my @subf = $field->subfields;
1031 for my $i (0..$#subf) {
1032 my $subfieldcode = $subf[$i][0];
1033 my $subfieldvalue = $subf[$i][1];
1034 my $tagsubf = $tag.$subfieldcode;
1035 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1038 push @stringssummary, $localsummary if ($localsummary ne $summary{summary});
1041 $resultstring = join(" -- ",@stringssummary);
1042 $resultstring =~ s/\[(.*?)\]//g;
1043 $resultstring =~ s/\n/<br>/g;
1044 $summary{summary} = $resultstring;
1051 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1052 # construct UNIMARC summary, that is quite different from MARC21 one
1054 foreach my $field ($record->field('2..')) {
1055 push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), field => $field->tag() };
1058 foreach my $field ($record->field('3..')) {
1059 push @notes, { note => $field->subfield('a'), field => $field->tag() };
1061 foreach my $field ($record->field('4..')) {
1062 my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1063 push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), type => 'seefrom', field => $field->tag() };
1068 my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1069 my $heading = $_->as_string('abcdefgjxyz');
1073 heading => $heading,
1075 authid => $_->subfield('9'),
1077 } $record->field('5..');
1080 @otherscript = map { {
1081 lang => $_->subfield('8') || '',
1082 term => $_->subfield('a'),
1085 } } $record->field('7..');
1088 # construct MARC21 summary
1089 # FIXME - looping over 1XX is questionable
1090 # since MARC21 authority should have only one 1XX
1091 my $subfields_to_report;
1092 foreach my $field ($record->field('1..')) {
1093 my $tag = $field->tag();
1094 next if "152" eq $tag;
1095 # FIXME - 152 is not a good tag to use
1096 # in MARC21 -- purely local tags really ought to be
1098 if ($tag eq '100') {
1099 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1100 } elsif ($tag eq '110') {
1101 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1102 } elsif ($tag eq '111') {
1103 $subfields_to_report = 'acdefghklnpqstvxyz';
1104 } elsif ($tag eq '130') {
1105 $subfields_to_report = 'adfghklmnoprstvxyz';
1106 } elsif ($tag eq '148') {
1107 $subfields_to_report = 'abvxyz';
1108 } elsif ($tag eq '150') {
1109 $subfields_to_report = 'abvxyz';
1110 } elsif ($tag eq '151') {
1111 $subfields_to_report = 'avxyz';
1112 } elsif ($tag eq '155') {
1113 $subfields_to_report = 'abvxyz';
1114 } elsif ($tag eq '180') {
1115 $subfields_to_report = 'vxyz';
1116 } elsif ($tag eq '181') {
1117 $subfields_to_report = 'vxyz';
1118 } elsif ($tag eq '182') {
1119 $subfields_to_report = 'vxyz';
1120 } elsif ($tag eq '185') {
1121 $subfields_to_report = 'vxyz';
1123 if ($subfields_to_report) {
1124 push @authorized, { heading => $field->as_string($subfields_to_report), field => $tag };
1126 push @authorized, { heading => $field->as_string(), field => $tag };
1129 foreach my $field ($record->field('4..')) { #See From
1130 my $type = 'seefrom';
1131 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1132 if ($type eq 'notapplicable') {
1133 $type = substr $field->subfield('w'), 2, 1;
1134 $type = 'earlier' if $type && $type ne 'n';
1136 if ($type eq 'subfi') {
1137 push @seefrom, { heading => $field->as_string($marc21subfields), type => ($field->subfield('i') || ''), field => $field->tag() };
1139 push @seefrom, { heading => $field->as_string($marc21subfields), type => $type, field => $field->tag() };
1142 foreach my $field ($record->field('5..')) { #See Also
1143 my $type = 'seealso';
1144 $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1145 if ($type eq 'notapplicable') {
1146 $type = substr $field->subfield('w'), 2, 1;
1147 $type = 'earlier' if $type && $type ne 'n';
1149 if ($type eq 'subfi') {
1151 heading => $field->as_string($marc21subfields),
1152 type => $field->subfield('i'),
1153 field => $field->tag(),
1154 search => $field->as_string($marc21subfields) || '',
1155 authid => $field->subfield('9') || ''
1159 heading => $field->as_string($marc21subfields),
1161 field => $field->tag(),
1162 search => $field->as_string($marc21subfields) || '',
1163 authid => $field->subfield('9') || ''
1167 foreach my $field ($record->field('6..')) {
1168 push @notes, { note => $field->as_string(), field => $field->tag() };
1170 foreach my $field ($record->field('880')) {
1171 my $linkage = $field->subfield('6');
1172 my $category = substr $linkage, 0, 1;
1173 if ($category eq '1') {
1174 $category = 'preferred';
1175 } elsif ($category eq '4') {
1176 $category = 'seefrom';
1177 } elsif ($category eq '5') {
1178 $category = 'seealso';
1181 if ($field->subfield('w')) {
1182 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1186 my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1187 push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1190 $summary{mainentry} = $authorized[0]->{heading};
1191 $summary{authorized} = \@authorized;
1192 $summary{notes} = \@notes;
1193 $summary{seefrom} = \@seefrom;
1194 $summary{seealso} = \@seealso;
1195 $summary{otherscript} = \@otherscript;
1199 =head2 GetAuthorizedHeading
1201 $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1203 Takes a MARC::Record object describing an authority record or an authid, and
1204 returns a string representation of the first authorized heading. This routine
1205 should be considered a temporary shim to ease the future migration of authority
1206 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1210 sub GetAuthorizedHeading {
1213 unless ($record = $args->{record}) {
1214 return unless $args->{authid};
1215 $record = GetAuthority($args->{authid});
1217 return unless (ref $record eq 'MARC::Record');
1218 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1219 # construct UNIMARC summary, that is quite different from MARC21 one
1221 foreach my $field ($record->field('2..')) {
1222 return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1225 foreach my $field ($record->field('1..')) {
1226 my $tag = $field->tag();
1227 next if "152" eq $tag;
1228 # FIXME - 152 is not a good tag to use
1229 # in MARC21 -- purely local tags really ought to be
1231 if ($tag eq '100') {
1232 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1233 } elsif ($tag eq '110') {
1234 return $field->as_string('abcdefghklmnoprstvxyz68');
1235 } elsif ($tag eq '111') {
1236 return $field->as_string('acdefghklnpqstvxyz68');
1237 } elsif ($tag eq '130') {
1238 return $field->as_string('adfghklmnoprstvxyz68');
1239 } elsif ($tag eq '148') {
1240 return $field->as_string('abvxyz68');
1241 } elsif ($tag eq '150') {
1242 return $field->as_string('abvxyz68');
1243 } elsif ($tag eq '151') {
1244 return $field->as_string('avxyz68');
1245 } elsif ($tag eq '155') {
1246 return $field->as_string('abvxyz68');
1247 } elsif ($tag eq '180') {
1248 return $field->as_string('vxyz68');
1249 } elsif ($tag eq '181') {
1250 return $field->as_string('vxyz68');
1251 } elsif ($tag eq '182') {
1252 return $field->as_string('vxyz68');
1253 } elsif ($tag eq '185') {
1254 return $field->as_string('vxyz68');
1256 return $field->as_string();
1263 =head2 BuildAuthHierarchies
1265 $text= &BuildAuthHierarchies( $authid, $force)
1267 return text containing trees for hierarchies
1268 for them to be stored in auth_header
1271 122,1314,2452;1324,2342,3,2452
1275 sub BuildAuthHierarchies{
1276 my $authid = shift @_;
1277 # warn "authid : $authid";
1278 my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1280 my $dbh=C4::Context->dbh;
1282 my $data = GetHeaderAuthority($authid);
1283 if ($data->{'authtrees'} and not $force){
1284 return $data->{'authtrees'};
1285 # } elsif ($data->{'authtrees'}){
1286 # $hierarchies=$data->{'authtrees'};
1288 my $record = GetAuthority($authid);
1290 return unless $record;
1291 foreach my $field ($record->field('5..')){
1294 (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1295 (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1297 my $subfauthid=_get_authid_subfield($field) || '';
1298 next if ($subfauthid eq $authid);
1299 my $parentrecord = GetAuthority($subfauthid);
1300 next unless $parentrecord;
1301 my $localresult=$hierarchies;
1303 $trees = BuildAuthHierarchies($subfauthid);
1306 @trees = split(/;/,$trees);
1308 push @trees, $trees;
1313 @globalresult = (@globalresult,@trees);
1316 $hierarchies=join(";",@globalresult);
1318 #Unless there is no ancestor, I am alone.
1319 $hierarchies="$authid" unless ($hierarchies);
1321 AddAuthorityTrees($authid,$hierarchies);
1322 return $hierarchies;
1325 =head2 BuildAuthHierarchy
1327 $ref= &BuildAuthHierarchy( $record, $class,$authid)
1329 return a hashref in order to display hierarchy for record and final Authid $authid
1340 sub BuildAuthHierarchy{
1341 my $record = shift @_;
1342 my $class = shift @_;
1343 my $authid_constructed = shift @_;
1344 return unless ($record && $record->field('001'));
1345 my $authid=$record->field('001')->data();
1347 my $parents=""; my $children="";
1348 my (@loopparents,@loopchildren);
1349 my $marcflavour = C4::Context->preference('marcflavour');
1350 my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1351 foreach my $field ($record->field('5..')){
1352 my $subfauthid=_get_authid_subfield($field);
1353 if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1354 my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1355 if ($relationship eq 'h'){
1356 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1358 elsif ($relationship eq 'g'){
1359 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1361 # brothers could get in there with an else
1364 $cell{"parents"}=\@loopparents;
1365 $cell{"children"}=\@loopchildren;
1366 $cell{"class"}=$class;
1367 $cell{"authid"}=$authid;
1368 $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1369 $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1373 =head2 BuildAuthHierarchyBranch
1375 $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1377 Return a data structure representing an authority hierarchy
1378 given a list of authorities representing a single branch in
1379 an authority hierarchy tree. $authid is the current node in
1380 the tree (which may or may not be somewhere in the middle).
1381 $cnt represents the level of the upper-most item, and is only
1382 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1383 don't ever pass in anything but zero to it).
1387 sub BuildAuthHierarchyBranch {
1388 my ($tree, $authid, $cnt) = @_;
1390 my $elementdata = GetAuthority(shift @$tree);
1391 my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1392 if (scalar @$tree > 0) {
1393 my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1394 my $nextAuthid = $nextBranch->{authid};
1396 # If we already have the next branch listed as a child, let's
1397 # replace the old listing with the new one. If not, we will add
1398 # the branch at the end.
1399 foreach my $cell (@{$branch->{children}}) {
1400 if ($cell->{authid} eq $nextAuthid) {
1401 $cell = $nextBranch;
1406 push @{$branch->{children}}, $nextBranch unless $found;
1411 =head2 GenerateHierarchy
1413 $hierarchy = &GenerateHierarchy($authid);
1415 Return an arrayref holding one or more "trees" representing
1416 authority hierarchies.
1420 sub GenerateHierarchy {
1422 my $trees = BuildAuthHierarchies($authid);
1423 my @trees = split /;/,$trees ;
1424 push @trees,$trees unless (@trees);
1425 my @loophierarchies;
1426 foreach my $tree (@trees){
1427 my @tree=split /,/,$tree;
1428 push @tree, $tree unless (@tree);
1429 my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1430 push @loophierarchies, [ $branch ];
1432 return \@loophierarchies;
1435 sub _get_authid_subfield{
1437 return $field->subfield('9')||$field->subfield('3');
1439 =head2 GetHeaderAuthority
1441 $ref= &GetHeaderAuthority( $authid)
1443 return a hashref in order auth_header table data
1447 sub GetHeaderAuthority{
1448 my $authid = shift @_;
1449 my $sql= "SELECT * from auth_header WHERE authid = ?";
1450 my $dbh=C4::Context->dbh;
1451 my $rq= $dbh->prepare($sql);
1452 $rq->execute($authid);
1453 my $data= $rq->fetchrow_hashref;
1457 =head2 AddAuthorityTrees
1459 $ref= &AddAuthorityTrees( $authid, $trees)
1461 return success or failure
1465 sub AddAuthorityTrees{
1466 my $authid = shift @_;
1467 my $trees = shift @_;
1468 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1469 my $dbh=C4::Context->dbh;
1470 my $rq= $dbh->prepare($sql);
1471 return $rq->execute($trees,$authid);
1476 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1478 Could add some feature : Migrating from a typecode to an other for instance.
1479 Then we should add some new parameter : bibliotargettag, authtargettag
1484 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1485 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1486 my $dbh=C4::Context->dbh;
1487 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1488 my $authtypecodeto = GetAuthTypeCode($mergeto);
1489 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1490 # return if authority does not exist
1491 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1492 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1493 # search the tag to report
1494 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1495 $sth->execute($authtypecodefrom);
1496 my ($auth_tag_to_report_from) = $sth->fetchrow;
1497 $sth->execute($authtypecodeto);
1498 my ($auth_tag_to_report_to) = $sth->fetchrow;
1501 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1503 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1506 # search all biblio tags using this authority.
1507 #Getting marcbiblios impacted by the change.
1508 if (C4::Context->preference('NoZebra')) {
1510 my $dbh=C4::Context->dbh;
1511 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1513 while (my $biblionumbers=$rq->fetchrow){
1514 my @biblionumbers=split /;/,$biblionumbers;
1515 foreach (@biblionumbers) {
1516 if ($_=~/(\d+),.*/) {
1517 my $marc=GetMarcBiblio($1);
1518 push @reccache,$marc;
1524 my $oConnection=C4::Context->Zconn("biblioserver",0);
1525 # We used to use XML syntax here, but that no longer works.
1526 # Thankfully, we don't need it.
1528 $query= "an=".$mergefrom;
1529 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1532 $count=$oResult->size();
1535 while ( $z<$count ) {
1537 $rec=$oResult->record($z);
1538 my $marcdata = $rec->raw();
1539 my $marcrecordzebra= MARC::Record->new_from_usmarc($marcdata);
1540 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1541 my $i = ($biblionumbertagfield < 10) ? $marcrecordzebra->field($biblionumbertagfield)->data : $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1542 my $marcrecorddb=GetMarcBiblio($i);
1543 push @reccache, $marcrecorddb;
1546 $oResult->destroy();
1548 #warn scalar(@reccache)." biblios to update";
1549 # Get All candidate Tags for the change
1550 # (This will reduce the search scope in marc records).
1551 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1552 $sth->execute($authtypecodefrom);
1553 my @tags_using_authtype;
1554 while (my ($tagfield) = $sth->fetchrow) {
1555 push @tags_using_authtype,$tagfield ;
1558 if ($authtypecodeto ne $authtypecodefrom){
1559 # If many tags, take the first
1560 $sth->execute($authtypecodeto);
1561 $tag_to=$sth->fetchrow;
1564 # BulkEdit marc records
1565 # May be used as a template for a bulkedit field
1566 foreach my $marcrecord(@reccache){
1568 foreach my $tagfield (@tags_using_authtype){
1569 # warn "tagfield : $tagfield ";
1570 foreach my $field ($marcrecord->field($tagfield)){
1571 # biblio is linked to authority with $9 subfield containing authid
1572 my $auth_number=$field->subfield("9");
1573 my $tag=$field->tag();
1574 if ($auth_number==$mergefrom) {
1575 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1577 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1578 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1579 $exclude.= $subfield->[0];
1581 $exclude='['.$exclude.']';
1582 # add subfields in $field not included in @record_to
1583 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1584 foreach my $subfield (@restore) {
1585 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1587 $marcrecord->delete_field($field);
1588 $marcrecord->insert_grouped_field($field_to);
1593 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1596 $biblionumber=$marcrecord->field($bibliotag)->data;
1599 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1601 unless ($biblionumber){
1602 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1606 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1607 $counteditedbiblio++;
1608 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1611 return $counteditedbiblio;
1612 # now, find every other authority linked with this authority
1613 # now, find every other authority linked with this authority
1614 # my $oConnection=C4::Context->Zconn("authorityserver");
1616 # # att 9210 Auth-Internal-authtype
1617 # # att 9220 Auth-Internal-LN
1618 # # ccl.properties to add for authorities
1619 # $query= "= ".$mergefrom;
1620 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1621 # my $count=$oResult->size() if ($oResult);
1624 # while ( $z<$count ) {
1626 # $rec=$oResult->record($z);
1627 # my $marcdata = $rec->raw();
1628 # push @reccache, $marcdata;
1631 # $oResult->destroy();
1632 # foreach my $marc(@reccache){
1635 # $marcrecord = MARC::File::USMARC::decode($marc);
1636 # foreach my $tagfield (@tags_using_authtype){
1637 # $tagfield=substr($tagfield,0,3);
1638 # my @tags = $marcrecord->field($tagfield);
1639 # foreach my $tag (@tags){
1640 # my $tagsubs=$tag->subfield("9");
1641 # #warn "$tagfield:$tagsubs:$mergefrom";
1642 # if ($tagsubs== $mergefrom) {
1643 # $tag->update("9" =>$mergeto);
1644 # foreach my $subfield (@record_to) {
1645 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1646 # $tag->update($subfield->[0] =>$subfield->[1]);
1649 # $marcrecord->delete_field($tag);
1650 # $marcrecord->add_fields($tag);
1653 # }#foreach tagfield
1654 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1656 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1662 =head2 get_auth_type_location
1664 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1666 Get the tag and subfield used to store the heading type
1667 for indexing purposes. The C<$auth_type> parameter is
1668 optional; if it is not supplied, assume ''.
1670 This routine searches the MARC authority framework
1671 for the tag and subfield whose kohafield is
1672 C<auth_header.authtypecode>; if no such field is
1673 defined in the framework, default to the hardcoded value
1674 specific to the MARC format.
1678 sub get_auth_type_location {
1679 my $auth_type_code = @_ ? shift : '';
1681 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1682 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1683 return ($tag, $subfield);
1685 if (C4::Context->preference('marcflavour') eq "MARC21") {
1686 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1688 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1693 END { } # module clean-up code here (global destructor)
1700 Koha Development Team <http://koha-community.org/>
1702 Paul POULAIN paul.poulain@free.fr