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.
20 #use warnings; FIXME - Bug 2505
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
30 use vars qw($VERSION @ISA @EXPORT);
33 # set the version for version checking
42 &GetAuthMARCFromKohaField
56 &BuildUnimarcHierarchies
57 &BuildUnimarcHierarchy
60 &FindDuplicateAuthority
72 =head2 GetAuthMARCFromKohaField
74 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
76 returns tag and subfield linked to kohafield
79 Suppose Kohafield is only linked to ONE subfield
83 sub GetAuthMARCFromKohaField {
84 #AUTHfind_marc_from_kohafield
85 my ( $kohafield,$authtypecode ) = @_;
86 my $dbh=C4::Context->dbh;
87 return 0, 0 unless $kohafield;
88 $authtypecode="" unless $authtypecode;
89 my $marcfromkohafield;
90 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
91 $sth->execute($kohafield,$authtypecode);
92 my ($tagfield,$tagsubfield) = $sth->fetchrow;
94 return ($tagfield,$tagsubfield);
97 =head2 SearchAuthorities
99 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
100 $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
102 returns ref to array result and count of results returned
106 sub SearchAuthorities {
107 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
108 # warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
109 my $dbh=C4::Context->dbh;
110 if (C4::Context->preference('NoZebra')) {
116 my @auths=split / /,$authtypecode ;
117 foreach my $auth (@auths){
118 $query .="AND auth_type= $auth ";
122 for(my $i = 0 ; $i <= $#{$value} ; $i++)
125 if (@$tags[$i] =~/mainentry|mainmainentry/) {
126 $query .= qq( AND @$tags[$i] );
130 if (@$operator[$i] eq 'is') {
131 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
132 }elsif (@$operator[$i] eq "="){
133 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
134 }elsif (@$operator[$i] eq "start"){
135 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
137 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
143 # do the query (if we had some search term
146 # warn "QUERY : $query";
147 my $result = C4::Search::NZanalyse($query,'authorityserver');
148 # warn "result : $result";
150 foreach (split /;/,$result) {
151 my ($authid,$title) = split /,/,$_;
152 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
153 # and we don't want to get only 1 result for each of them !!!
154 # hint & speed improvement : we can order without reading the record
155 # so order, and read records only for the requested page !
156 $result{$title.$authid}=$authid;
158 # sort the hash and return the same structure as GetRecords (Zebra querying)
161 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
162 foreach my $key (sort {$b cmp $a} (keys %result)) {
163 push @listresult, $result{$key};
164 # warn "push..."$#finalresult;
167 } else { # sort by mainmainentry ASC
168 foreach my $key (sort (keys %result)) {
169 push @listresult, $result{$key};
170 # warn "push..."$#finalresult;
174 # limit the $results_per_page to result size if it's more
175 $length = $numbers-$offset if $numbers < ($offset+$length);
176 # for the requested page, replace authid by the complete record
177 # speed improvement : avoid reading too much things
179 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
180 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
181 my $separator=C4::Context->preference('authoritysep');
182 my $authrecord =GetAuthority($listresult[$counter]);
183 my $authid=$listresult[$counter];
184 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
185 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
186 my $sth = $dbh->prepare($query_auth_tag);
187 $sth->execute($authtypecode);
188 my $auth_tag_to_report = $sth->fetchrow;
190 $newline{used}=CountUsage($authid);
191 $newline{summary} = $summary;
192 $newline{authid} = $authid;
193 $newline{even} = $counter % 2;
194 push @finalresult, \%newline;
196 return (\@finalresult, $numbers);
203 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
204 # the authtypecode. Then, search on $a of this tag_to_report
205 # also store main entry MARC tag, to extract it at end of search
207 ##first set the authtype search and may be multiple authorities
210 my @auths=split / /,$authtypecode ;
211 foreach my $auth (@auths){
212 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
213 push @authtypecode ,$auth;
217 while ($n>1){$query= "\@or ".$query;$n--;}
223 for(my $i = 0 ; $i <= $#{$value} ; $i++)
226 if (@$tags[$i] eq "mainmainentry") {
228 $attr =" \@attr 1=Heading-Main ";
230 }elsif (@$tags[$i] eq "mainentry") {
231 $attr =" \@attr 1=Heading ";
233 $attr =" \@attr 1=Any ";
235 if (@$operator[$i] eq 'is') {
236 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
237 }elsif (@$operator[$i] eq "="){
238 $attr.=" \@attr 4=107 "; #Number Exact match
239 }elsif (@$operator[$i] eq "start"){
240 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
242 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
244 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
245 $attr =$attr."\"".@$value[$i]."\"";
250 ##Add how many queries generated
252 $query= $and.$query.$q2
257 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
258 my $orderstring= ($sortby eq "HeadingAsc"?
259 '@attr 7=1 @attr 1=Heading 0'
261 $sortby eq "HeadingDsc"?
262 '@attr 7=2 @attr 1=Heading 0'
265 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
266 $query="\@or $orderstring $query" if $orderstring;
268 $offset=0 unless $offset;
269 my $counter = $offset;
270 $length=10 unless $length;
273 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
274 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
276 $oAResult= $oAuth[0]->search($Anewq) ;
277 while (($i = ZOOM::event(\@oAuth)) != 0) {
278 my $ev = $oAuth[$i-1]->last_event();
279 last if $ev == ZOOM::Event::ZEND;
281 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
283 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
288 $nbresults=$oAResult->size();
289 my $nremains=$nbresults;
291 my @finalresult = ();
295 ##Find authid and linkid fields
296 ##we may be searching multiple authoritytypes.
297 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
298 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
299 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
300 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
302 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
303 my $rec=$oAResult->record($counter);
304 my $marcdata=$rec->raw();
306 my $separator=C4::Context->preference('authoritysep');
307 $authrecord = MARC::File::USMARC::decode($marcdata);
308 my $authid=$authrecord->field('001')->data();
309 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
310 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
311 my $sth = $dbh->prepare($query_auth_tag);
312 $sth->execute($authtypecode);
313 my $auth_tag_to_report = $sth->fetchrow;
315 my $mainentry = $authrecord->field($auth_tag_to_report);
317 foreach ($mainentry->subfields()) {
318 $reported_tag .='$'.$_->[0].$_->[1];
322 $newline{summary} = $summary;
323 $newline{authid} = $authid;
324 $newline{even} = $counter % 2;
325 $newline{reported_tag} = $reported_tag;
327 push @finalresult, \%newline;
330 for (my $z=0; $z<@finalresult; $z++){
331 my $count=CountUsage($finalresult[$z]{authid});
332 $finalresult[$z]{used}=$count;
337 # $oAResult->destroy();
338 # $oAuth[0]->destroy();
340 return (\@finalresult, $nbresults);
346 $count= &CountUsage($authid)
348 counts Usage of Authid in bibliorecords.
354 if (C4::Context->preference('NoZebra')) {
355 # Read the index Koha-Auth-Number for this authid and count the lines
356 my $result = C4::Search::NZanalyse("an=$authid");
357 my @tab = split /;/,$result;
362 $query= "an=".$authid;
363 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
368 =head2 CountUsageChildren
370 $count= &CountUsageChildren($authid)
372 counts Usage of narrower terms of Authid in bibliorecords.
376 sub CountUsageChildren {
380 =head2 GetAuthTypeCode
382 $authtypecode= &GetAuthTypeCode($authid)
384 returns authtypecode of an authid
388 sub GetAuthTypeCode {
389 #AUTHfind_authtypecode
391 my $dbh=C4::Context->dbh;
392 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
393 $sth->execute($authid);
394 my $authtypecode = $sth->fetchrow;
395 return $authtypecode;
398 =head2 GuessAuthTypeCode
400 my $authtypecode = GuessAuthTypeCode($record);
402 Get the record and tries to guess the adequate authtypecode from its content.
406 sub GuessAuthTypeCode {
408 return unless defined $record;
409 my $heading_fields = {
411 '100'=>{authtypecode=>'PERSO_NAME'},
412 '110'=>{authtypecode=>'CORPO_NAME'},
413 '111'=>{authtypecode=>'MEETI_NAME'},
414 '130'=>{authtypecode=>'UNIF_TITLE'},
415 '148'=>{authtypecode=>'CHRON_TERM'},
416 '150'=>{authtypecode=>'TOPIC_TERM'},
417 '151'=>{authtypecode=>'GEOGR_NAME'},
418 '155'=>{authtypecode=>'GENRE/FORM'},
419 '180'=>{authtypecode=>'GEN_SUBDIV'},
420 '181'=>{authtypecode=>'GEO_SUBDIV'},
421 '182'=>{authtypecode=>'CHRON_SUBD'},
422 '185'=>{authtypecode=>'FORM_SUBD'},
424 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
425 # 604 with embedded 700, 701, 702
426 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
427 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
428 #216 Trademark 716 [Reserved for future use]
429 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
430 #230 Title 500 4-- with embedded 500 605
431 #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
432 #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
433 #250 Topical subject 606
434 #260 Place access 620
435 #280 Form, genre or physical characteristics 608
438 # Could also be represented with :
440 #a = personal name entry
441 #b = corporate name entry
442 #c = territorial or geographical name
446 #g = collective uniform title
448 #i = name/collective uniform title
451 #l = form, genre or physical characteristics
453 '200'=>{authtypecode=>'NP'},
454 '210'=>{authtypecode=>'CO'},
455 '215'=>{authtypecode=>'SNG'},
456 '216'=>{authtypecode=>'TM'},
457 '220'=>{authtypecode=>'FAM'},
458 '230'=>{authtypecode=>'TU'},
459 '235'=>{authtypecode=>'CO_UNI_TI'},
460 '240'=>{authtypecode=>'SAUTTIT'},
461 '245'=>{authtypecode=>'NAME_COL'},
462 '250'=>{authtypecode=>'SNC'},
463 '260'=>{authtypecode=>'PA'},
464 '280'=>{authtypecode=>'GENRE/FORM'},
467 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
468 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
475 my $authtid = GuessAuthId($record);
477 Get the record and tries to guess the adequate authtypecode from its content.
483 return unless ($record && $record->field('001'));
484 # my $authtypecode=GuessAuthTypeCode($record);
485 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
486 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
487 # else {return $record->field($tag)->data}
488 return $record->field('001')->data;
493 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
495 returns a ref to hashref of authorities tag and subfield structure.
499 $tagslabel->{$tag}->{$subfield}->{'attribute'}
501 where attribute takes values in :
519 my ($forlibrarian,$authtypecode)= @_;
520 my $dbh=C4::Context->dbh;
521 $authtypecode="" unless $authtypecode;
523 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
526 # check that authority exists
527 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
528 $sth->execute($authtypecode);
529 my ($total) = $sth->fetchrow;
530 $authtypecode="" unless ($total >0);
532 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
533 FROM auth_tag_structure
538 $sth->execute($authtypecode);
539 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
541 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
542 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
543 $res->{$tag}->{tab} = " "; # XXX
544 $res->{$tag}->{mandatory} = $mandatory;
545 $res->{$tag}->{repeatable} = $repeatable;
548 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
549 FROM auth_subfield_structure
551 ORDER BY tagfield,tagsubfield"
553 $sth->execute($authtypecode);
556 my $authorised_value;
565 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
566 $mandatory, $repeatable, $authorised_value, $authtypecode,
567 $value_builder, $kohafield, $seealso, $hidden,
572 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
573 $res->{$tag}->{$subfield}->{tab} = $tab;
574 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
575 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
576 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
577 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
578 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
579 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
580 $res->{$tag}->{$subfield}->{seealso} = $seealso;
581 $res->{$tag}->{$subfield}->{hidden} = $hidden;
582 $res->{$tag}->{$subfield}->{isurl} = $isurl;
583 $res->{$tag}->{$subfield}->{link} = $link;
590 $authid= &AddAuthority($record, $authid,$authtypecode)
592 Either Create Or Modify existing authority.
593 returns authid of the newly created authority
598 # pass the MARC::Record to this function, and it will create the records in the authority table
599 my ($record,$authid,$authtypecode) = @_;
600 my $dbh=C4::Context->dbh;
601 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
603 # if authid empty => true add, find a new authid number
605 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
606 $format= 'UNIMARCAUTH';
612 #update date/time to 005 for marc and unimarc
613 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
614 my $f5=$record->field('005');
616 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
619 $f5->update($time.".0");
622 SetUTF8Flag($record);
623 if ($format eq "MARC21") {
624 if (!$record->leader) {
625 $record->leader($leader);
627 if (!$record->field('003')) {
628 $record->insert_fields_ordered(
629 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
632 my $date=POSIX::strftime("%y%m%d",localtime);
633 if (!$record->field('008')) {
634 $record->insert_fields_ordered(
635 MARC::Field->new('008',$date."|||a|||||| | ||| d")
638 if (!$record->field('040')) {
639 $record->insert_fields_ordered(
640 MARC::Field->new('040','','',
641 'a' => C4::Context->preference('MARCOrgCode'),
642 'c' => C4::Context->preference('MARCOrgCode')
648 if ($format eq "UNIMARCAUTH") {
649 $record->leader(" nx j22 ") unless ($record->leader());
650 my $date=POSIX::strftime("%Y%m%d",localtime);
651 if (my $string=$record->subfield('100',"a")){
652 $string=~s/fre50/frey50/;
653 $record->field('100')->update('a'=>$string);
655 elsif ($record->field('100')){
656 $record->field('100')->update('a'=>$date."afrey50 ba0");
658 $record->append_fields(
659 MARC::Field->new('100',' ',' '
660 ,'a'=>$date."afrey50 ba0")
664 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
665 if (!$authid and $format eq "MARC21") {
666 # only need to do this fix when modifying an existing authority
667 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
669 if (my $field=$record->field($auth_type_tag)){
670 $field->update($auth_type_subfield=>$authtypecode);
673 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
679 my $sth=$dbh->prepare("select max(authid) from auth_header");
681 ($authid)=$sth->fetchrow;
683 ##Insert the recordID in MARC record
684 unless ($record->field('001') && $record->field('001')->data() eq $authid){
685 $record->delete_field($record->field('001'));
686 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
689 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
690 # warn "auth_exists = $auth_exists";
693 $oldRecord=GetAuthority($authid);
694 $record->add_fields('001',$authid) unless ($record->field('001'));
695 # warn "\n\n\n enregistrement".$record->as_formatted;
696 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
697 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
701 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
702 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
705 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
712 $authid= &DelAuthority($authid)
720 my $dbh=C4::Context->dbh;
722 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
723 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
724 $sth->execute($authid);
728 my ($authid,$record,$authtypecode,$merge)=@_;
729 my $dbh=C4::Context->dbh;
730 #Now rewrite the $record to table with an add
731 my $oldrecord=GetAuthority($authid);
732 $authid=AddAuthority($record,$authid,$authtypecode);
734 ### If a library thinks that updating all biblios is a long process and wishes to leave that to a cron job to use merge_authotities.p
735 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
736 ### the $merge flag is now depreceated and will be removed at code cleaning
737 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
738 &merge($authid,$oldrecord,$authid,$record);
740 # save the file in tmp/modified_authorities
741 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
742 unless (opendir(DIR,"$cgidir")) {
743 $cgidir = C4::Context->intranetdir."/";
747 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
748 open AUTH, "> $filename";
755 =head2 GetAuthorityXML
757 $marcxml= &GetAuthorityXML( $authid)
759 returns xml form of record $authid
763 sub GetAuthorityXML {
764 # Returns MARC::XML of the authority passed in parameter.
766 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
767 my $dbh=C4::Context->dbh;
768 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
769 $sth->execute($authid);
770 my ($marcxml)=$sth->fetchrow;
774 # for MARC21, call GetAuthority instead of
775 # getting the XML directly since we may
776 # need to fix up the location of the authority
777 # code -- note that this is reasonably safe
778 # because GetAuthorityXML is used only by the
779 # indexing processes like zebraqueue_start.pl
780 my $record = GetAuthority($authid);
781 return $record->as_xml_record('MARC21');
787 $record= &GetAuthority( $authid)
789 Returns MARC::Record of the authority passed in parameter.
795 my $dbh=C4::Context->dbh;
796 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
797 $sth->execute($authid);
798 my ($authtypecode, $marcxml) = $sth->fetchrow;
799 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
800 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
801 return undef if ($@);
802 $record->encoding('UTF-8');
803 if (C4::Context->preference("marcflavour") eq "MARC21") {
804 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
805 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
812 $result = &GetAuthType($authtypecode)
814 If the authority type specified by C<$authtypecode> exists,
815 returns a hashref of the type's fields. If the type
816 does not exist, returns undef.
821 my ($authtypecode) = @_;
822 my $dbh=C4::Context->dbh;
824 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
825 # type (FIXME but why?)
826 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
827 $sth->execute($authtypecode);
828 if (my $res = $sth->fetchrow_hashref) {
837 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
838 my $dbh=C4::Context->dbh;
840 my $record = MARC::Record->new();
841 #---- TODO : the leader is missing
843 # my %subfieldlist=();
844 my $prevvalue; # if tag <10
845 my $field; # if tag >=10
846 for (my $i=0; $i< @$rtags; $i++) {
847 # rebuild MARC::Record
848 if (@$rtags[$i] ne $prevtag) {
851 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
855 $record->add_fields($field);
858 $indicators{@$rtags[$i]}.=' ';
859 if (@$rtags[$i] <10) {
860 $prevvalue= @$rvalues[$i];
864 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
866 $prevtag = @$rtags[$i];
868 if (@$rtags[$i] <10) {
869 $prevvalue=@$rvalues[$i];
871 if (length(@$rvalues[$i])>0) {
872 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
875 $prevtag= @$rtags[$i];
878 # the last has not been included inside the loop... do it now !
879 $record->add_fields($field) if $field;
883 =head2 FindDuplicateAuthority
885 $record= &FindDuplicateAuthority( $record, $authtypecode)
887 return $authid,Summary if duplicate is found.
889 Comments : an improvement would be to return All the records that match.
893 sub FindDuplicateAuthority {
895 my ($record,$authtypecode)=@_;
896 # warn "IN for ".$record->as_formatted;
897 my $dbh = C4::Context->dbh;
898 # warn "".$record->as_formatted;
899 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
900 $sth->execute($authtypecode);
901 my ($auth_tag_to_report) = $sth->fetchrow;
903 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
904 # build a request for SearchAuthorities
905 my $query='at='.$authtypecode.' ';
906 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
907 if ($record->field($auth_tag_to_report)) {
908 foreach ($record->field($auth_tag_to_report)->subfields()) {
909 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
912 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
913 # there is at least 1 result => return the 1st one
915 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
916 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
918 # no result, returns nothing
924 $text= &BuildSummary( $record, $authid, $authtypecode)
926 return HTML encoded Summary
928 Comment : authtypecode can be infered from both record and authid.
929 Moreover, authid can also be inferred from $record.
930 Would it be interesting to delete those things.
935 ## give this a Marc record to return summary
936 my ($record,$authid,$authtypecode)=@_;
937 my $dbh=C4::Context->dbh;
939 # handle $authtypecode is NULL or eq ""
941 my $authref = GetAuthType($authtypecode);
942 $summary = $authref->{summary};
944 # FIXME: should use I18N.pm
946 $language{'fre'}="Français";
947 $language{'eng'}="Anglais";
948 $language{'ger'}="Allemand";
949 $language{'ita'}="Italien";
950 $language{'spa'}="Espagnol";
952 $thesaurus{'1'}="Peuples";
953 $thesaurus{'2'}="Anthroponymes";
954 $thesaurus{'3'}="Oeuvres";
955 $thesaurus{'4'}="Chronologie";
956 $thesaurus{'5'}="Lieux";
957 $thesaurus{'6'}="Sujets";
959 my @fields = $record->fields();
961 # if the library has a summary defined, use it. Otherwise, build a standard one
962 # FIXME - it appears that the summary field in the authority frameworks
963 # can work as a display template. However, this doesn't
964 # suit the MARC21 version, so for now the "templating"
965 # feature will be enabled only for UNIMARC for backwards
967 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
968 my @fields = $record->fields();
969 # $reported_tag = '$9'.$result[$counter];
971 foreach my $field (@fields) {
972 my $tag = $field->tag();
973 my $tagvalue = $field->as_string();
974 my $localsummary= $summary;
975 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
978 $reported_tag.='$3'.$field->data();
981 my @subf = $field->subfields;
982 for my $i (0..$#subf) {
983 my $subfieldcode = $subf[$i][0];
984 my $subfieldvalue = $subf[$i][1];
985 my $tagsubf = $tag.$subfieldcode;
986 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
989 push @stringssummary, $localsummary if ($localsummary ne $summary);
992 $resultstring = join(" -- ",@stringssummary);
993 $resultstring =~ s/\[(.*?)\]//g;
994 $resultstring =~ s/\n/<br>/g;
995 $summary = $resultstring;
1005 my @fields = $record->fields();
1006 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1007 # construct UNIMARC summary, that is quite different from MARC21 one
1009 foreach my $field ($record->field('2..')) {
1010 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1013 foreach my $field ($record->field('3..')) {
1014 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1016 foreach my $field ($record->field('4..')) {
1017 if ($field->subfield('2')) {
1018 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1019 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1023 foreach my $field ($record->field('5..')) {
1025 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1026 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1027 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1028 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1029 } elsif ($field->subfield('a')) {
1030 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1034 foreach my $field ($record->field('7..')) {
1035 my $lang = substr($field->subfield('8'),3,3);
1036 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1038 $broaderterms =~s/-- \n$//;
1039 $narrowerterms =~s/-- \n$//;
1040 $seealso =~s/-- \n$//;
1042 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1043 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1044 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1045 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1046 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1047 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1049 # construct MARC21 summary
1050 # FIXME - looping over 1XX is questionable
1051 # since MARC21 authority should have only one 1XX
1052 foreach my $field ($record->field('1..')) {
1053 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1054 # in MARC21 -- purely local tags really ought to be
1056 if ($record->field('100')) {
1057 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1058 } elsif ($record->field('110')) {
1059 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1060 } elsif ($record->field('111')) {
1061 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1062 } elsif ($record->field('130')) {
1063 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1064 } elsif ($record->field('148')) {
1065 $heading.= $field->as_string('abvxyz68');
1066 } elsif ($record->field('150')) {
1067 # $heading.= $field->as_string('abvxyz68');
1068 $heading.= $field->as_formatted();
1069 my $tag=$field->tag();
1070 $heading=~s /^$tag//g;
1071 $heading =~s /\_/\$/g;
1072 } elsif ($record->field('151')) {
1073 $heading.= $field->as_string('avxyz68');
1074 } elsif ($record->field('155')) {
1075 $heading.= $field->as_string('abvxyz68');
1076 } elsif ($record->field('180')) {
1077 $heading.= $field->as_string('vxyz68');
1078 } elsif ($record->field('181')) {
1079 $heading.= $field->as_string('vxyz68');
1080 } elsif ($record->field('182')) {
1081 $heading.= $field->as_string('vxyz68');
1082 } elsif ($record->field('185')) {
1083 $heading.= $field->as_string('vxyz68');
1085 $heading.= $field->as_string();
1088 foreach my $field ($record->field('4..')) {
1089 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1091 foreach my $field ($record->field('5..')) {
1092 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1094 $summary .= ": " if $summary;
1095 $summary.=$heading.$seeheading.$altheading;
1101 =head2 BuildUnimarcHierarchies
1103 $text= &BuildUnimarcHierarchies( $authid, $force)
1105 return text containing trees for hierarchies
1106 for them to be stored in auth_header
1109 122,1314,2452;1324,2342,3,2452
1113 sub BuildUnimarcHierarchies{
1114 my $authid = shift @_;
1115 # warn "authid : $authid";
1116 my $force = shift @_;
1118 my $dbh=C4::Context->dbh;
1120 my $data = GetHeaderAuthority($authid);
1121 if ($data->{'authtrees'} and not $force){
1122 return $data->{'authtrees'};
1123 } elsif ($data->{'authtrees'}){
1124 $hierarchies=$data->{'authtrees'};
1126 my $record = GetAuthority($authid);
1129 foreach my $field ($record->field('550')){
1130 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1131 my $parentrecord = GetAuthority($field->subfield('3'));
1132 my $localresult=$hierarchies;
1134 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1137 @trees = split(/;/,$trees);
1139 push @trees, $trees;
1144 @globalresult = (@globalresult,@trees);
1147 $hierarchies=join(";",@globalresult);
1150 #Unless there is no ancestor, I am alone.
1151 $hierarchies="$authid" unless ($hierarchies);
1153 AddAuthorityTrees($authid,$hierarchies);
1154 return $hierarchies;
1157 =head2 BuildUnimarcHierarchy
1159 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1161 return a hashref in order to display hierarchy for record and final Authid $authid
1172 Those two latest ones should disappear soon.
1176 sub BuildUnimarcHierarchy{
1177 my $record = shift @_;
1178 my $class = shift @_;
1179 my $authid_constructed = shift @_;
1180 return undef unless ($record);
1181 my $authid=$record->subfield('2..','3');
1183 my $parents=""; my $children="";
1184 my (@loopparents,@loopchildren);
1185 foreach my $field ($record->field('550')){
1186 if ($field->subfield('5') && $field->subfield('a')){
1187 if ($field->subfield('5') eq 'h'){
1188 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1189 }elsif ($field->subfield('5') eq 'g'){
1190 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1192 # brothers could get in there with an else
1195 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1196 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1197 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1198 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1199 $cell{"class"}=$class;
1200 $cell{"loopauthid"}=$authid;
1201 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1202 $cell{"value"}=$record->subfield('2..',"a");
1206 =head2 GetHeaderAuthority
1208 $ref= &GetHeaderAuthority( $authid)
1210 return a hashref in order auth_header table data
1214 sub GetHeaderAuthority{
1215 my $authid = shift @_;
1216 my $sql= "SELECT * from auth_header WHERE authid = ?";
1217 my $dbh=C4::Context->dbh;
1218 my $rq= $dbh->prepare($sql);
1219 $rq->execute($authid);
1220 my $data= $rq->fetchrow_hashref;
1224 =head2 AddAuthorityTrees
1226 $ref= &AddAuthorityTrees( $authid, $trees)
1228 return success or failure
1232 sub AddAuthorityTrees{
1233 my $authid = shift @_;
1234 my $trees = shift @_;
1235 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1236 my $dbh=C4::Context->dbh;
1237 my $rq= $dbh->prepare($sql);
1238 return $rq->execute($trees,$authid);
1243 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1245 Could add some feature : Migrating from a typecode to an other for instance.
1246 Then we should add some new parameter : bibliotargettag, authtargettag
1251 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1252 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1253 my $dbh=C4::Context->dbh;
1254 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1255 my $authtypecodeto = GetAuthTypeCode($mergeto);
1256 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1257 # return if authority does not exist
1258 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1259 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1260 # search the tag to report
1261 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1262 $sth->execute($authtypecodefrom);
1263 my ($auth_tag_to_report_from) = $sth->fetchrow;
1264 $sth->execute($authtypecodeto);
1265 my ($auth_tag_to_report_to) = $sth->fetchrow;
1268 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1270 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1273 # search all biblio tags using this authority.
1274 #Getting marcbiblios impacted by the change.
1275 if (C4::Context->preference('NoZebra')) {
1277 my $dbh=C4::Context->dbh;
1278 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1280 while (my $biblionumbers=$rq->fetchrow){
1281 my @biblionumbers=split /;/,$biblionumbers;
1282 foreach (@biblionumbers) {
1283 if ($_=~/(\d+),.*/) {
1284 my $marc=GetMarcBiblio($1);
1285 push @reccache,$marc;
1291 my $oConnection=C4::Context->Zconn("biblioserver",0);
1292 $oConnection->option("preferredRecordSyntax"=>"XML");
1294 $query= "an=".$mergefrom;
1295 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1298 $count=$oResult->size();
1301 while ( $z<$count ) {
1303 $rec=$oResult->record($z);
1304 my $marcdata = $rec->raw();
1305 push @reccache, $marcdata;
1308 $oConnection->destroy();
1310 #warn scalar(@reccache)." biblios to update";
1311 # Get All candidate Tags for the change
1312 # (This will reduce the search scope in marc records).
1313 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1314 $sth->execute($authtypecodefrom);
1315 my @tags_using_authtype;
1316 while (my ($tagfield) = $sth->fetchrow) {
1317 push @tags_using_authtype,$tagfield ;
1320 if ($authtypecodeto ne $authtypecodefrom){
1321 # If many tags, take the first
1322 $sth->execute($authtypecodeto);
1323 $tag_to=$sth->fetchrow;
1326 # BulkEdit marc records
1327 # May be used as a template for a bulkedit field
1328 foreach my $marcrecord(@reccache){
1330 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1331 foreach my $tagfield (@tags_using_authtype){
1332 # warn "tagfield : $tagfield ";
1333 foreach my $field ($marcrecord->field($tagfield)){
1334 my $auth_number=$field->subfield("9");
1335 my $tag=$field->tag();
1336 if ($auth_number==$mergefrom) {
1337 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1339 foreach my $subfield (@record_to) {
1340 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1341 $exclude.= $subfield->[0];
1343 $exclude='['.$exclude.']';
1344 # add subfields in $field not included in @record_to
1345 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1346 foreach my $subfield (@restore) {
1347 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1349 $marcrecord->delete_field($field);
1350 $marcrecord->insert_grouped_field($field_to);
1355 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1358 $biblionumber=$marcrecord->field($bibliotag)->data;
1361 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1363 unless ($biblionumber){
1364 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1368 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1369 $counteditedbiblio++;
1370 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1373 return $counteditedbiblio;
1374 # now, find every other authority linked with this authority
1375 # now, find every other authority linked with this authority
1376 # my $oConnection=C4::Context->Zconn("authorityserver");
1378 # # att 9210 Auth-Internal-authtype
1379 # # att 9220 Auth-Internal-LN
1380 # # ccl.properties to add for authorities
1381 # $query= "= ".$mergefrom;
1382 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1383 # my $count=$oResult->size() if ($oResult);
1386 # while ( $z<$count ) {
1388 # $rec=$oResult->record($z);
1389 # my $marcdata = $rec->raw();
1390 # push @reccache, $marcdata;
1393 # $oResult->destroy();
1394 # foreach my $marc(@reccache){
1397 # $marcrecord = MARC::File::USMARC::decode($marc);
1398 # foreach my $tagfield (@tags_using_authtype){
1399 # $tagfield=substr($tagfield,0,3);
1400 # my @tags = $marcrecord->field($tagfield);
1401 # foreach my $tag (@tags){
1402 # my $tagsubs=$tag->subfield("9");
1403 # #warn "$tagfield:$tagsubs:$mergefrom";
1404 # if ($tagsubs== $mergefrom) {
1405 # $tag->update("9" =>$mergeto);
1406 # foreach my $subfield (@record_to) {
1407 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1408 # $tag->update($subfield->[0] =>$subfield->[1]);
1411 # $marcrecord->delete_field($tag);
1412 # $marcrecord->add_fields($tag);
1415 # }#foreach tagfield
1416 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1418 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1424 =head2 get_auth_type_location
1426 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1428 Get the tag and subfield used to store the heading type
1429 for indexing purposes. The C<$auth_type> parameter is
1430 optional; if it is not supplied, assume ''.
1432 This routine searches the MARC authority framework
1433 for the tag and subfield whose kohafield is
1434 C<auth_header.authtypecode>; if no such field is
1435 defined in the framework, default to the hardcoded value
1436 specific to the MARC format.
1440 sub get_auth_type_location {
1441 my $auth_type_code = @_ ? shift : '';
1443 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1444 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1445 return ($tag, $subfield);
1447 if (C4::Context->preference('marcflavour') eq "MARC21") {
1448 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1450 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1455 END { } # module clean-up code here (global destructor)
1462 Koha Development Team <http://koha-community.org/>
1464 Paul POULAIN paul.poulain@free.fr