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--;}
224 for(my $i = 0 ; $i <= $#{$value} ; $i++)
227 ##If mainentry search $a tag
228 if (@$tags[$i] eq "mainmainentry") {
230 # FIXME: 'Heading-Main' index not yet defined in zebra
231 # $attr =" \@attr 1=Heading-Main ";
232 $attr =" \@attr 1=Heading ";
234 }elsif (@$tags[$i] eq "mainentry") {
235 $attr =" \@attr 1=Heading ";
237 $attr =" \@attr 1=Any ";
239 if (@$operator[$i] eq 'is') {
240 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
241 }elsif (@$operator[$i] eq "="){
242 $attr.=" \@attr 4=107 "; #Number Exact match
243 }elsif (@$operator[$i] eq "start"){
244 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
246 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
248 $attr =$attr."\"".@$value[$i]."\"";
254 ##Add how many queries generated
256 $query= $and x $attr_cnt . $query . $q2;
261 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
262 my $orderstring= ($sortby eq "HeadingAsc"?
263 '@attr 7=1 @attr 1=Heading 0'
265 $sortby eq "HeadingDsc"?
266 '@attr 7=2 @attr 1=Heading 0'
269 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
270 $query="\@or $orderstring $query" if $orderstring;
272 $offset=0 unless $offset;
273 my $counter = $offset;
274 $length=10 unless $length;
277 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
278 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
280 $oAResult= $oAuth[0]->search($Anewq) ;
281 while (($i = ZOOM::event(\@oAuth)) != 0) {
282 my $ev = $oAuth[$i-1]->last_event();
283 last if $ev == ZOOM::Event::ZEND;
285 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
287 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
292 $nbresults=$oAResult->size();
293 my $nremains=$nbresults;
295 my @finalresult = ();
299 ##Find authid and linkid fields
300 ##we may be searching multiple authoritytypes.
301 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
302 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
303 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
304 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
306 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
307 my $rec=$oAResult->record($counter);
308 my $marcdata=$rec->raw();
310 my $separator=C4::Context->preference('authoritysep');
311 $authrecord = MARC::File::USMARC::decode($marcdata);
312 my $authid=$authrecord->field('001')->data();
313 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
314 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
315 my $sth = $dbh->prepare($query_auth_tag);
316 $sth->execute($authtypecode);
317 my $auth_tag_to_report = $sth->fetchrow;
319 my $mainentry = $authrecord->field($auth_tag_to_report);
321 foreach ($mainentry->subfields()) {
322 $reported_tag .='$'.$_->[0].$_->[1];
326 $newline{summary} = $summary;
327 $newline{authid} = $authid;
328 $newline{even} = $counter % 2;
329 $newline{reported_tag} = $reported_tag;
331 push @finalresult, \%newline;
334 for (my $z=0; $z<@finalresult; $z++){
335 my $count=CountUsage($finalresult[$z]{authid});
336 $finalresult[$z]{used}=$count;
341 # $oAResult->destroy();
342 # $oAuth[0]->destroy();
344 return (\@finalresult, $nbresults);
350 $count= &CountUsage($authid)
352 counts Usage of Authid in bibliorecords.
358 if (C4::Context->preference('NoZebra')) {
359 # Read the index Koha-Auth-Number for this authid and count the lines
360 my $result = C4::Search::NZanalyse("an=$authid");
361 my @tab = split /;/,$result;
366 $query= "an=".$authid;
367 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
372 =head2 CountUsageChildren
374 $count= &CountUsageChildren($authid)
376 counts Usage of narrower terms of Authid in bibliorecords.
380 sub CountUsageChildren {
384 =head2 GetAuthTypeCode
386 $authtypecode= &GetAuthTypeCode($authid)
388 returns authtypecode of an authid
392 sub GetAuthTypeCode {
393 #AUTHfind_authtypecode
395 my $dbh=C4::Context->dbh;
396 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
397 $sth->execute($authid);
398 my $authtypecode = $sth->fetchrow;
399 return $authtypecode;
402 =head2 GuessAuthTypeCode
404 my $authtypecode = GuessAuthTypeCode($record);
406 Get the record and tries to guess the adequate authtypecode from its content.
410 sub GuessAuthTypeCode {
412 return unless defined $record;
413 my $heading_fields = {
415 '100'=>{authtypecode=>'PERSO_NAME'},
416 '110'=>{authtypecode=>'CORPO_NAME'},
417 '111'=>{authtypecode=>'MEETI_NAME'},
418 '130'=>{authtypecode=>'UNIF_TITLE'},
419 '148'=>{authtypecode=>'CHRON_TERM'},
420 '150'=>{authtypecode=>'TOPIC_TERM'},
421 '151'=>{authtypecode=>'GEOGR_NAME'},
422 '155'=>{authtypecode=>'GENRE/FORM'},
423 '180'=>{authtypecode=>'GEN_SUBDIV'},
424 '181'=>{authtypecode=>'GEO_SUBDIV'},
425 '182'=>{authtypecode=>'CHRON_SUBD'},
426 '185'=>{authtypecode=>'FORM_SUBD'},
428 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
429 # 604 with embedded 700, 701, 702
430 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
431 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
432 #216 Trademark 716 [Reserved for future use]
433 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
434 #230 Title 500 4-- with embedded 500 605
435 #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
436 #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
437 #250 Topical subject 606
438 #260 Place access 620
439 #280 Form, genre or physical characteristics 608
442 # Could also be represented with :
444 #a = personal name entry
445 #b = corporate name entry
446 #c = territorial or geographical name
450 #g = collective uniform title
452 #i = name/collective uniform title
455 #l = form, genre or physical characteristics
457 '200'=>{authtypecode=>'NP'},
458 '210'=>{authtypecode=>'CO'},
459 '215'=>{authtypecode=>'SNG'},
460 '216'=>{authtypecode=>'TM'},
461 '220'=>{authtypecode=>'FAM'},
462 '230'=>{authtypecode=>'TU'},
463 '235'=>{authtypecode=>'CO_UNI_TI'},
464 '240'=>{authtypecode=>'SAUTTIT'},
465 '245'=>{authtypecode=>'NAME_COL'},
466 '250'=>{authtypecode=>'SNC'},
467 '260'=>{authtypecode=>'PA'},
468 '280'=>{authtypecode=>'GENRE/FORM'},
471 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
472 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
479 my $authtid = GuessAuthId($record);
481 Get the record and tries to guess the adequate authtypecode from its content.
487 return unless ($record && $record->field('001'));
488 # my $authtypecode=GuessAuthTypeCode($record);
489 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
490 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
491 # else {return $record->field($tag)->data}
492 return $record->field('001')->data;
497 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
499 returns a ref to hashref of authorities tag and subfield structure.
503 $tagslabel->{$tag}->{$subfield}->{'attribute'}
505 where attribute takes values in :
523 my ($forlibrarian,$authtypecode)= @_;
524 my $dbh=C4::Context->dbh;
525 $authtypecode="" unless $authtypecode;
527 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
530 # check that authority exists
531 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
532 $sth->execute($authtypecode);
533 my ($total) = $sth->fetchrow;
534 $authtypecode="" unless ($total >0);
536 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
537 FROM auth_tag_structure
542 $sth->execute($authtypecode);
543 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
545 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
546 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
547 $res->{$tag}->{tab} = " "; # XXX
548 $res->{$tag}->{mandatory} = $mandatory;
549 $res->{$tag}->{repeatable} = $repeatable;
552 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
553 FROM auth_subfield_structure
555 ORDER BY tagfield,tagsubfield"
557 $sth->execute($authtypecode);
560 my $authorised_value;
569 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
570 $mandatory, $repeatable, $authorised_value, $authtypecode,
571 $value_builder, $kohafield, $seealso, $hidden,
576 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
577 $res->{$tag}->{$subfield}->{tab} = $tab;
578 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
579 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
580 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
581 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
582 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
583 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
584 $res->{$tag}->{$subfield}->{seealso} = $seealso;
585 $res->{$tag}->{$subfield}->{hidden} = $hidden;
586 $res->{$tag}->{$subfield}->{isurl} = $isurl;
587 $res->{$tag}->{$subfield}->{link} = $link;
594 $authid= &AddAuthority($record, $authid,$authtypecode)
596 Either Create Or Modify existing authority.
597 returns authid of the newly created authority
602 # pass the MARC::Record to this function, and it will create the records in the authority table
603 my ($record,$authid,$authtypecode) = @_;
604 my $dbh=C4::Context->dbh;
605 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
607 # if authid empty => true add, find a new authid number
609 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
610 $format= 'UNIMARCAUTH';
616 #update date/time to 005 for marc and unimarc
617 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
618 my $f5=$record->field('005');
620 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
623 $f5->update($time.".0");
626 if ($format eq "MARC21") {
627 if (!$record->leader) {
628 $record->leader($leader);
630 if (!$record->field('003')) {
631 $record->insert_fields_ordered(
632 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
635 my $date=POSIX::strftime("%y%m%d",localtime);
636 if (!$record->field('008')) {
637 $record->insert_fields_ordered(
638 MARC::Field->new('008',$date."|||a|||||| | ||| d")
641 if (!$record->field('040')) {
642 $record->insert_fields_ordered(
643 MARC::Field->new('040','','',
644 'a' => C4::Context->preference('MARCOrgCode'),
645 'c' => C4::Context->preference('MARCOrgCode')
651 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
652 $record->leader(" nx j22 ");
653 my $date=POSIX::strftime("%Y%m%d",localtime);
654 if ($record->field('100')){
655 $record->field('100')->update('a'=>$date."afrey50 ba0");
657 $record->append_fields(
658 MARC::Field->new('100',' ',' '
659 ,'a'=>$date."afrey50 ba0")
663 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
664 if (!$authid and $format eq "MARC21") {
665 # only need to do this fix when modifying an existing authority
666 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
668 if (my $field=$record->field($auth_type_tag)){
669 $field->update($auth_type_subfield=>$authtypecode);
672 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
678 my $sth=$dbh->prepare("select max(authid) from auth_header");
680 ($authid)=$sth->fetchrow;
682 ##Insert the recordID in MARC record
683 unless ($record->field('001') && $record->field('001')->data() eq $authid){
684 $record->delete_field($record->field('001'));
685 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
688 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
689 # warn "auth_exists = $auth_exists";
692 $oldRecord=GetAuthority($authid);
693 $record->add_fields('001',$authid) unless ($record->field('001'));
694 # warn "\n\n\n enregistrement".$record->as_formatted;
695 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
696 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
700 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
701 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
704 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
711 $authid= &DelAuthority($authid)
719 my $dbh=C4::Context->dbh;
721 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
722 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
723 $sth->execute($authid);
727 my ($authid,$record,$authtypecode,$merge)=@_;
728 my $dbh=C4::Context->dbh;
729 #Now rewrite the $record to table with an add
730 my $oldrecord=GetAuthority($authid);
731 $authid=AddAuthority($record,$authid,$authtypecode);
733 ### 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
734 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
735 ### the $merge flag is now depreceated and will be removed at code cleaning
736 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
737 &merge($authid,$oldrecord,$authid,$record);
739 # save the file in tmp/modified_authorities
740 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
741 unless (opendir(DIR,"$cgidir")) {
742 $cgidir = C4::Context->intranetdir."/";
746 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
747 open AUTH, "> $filename";
754 =head2 GetAuthorityXML
756 $marcxml= &GetAuthorityXML( $authid)
758 returns xml form of record $authid
762 sub GetAuthorityXML {
763 # Returns MARC::XML of the authority passed in parameter.
765 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
766 my $dbh=C4::Context->dbh;
767 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
768 $sth->execute($authid);
769 my ($marcxml)=$sth->fetchrow;
773 # for MARC21, call GetAuthority instead of
774 # getting the XML directly since we may
775 # need to fix up the location of the authority
776 # code -- note that this is reasonably safe
777 # because GetAuthorityXML is used only by the
778 # indexing processes like zebraqueue_start.pl
779 my $record = GetAuthority($authid);
780 return $record->as_xml_record('MARC21');
786 $record= &GetAuthority( $authid)
788 Returns MARC::Record of the authority passed in parameter.
794 my $dbh=C4::Context->dbh;
795 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
796 $sth->execute($authid);
797 my ($authtypecode, $marcxml) = $sth->fetchrow;
798 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
799 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
800 return undef if ($@);
801 $record->encoding('UTF-8');
802 if (C4::Context->preference("marcflavour") eq "MARC21") {
803 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
804 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
811 $result = &GetAuthType($authtypecode)
813 If the authority type specified by C<$authtypecode> exists,
814 returns a hashref of the type's fields. If the type
815 does not exist, returns undef.
820 my ($authtypecode) = @_;
821 my $dbh=C4::Context->dbh;
823 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
824 # type (FIXME but why?)
825 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
826 $sth->execute($authtypecode);
827 if (my $res = $sth->fetchrow_hashref) {
836 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
837 my $dbh=C4::Context->dbh;
839 my $record = MARC::Record->new();
840 #---- TODO : the leader is missing
842 # my %subfieldlist=();
843 my $prevvalue; # if tag <10
844 my $field; # if tag >=10
845 for (my $i=0; $i< @$rtags; $i++) {
846 # rebuild MARC::Record
847 if (@$rtags[$i] ne $prevtag) {
850 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
854 $record->add_fields($field);
857 $indicators{@$rtags[$i]}.=' ';
858 if (@$rtags[$i] <10) {
859 $prevvalue= @$rvalues[$i];
863 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
865 $prevtag = @$rtags[$i];
867 if (@$rtags[$i] <10) {
868 $prevvalue=@$rvalues[$i];
870 if (length(@$rvalues[$i])>0) {
871 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
874 $prevtag= @$rtags[$i];
877 # the last has not been included inside the loop... do it now !
878 $record->add_fields($field) if $field;
882 =head2 FindDuplicateAuthority
884 $record= &FindDuplicateAuthority( $record, $authtypecode)
886 return $authid,Summary if duplicate is found.
888 Comments : an improvement would be to return All the records that match.
892 sub FindDuplicateAuthority {
894 my ($record,$authtypecode)=@_;
895 # warn "IN for ".$record->as_formatted;
896 my $dbh = C4::Context->dbh;
897 # warn "".$record->as_formatted;
898 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
899 $sth->execute($authtypecode);
900 my ($auth_tag_to_report) = $sth->fetchrow;
902 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
903 # build a request for SearchAuthorities
904 my $query='at='.$authtypecode.' ';
905 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
906 if ($record->field($auth_tag_to_report)) {
907 foreach ($record->field($auth_tag_to_report)->subfields()) {
908 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
911 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
912 # there is at least 1 result => return the 1st one
914 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
915 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
917 # no result, returns nothing
923 $text= &BuildSummary( $record, $authid, $authtypecode)
925 return HTML encoded Summary
927 Comment : authtypecode can be infered from both record and authid.
928 Moreover, authid can also be inferred from $record.
929 Would it be interesting to delete those things.
934 ## give this a Marc record to return summary
935 my ($record,$authid,$authtypecode)=@_;
936 my $dbh=C4::Context->dbh;
938 # handle $authtypecode is NULL or eq ""
940 my $authref = GetAuthType($authtypecode);
941 $summary = $authref->{summary};
943 # FIXME: should use I18N.pm
945 $language{'fre'}="Français";
946 $language{'eng'}="Anglais";
947 $language{'ger'}="Allemand";
948 $language{'ita'}="Italien";
949 $language{'spa'}="Espagnol";
951 $thesaurus{'1'}="Peuples";
952 $thesaurus{'2'}="Anthroponymes";
953 $thesaurus{'3'}="Oeuvres";
954 $thesaurus{'4'}="Chronologie";
955 $thesaurus{'5'}="Lieux";
956 $thesaurus{'6'}="Sujets";
958 my @fields = $record->fields();
960 # if the library has a summary defined, use it. Otherwise, build a standard one
961 # FIXME - it appears that the summary field in the authority frameworks
962 # can work as a display template. However, this doesn't
963 # suit the MARC21 version, so for now the "templating"
964 # feature will be enabled only for UNIMARC for backwards
966 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
967 my @fields = $record->fields();
968 # $reported_tag = '$9'.$result[$counter];
970 foreach my $field (@fields) {
971 my $tag = $field->tag();
972 my $tagvalue = $field->as_string();
973 my $localsummary= $summary;
974 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
977 $reported_tag.='$3'.$field->data();
980 my @subf = $field->subfields;
981 for my $i (0..$#subf) {
982 my $subfieldcode = $subf[$i][0];
983 my $subfieldvalue = $subf[$i][1];
984 my $tagsubf = $tag.$subfieldcode;
985 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
988 push @stringssummary, $localsummary if ($localsummary ne $summary);
991 $resultstring = join(" -- ",@stringssummary);
992 $resultstring =~ s/\[(.*?)\]//g;
993 $resultstring =~ s/\n/<br>/g;
994 $summary = $resultstring;
1004 my @fields = $record->fields();
1005 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1006 # construct UNIMARC summary, that is quite different from MARC21 one
1008 foreach my $field ($record->field('2..')) {
1009 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1012 foreach my $field ($record->field('3..')) {
1013 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1015 foreach my $field ($record->field('4..')) {
1016 if ($field->subfield('2')) {
1017 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1018 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1022 foreach my $field ($record->field('5..')) {
1024 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1025 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1026 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1027 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1028 } elsif ($field->subfield('a')) {
1029 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1033 foreach my $field ($record->field('7..')) {
1034 my $lang = substr($field->subfield('8'),3,3);
1035 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1037 $broaderterms =~s/-- \n$//;
1038 $narrowerterms =~s/-- \n$//;
1039 $seealso =~s/-- \n$//;
1041 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1042 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1043 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1044 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1045 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1046 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1048 # construct MARC21 summary
1049 # FIXME - looping over 1XX is questionable
1050 # since MARC21 authority should have only one 1XX
1051 foreach my $field ($record->field('1..')) {
1052 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1053 # in MARC21 -- purely local tags really ought to be
1055 if ($record->field('100')) {
1056 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1057 } elsif ($record->field('110')) {
1058 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1059 } elsif ($record->field('111')) {
1060 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1061 } elsif ($record->field('130')) {
1062 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1063 } elsif ($record->field('148')) {
1064 $heading.= $field->as_string('abvxyz68');
1065 } elsif ($record->field('150')) {
1066 # $heading.= $field->as_string('abvxyz68');
1067 $heading.= $field->as_formatted();
1068 my $tag=$field->tag();
1069 $heading=~s /^$tag//g;
1070 $heading =~s /\_/\$/g;
1071 } elsif ($record->field('151')) {
1072 $heading.= $field->as_string('avxyz68');
1073 } elsif ($record->field('155')) {
1074 $heading.= $field->as_string('abvxyz68');
1075 } elsif ($record->field('180')) {
1076 $heading.= $field->as_string('vxyz68');
1077 } elsif ($record->field('181')) {
1078 $heading.= $field->as_string('vxyz68');
1079 } elsif ($record->field('182')) {
1080 $heading.= $field->as_string('vxyz68');
1081 } elsif ($record->field('185')) {
1082 $heading.= $field->as_string('vxyz68');
1084 $heading.= $field->as_string();
1087 foreach my $field ($record->field('4..')) {
1088 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1090 foreach my $field ($record->field('5..')) {
1091 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1093 $summary .= ": " if $summary;
1094 $summary.=$heading.$seeheading.$altheading;
1100 =head2 BuildUnimarcHierarchies
1102 $text= &BuildUnimarcHierarchies( $authid, $force)
1104 return text containing trees for hierarchies
1105 for them to be stored in auth_header
1108 122,1314,2452;1324,2342,3,2452
1112 sub BuildUnimarcHierarchies{
1113 my $authid = shift @_;
1114 # warn "authid : $authid";
1115 my $force = shift @_;
1117 my $dbh=C4::Context->dbh;
1119 my $data = GetHeaderAuthority($authid);
1120 if ($data->{'authtrees'} and not $force){
1121 return $data->{'authtrees'};
1122 } elsif ($data->{'authtrees'}){
1123 $hierarchies=$data->{'authtrees'};
1125 my $record = GetAuthority($authid);
1128 foreach my $field ($record->field('550')){
1129 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1130 my $parentrecord = GetAuthority($field->subfield('3'));
1131 my $localresult=$hierarchies;
1133 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1136 @trees = split(/;/,$trees);
1138 push @trees, $trees;
1143 @globalresult = (@globalresult,@trees);
1146 $hierarchies=join(";",@globalresult);
1149 #Unless there is no ancestor, I am alone.
1150 $hierarchies="$authid" unless ($hierarchies);
1152 AddAuthorityTrees($authid,$hierarchies);
1153 return $hierarchies;
1156 =head2 BuildUnimarcHierarchy
1158 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1160 return a hashref in order to display hierarchy for record and final Authid $authid
1171 Those two latest ones should disappear soon.
1175 sub BuildUnimarcHierarchy{
1176 my $record = shift @_;
1177 my $class = shift @_;
1178 my $authid_constructed = shift @_;
1179 return undef unless ($record);
1180 my $authid=$record->subfield('2..','3');
1182 my $parents=""; my $children="";
1183 my (@loopparents,@loopchildren);
1184 foreach my $field ($record->field('550')){
1185 if ($field->subfield('5') && $field->subfield('a')){
1186 if ($field->subfield('5') eq 'h'){
1187 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1188 }elsif ($field->subfield('5') eq 'g'){
1189 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1191 # brothers could get in there with an else
1194 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1195 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1196 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1197 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1198 $cell{"class"}=$class;
1199 $cell{"loopauthid"}=$authid;
1200 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1201 $cell{"value"}=$record->subfield('2..',"a");
1205 =head2 GetHeaderAuthority
1207 $ref= &GetHeaderAuthority( $authid)
1209 return a hashref in order auth_header table data
1213 sub GetHeaderAuthority{
1214 my $authid = shift @_;
1215 my $sql= "SELECT * from auth_header WHERE authid = ?";
1216 my $dbh=C4::Context->dbh;
1217 my $rq= $dbh->prepare($sql);
1218 $rq->execute($authid);
1219 my $data= $rq->fetchrow_hashref;
1223 =head2 AddAuthorityTrees
1225 $ref= &AddAuthorityTrees( $authid, $trees)
1227 return success or failure
1231 sub AddAuthorityTrees{
1232 my $authid = shift @_;
1233 my $trees = shift @_;
1234 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1235 my $dbh=C4::Context->dbh;
1236 my $rq= $dbh->prepare($sql);
1237 return $rq->execute($trees,$authid);
1242 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1244 Could add some feature : Migrating from a typecode to an other for instance.
1245 Then we should add some new parameter : bibliotargettag, authtargettag
1250 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1251 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1252 my $dbh=C4::Context->dbh;
1253 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1254 my $authtypecodeto = GetAuthTypeCode($mergeto);
1255 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1256 # return if authority does not exist
1257 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1258 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1259 # search the tag to report
1260 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1261 $sth->execute($authtypecodefrom);
1262 my ($auth_tag_to_report_from) = $sth->fetchrow;
1263 $sth->execute($authtypecodeto);
1264 my ($auth_tag_to_report_to) = $sth->fetchrow;
1267 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1269 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1272 # search all biblio tags using this authority.
1273 #Getting marcbiblios impacted by the change.
1274 if (C4::Context->preference('NoZebra')) {
1276 my $dbh=C4::Context->dbh;
1277 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1279 while (my $biblionumbers=$rq->fetchrow){
1280 my @biblionumbers=split /;/,$biblionumbers;
1281 foreach (@biblionumbers) {
1282 if ($_=~/(\d+),.*/) {
1283 my $marc=GetMarcBiblio($1);
1284 push @reccache,$marc;
1290 my $oConnection=C4::Context->Zconn("biblioserver",0);
1291 $oConnection->option("preferredRecordSyntax"=>"XML");
1293 $query= "an=".$mergefrom;
1294 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1297 $count=$oResult->size();
1300 while ( $z<$count ) {
1302 $rec=$oResult->record($z);
1303 my $marcdata = $rec->raw();
1304 push @reccache, $marcdata;
1307 $oConnection->destroy();
1309 #warn scalar(@reccache)." biblios to update";
1310 # Get All candidate Tags for the change
1311 # (This will reduce the search scope in marc records).
1312 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1313 $sth->execute($authtypecodefrom);
1314 my @tags_using_authtype;
1315 while (my ($tagfield) = $sth->fetchrow) {
1316 push @tags_using_authtype,$tagfield ;
1319 if ($authtypecodeto ne $authtypecodefrom){
1320 # If many tags, take the first
1321 $sth->execute($authtypecodeto);
1322 $tag_to=$sth->fetchrow;
1325 # BulkEdit marc records
1326 # May be used as a template for a bulkedit field
1327 foreach my $marcrecord(@reccache){
1329 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1330 foreach my $tagfield (@tags_using_authtype){
1331 # warn "tagfield : $tagfield ";
1332 foreach my $field ($marcrecord->field($tagfield)){
1333 my $auth_number=$field->subfield("9");
1334 my $tag=$field->tag();
1335 if ($auth_number==$mergefrom) {
1336 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1338 foreach my $subfield (@record_to) {
1339 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1340 $exclude.= $subfield->[0];
1342 $exclude='['.$exclude.']';
1343 # add subfields in $field not included in @record_to
1344 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1345 foreach my $subfield (@restore) {
1346 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1348 $marcrecord->delete_field($field);
1349 $marcrecord->insert_grouped_field($field_to);
1354 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1357 $biblionumber=$marcrecord->field($bibliotag)->data;
1360 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1362 unless ($biblionumber){
1363 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1367 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1368 $counteditedbiblio++;
1369 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1372 return $counteditedbiblio;
1373 # now, find every other authority linked with this authority
1374 # now, find every other authority linked with this authority
1375 # my $oConnection=C4::Context->Zconn("authorityserver");
1377 # # att 9210 Auth-Internal-authtype
1378 # # att 9220 Auth-Internal-LN
1379 # # ccl.properties to add for authorities
1380 # $query= "= ".$mergefrom;
1381 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1382 # my $count=$oResult->size() if ($oResult);
1385 # while ( $z<$count ) {
1387 # $rec=$oResult->record($z);
1388 # my $marcdata = $rec->raw();
1389 # push @reccache, $marcdata;
1392 # $oResult->destroy();
1393 # foreach my $marc(@reccache){
1396 # $marcrecord = MARC::File::USMARC::decode($marc);
1397 # foreach my $tagfield (@tags_using_authtype){
1398 # $tagfield=substr($tagfield,0,3);
1399 # my @tags = $marcrecord->field($tagfield);
1400 # foreach my $tag (@tags){
1401 # my $tagsubs=$tag->subfield("9");
1402 # #warn "$tagfield:$tagsubs:$mergefrom";
1403 # if ($tagsubs== $mergefrom) {
1404 # $tag->update("9" =>$mergeto);
1405 # foreach my $subfield (@record_to) {
1406 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1407 # $tag->update($subfield->[0] =>$subfield->[1]);
1410 # $marcrecord->delete_field($tag);
1411 # $marcrecord->add_fields($tag);
1414 # }#foreach tagfield
1415 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1417 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1423 =head2 get_auth_type_location
1425 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1427 Get the tag and subfield used to store the heading type
1428 for indexing purposes. The C<$auth_type> parameter is
1429 optional; if it is not supplied, assume ''.
1431 This routine searches the MARC authority framework
1432 for the tag and subfield whose kohafield is
1433 C<auth_header.authtypecode>; if no such field is
1434 defined in the framework, default to the hardcoded value
1435 specific to the MARC format.
1439 sub get_auth_type_location {
1440 my $auth_type_code = @_ ? shift : '';
1442 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1443 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1444 return ($tag, $subfield);
1446 if (C4::Context->preference('marcflavour') eq "MARC21") {
1447 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1449 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1454 END { } # module clean-up code here (global destructor)
1461 Koha Development Team <http://koha-community.org/>
1463 Paul POULAIN paul.poulain@free.fr