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?"\@or $orderstring $query":"\@or \@attr 1=_ALLRECORDS \@attr 2=103 '' $orderstring ");
271 $offset=0 unless $offset;
272 my $counter = $offset;
273 $length=10 unless $length;
276 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
277 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
279 $oAResult= $oAuth[0]->search($Anewq) ;
280 while (($i = ZOOM::event(\@oAuth)) != 0) {
281 my $ev = $oAuth[$i-1]->last_event();
282 last if $ev == ZOOM::Event::ZEND;
284 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
286 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
291 $nbresults=$oAResult->size();
292 my $nremains=$nbresults;
294 my @finalresult = ();
298 ##Find authid and linkid fields
299 ##we may be searching multiple authoritytypes.
300 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
301 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
302 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
303 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
305 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
306 my $rec=$oAResult->record($counter);
307 my $marcdata=$rec->raw();
309 my $separator=C4::Context->preference('authoritysep');
310 $authrecord = MARC::File::USMARC::decode($marcdata);
311 my $authid=$authrecord->field('001')->data();
312 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
313 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
314 my $sth = $dbh->prepare($query_auth_tag);
315 $sth->execute($authtypecode);
316 my $auth_tag_to_report = $sth->fetchrow;
318 my $mainentry = $authrecord->field($auth_tag_to_report);
320 foreach ($mainentry->subfields()) {
321 $reported_tag .='$'.$_->[0].$_->[1];
325 $newline{summary} = $summary;
326 $newline{authid} = $authid;
327 $newline{even} = $counter % 2;
328 $newline{reported_tag} = $reported_tag;
330 push @finalresult, \%newline;
333 for (my $z=0; $z<@finalresult; $z++){
334 my $count=CountUsage($finalresult[$z]{authid});
335 $finalresult[$z]{used}=$count;
340 # $oAResult->destroy();
341 # $oAuth[0]->destroy();
343 return (\@finalresult, $nbresults);
349 $count= &CountUsage($authid)
351 counts Usage of Authid in bibliorecords.
357 if (C4::Context->preference('NoZebra')) {
358 # Read the index Koha-Auth-Number for this authid and count the lines
359 my $result = C4::Search::NZanalyse("an=$authid");
360 my @tab = split /;/,$result;
365 $query= "an=".$authid;
366 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
371 =head2 CountUsageChildren
373 $count= &CountUsageChildren($authid)
375 counts Usage of narrower terms of Authid in bibliorecords.
379 sub CountUsageChildren {
383 =head2 GetAuthTypeCode
385 $authtypecode= &GetAuthTypeCode($authid)
387 returns authtypecode of an authid
391 sub GetAuthTypeCode {
392 #AUTHfind_authtypecode
394 my $dbh=C4::Context->dbh;
395 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
396 $sth->execute($authid);
397 my $authtypecode = $sth->fetchrow;
398 return $authtypecode;
401 =head2 GuessAuthTypeCode
403 my $authtypecode = GuessAuthTypeCode($record);
405 Get the record and tries to guess the adequate authtypecode from its content.
409 sub GuessAuthTypeCode {
411 return unless defined $record;
412 my $heading_fields = {
414 '100'=>{authtypecode=>'PERSO_NAME'},
415 '110'=>{authtypecode=>'CORPO_NAME'},
416 '111'=>{authtypecode=>'MEETI_NAME'},
417 '130'=>{authtypecode=>'UNIF_TITLE'},
418 '148'=>{authtypecode=>'CHRON_TERM'},
419 '150'=>{authtypecode=>'TOPIC_TERM'},
420 '151'=>{authtypecode=>'GEOGR_NAME'},
421 '155'=>{authtypecode=>'GENRE/FORM'},
422 '180'=>{authtypecode=>'GEN_SUBDIV'},
423 '181'=>{authtypecode=>'GEO_SUBDIV'},
424 '182'=>{authtypecode=>'CHRON_SUBD'},
425 '185'=>{authtypecode=>'FORM_SUBD'},
427 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
428 # 604 with embedded 700, 701, 702
429 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
430 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
431 #216 Trademark 716 [Reserved for future use]
432 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
433 #230 Title 500 4-- with embedded 500 605
434 #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
435 #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
436 #250 Topical subject 606
437 #260 Place access 620
438 #280 Form, genre or physical characteristics 608
441 # Could also be represented with :
443 #a = personal name entry
444 #b = corporate name entry
445 #c = territorial or geographical name
449 #g = collective uniform title
451 #i = name/collective uniform title
454 #l = form, genre or physical characteristics
456 '200'=>{authtypecode=>'NP'},
457 '210'=>{authtypecode=>'CO'},
458 '215'=>{authtypecode=>'SNG'},
459 '216'=>{authtypecode=>'TM'},
460 '220'=>{authtypecode=>'FAM'},
461 '230'=>{authtypecode=>'TU'},
462 '235'=>{authtypecode=>'CO_UNI_TI'},
463 '240'=>{authtypecode=>'SAUTTIT'},
464 '245'=>{authtypecode=>'NAME_COL'},
465 '250'=>{authtypecode=>'SNC'},
466 '260'=>{authtypecode=>'PA'},
467 '280'=>{authtypecode=>'GENRE/FORM'},
470 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
471 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
478 my $authtid = GuessAuthId($record);
480 Get the record and tries to guess the adequate authtypecode from its content.
486 return unless ($record && $record->field('001'));
487 # my $authtypecode=GuessAuthTypeCode($record);
488 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
489 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
490 # else {return $record->field($tag)->data}
491 return $record->field('001')->data;
496 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
498 returns a ref to hashref of authorities tag and subfield structure.
502 $tagslabel->{$tag}->{$subfield}->{'attribute'}
504 where attribute takes values in :
522 my ($forlibrarian,$authtypecode)= @_;
523 my $dbh=C4::Context->dbh;
524 $authtypecode="" unless $authtypecode;
526 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
529 # check that authority exists
530 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
531 $sth->execute($authtypecode);
532 my ($total) = $sth->fetchrow;
533 $authtypecode="" unless ($total >0);
535 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
536 FROM auth_tag_structure
541 $sth->execute($authtypecode);
542 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
544 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
545 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
546 $res->{$tag}->{tab} = " "; # XXX
547 $res->{$tag}->{mandatory} = $mandatory;
548 $res->{$tag}->{repeatable} = $repeatable;
551 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
552 FROM auth_subfield_structure
554 ORDER BY tagfield,tagsubfield"
556 $sth->execute($authtypecode);
559 my $authorised_value;
568 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
569 $mandatory, $repeatable, $authorised_value, $authtypecode,
570 $value_builder, $kohafield, $seealso, $hidden,
575 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
576 $res->{$tag}->{$subfield}->{tab} = $tab;
577 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
578 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
579 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
580 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
581 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
582 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
583 $res->{$tag}->{$subfield}->{seealso} = $seealso;
584 $res->{$tag}->{$subfield}->{hidden} = $hidden;
585 $res->{$tag}->{$subfield}->{isurl} = $isurl;
586 $res->{$tag}->{$subfield}->{link} = $link;
593 $authid= &AddAuthority($record, $authid,$authtypecode)
595 Either Create Or Modify existing authority.
596 returns authid of the newly created authority
601 # pass the MARC::Record to this function, and it will create the records in the authority table
602 my ($record,$authid,$authtypecode) = @_;
603 my $dbh=C4::Context->dbh;
604 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
606 # if authid empty => true add, find a new authid number
608 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
609 $format= 'UNIMARCAUTH';
615 #update date/time to 005 for marc and unimarc
616 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
617 my $f5=$record->field('005');
619 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
622 $f5->update($time.".0");
625 if ($format eq "MARC21") {
626 if (!$record->leader) {
627 $record->leader($leader);
629 if (!$record->field('003')) {
630 $record->insert_fields_ordered(
631 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
634 my $date=POSIX::strftime("%y%m%d",localtime);
635 if (!$record->field('008')) {
636 $record->insert_fields_ordered(
637 MARC::Field->new('008',$date."|||a|||||| | ||| d")
640 if (!$record->field('040')) {
641 $record->insert_fields_ordered(
642 MARC::Field->new('040','','',
643 'a' => C4::Context->preference('MARCOrgCode'),
644 'c' => C4::Context->preference('MARCOrgCode')
650 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
651 $record->leader(" nx j22 ");
652 my $date=POSIX::strftime("%Y%m%d",localtime);
653 if ($record->field('100')){
654 $record->field('100')->update('a'=>$date."afrey50 ba0");
656 $record->append_fields(
657 MARC::Field->new('100',' ',' '
658 ,'a'=>$date."afrey50 ba0")
662 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
663 if (!$authid and $format eq "MARC21") {
664 # only need to do this fix when modifying an existing authority
665 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
667 if (my $field=$record->field($auth_type_tag)){
668 $field->update($auth_type_subfield=>$authtypecode);
671 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
677 my $sth=$dbh->prepare("select max(authid) from auth_header");
679 ($authid)=$sth->fetchrow;
681 ##Insert the recordID in MARC record
682 unless ($record->field('001') && $record->field('001')->data() eq $authid){
683 $record->delete_field($record->field('001'));
684 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
687 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
688 # warn "auth_exists = $auth_exists";
691 $oldRecord=GetAuthority($authid);
692 $record->add_fields('001',$authid) unless ($record->field('001'));
693 # warn "\n\n\n enregistrement".$record->as_formatted;
694 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
695 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
699 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
700 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
703 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
710 $authid= &DelAuthority($authid)
718 my $dbh=C4::Context->dbh;
720 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
721 $dbh->do("delete from auth_header where authid=$authid") ;
726 my ($authid,$record,$authtypecode,$merge)=@_;
727 my $dbh=C4::Context->dbh;
728 #Now rewrite the $record to table with an add
729 my $oldrecord=GetAuthority($authid);
730 $authid=AddAuthority($record,$authid,$authtypecode);
732 ### 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
733 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
734 ### the $merge flag is now depreceated and will be removed at code cleaning
735 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
736 &merge($authid,$oldrecord,$authid,$record);
738 # save the file in tmp/modified_authorities
739 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
740 unless (opendir(DIR,"$cgidir")) {
741 $cgidir = C4::Context->intranetdir."/";
745 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
746 open AUTH, "> $filename";
753 =head2 GetAuthorityXML
755 $marcxml= &GetAuthorityXML( $authid)
757 returns xml form of record $authid
761 sub GetAuthorityXML {
762 # Returns MARC::XML of the authority passed in parameter.
764 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
765 my $dbh=C4::Context->dbh;
766 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
767 $sth->execute($authid);
768 my ($marcxml)=$sth->fetchrow;
772 # for MARC21, call GetAuthority instead of
773 # getting the XML directly since we may
774 # need to fix up the location of the authority
775 # code -- note that this is reasonably safe
776 # because GetAuthorityXML is used only by the
777 # indexing processes like zebraqueue_start.pl
778 my $record = GetAuthority($authid);
779 return $record->as_xml_record('MARC21');
785 $record= &GetAuthority( $authid)
787 Returns MARC::Record of the authority passed in parameter.
793 my $dbh=C4::Context->dbh;
794 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
795 $sth->execute($authid);
796 my ($authtypecode, $marcxml) = $sth->fetchrow;
797 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
798 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
799 return undef if ($@);
800 $record->encoding('UTF-8');
801 if (C4::Context->preference("marcflavour") eq "MARC21") {
802 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
803 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
810 $result = &GetAuthType($authtypecode)
812 If the authority type specified by C<$authtypecode> exists,
813 returns a hashref of the type's fields. If the type
814 does not exist, returns undef.
819 my ($authtypecode) = @_;
820 my $dbh=C4::Context->dbh;
822 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
823 # type (FIXME but why?)
824 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
825 $sth->execute($authtypecode);
826 if (my $res = $sth->fetchrow_hashref) {
835 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
836 my $dbh=C4::Context->dbh;
838 my $record = MARC::Record->new();
839 #---- TODO : the leader is missing
841 # my %subfieldlist=();
842 my $prevvalue; # if tag <10
843 my $field; # if tag >=10
844 for (my $i=0; $i< @$rtags; $i++) {
845 # rebuild MARC::Record
846 if (@$rtags[$i] ne $prevtag) {
849 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
853 $record->add_fields($field);
856 $indicators{@$rtags[$i]}.=' ';
857 if (@$rtags[$i] <10) {
858 $prevvalue= @$rvalues[$i];
862 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
864 $prevtag = @$rtags[$i];
866 if (@$rtags[$i] <10) {
867 $prevvalue=@$rvalues[$i];
869 if (length(@$rvalues[$i])>0) {
870 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
873 $prevtag= @$rtags[$i];
876 # the last has not been included inside the loop... do it now !
877 $record->add_fields($field) if $field;
881 =head2 FindDuplicateAuthority
883 $record= &FindDuplicateAuthority( $record, $authtypecode)
885 return $authid,Summary if duplicate is found.
887 Comments : an improvement would be to return All the records that match.
891 sub FindDuplicateAuthority {
893 my ($record,$authtypecode)=@_;
894 # warn "IN for ".$record->as_formatted;
895 my $dbh = C4::Context->dbh;
896 # warn "".$record->as_formatted;
897 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
898 $sth->execute($authtypecode);
899 my ($auth_tag_to_report) = $sth->fetchrow;
901 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
902 # build a request for SearchAuthorities
903 my $query='at='.$authtypecode.' ';
904 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
905 if ($record->field($auth_tag_to_report)) {
906 foreach ($record->field($auth_tag_to_report)->subfields()) {
907 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
910 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
911 # there is at least 1 result => return the 1st one
913 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
914 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
916 # no result, returns nothing
922 $text= &BuildSummary( $record, $authid, $authtypecode)
924 return HTML encoded Summary
926 Comment : authtypecode can be infered from both record and authid.
927 Moreover, authid can also be inferred from $record.
928 Would it be interesting to delete those things.
933 ## give this a Marc record to return summary
934 my ($record,$authid,$authtypecode)=@_;
935 my $dbh=C4::Context->dbh;
937 # handle $authtypecode is NULL or eq ""
939 my $authref = GetAuthType($authtypecode);
940 $summary = $authref->{summary};
942 # FIXME: should use I18N.pm
944 $language{'fre'}="Français";
945 $language{'eng'}="Anglais";
946 $language{'ger'}="Allemand";
947 $language{'ita'}="Italien";
948 $language{'spa'}="Espagnol";
950 $thesaurus{'1'}="Peuples";
951 $thesaurus{'2'}="Anthroponymes";
952 $thesaurus{'3'}="Oeuvres";
953 $thesaurus{'4'}="Chronologie";
954 $thesaurus{'5'}="Lieux";
955 $thesaurus{'6'}="Sujets";
957 my @fields = $record->fields();
959 # if the library has a summary defined, use it. Otherwise, build a standard one
960 # FIXME - it appears that the summary field in the authority frameworks
961 # can work as a display template. However, this doesn't
962 # suit the MARC21 version, so for now the "templating"
963 # feature will be enabled only for UNIMARC for backwards
965 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
966 my @fields = $record->fields();
967 # $reported_tag = '$9'.$result[$counter];
969 foreach my $field (@fields) {
970 my $tag = $field->tag();
971 my $tagvalue = $field->as_string();
972 my $localsummary= $summary;
973 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
976 $reported_tag.='$3'.$field->data();
979 my @subf = $field->subfields;
980 for my $i (0..$#subf) {
981 my $subfieldcode = $subf[$i][0];
982 my $subfieldvalue = $subf[$i][1];
983 my $tagsubf = $tag.$subfieldcode;
984 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
987 push @stringssummary, $localsummary if ($localsummary ne $summary);
990 $resultstring = join(" -- ",@stringssummary);
991 $resultstring =~ s/\[(.*?)\]//g;
992 $resultstring =~ s/\n/<br>/g;
993 $summary = $resultstring;
1003 my @fields = $record->fields();
1004 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1005 # construct UNIMARC summary, that is quite different from MARC21 one
1007 foreach my $field ($record->field('2..')) {
1008 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1011 foreach my $field ($record->field('3..')) {
1012 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1014 foreach my $field ($record->field('4..')) {
1015 if ($field->subfield('2')) {
1016 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1017 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1021 foreach my $field ($record->field('5..')) {
1023 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1024 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1025 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1026 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1027 } elsif ($field->subfield('a')) {
1028 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1032 foreach my $field ($record->field('7..')) {
1033 my $lang = substr($field->subfield('8'),3,3);
1034 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1036 $broaderterms =~s/-- \n$//;
1037 $narrowerterms =~s/-- \n$//;
1038 $seealso =~s/-- \n$//;
1040 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1041 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1042 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1043 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1044 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1045 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1047 # construct MARC21 summary
1048 # FIXME - looping over 1XX is questionable
1049 # since MARC21 authority should have only one 1XX
1050 foreach my $field ($record->field('1..')) {
1051 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1052 # in MARC21 -- purely local tags really ought to be
1054 if ($record->field('100')) {
1055 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1056 } elsif ($record->field('110')) {
1057 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1058 } elsif ($record->field('111')) {
1059 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1060 } elsif ($record->field('130')) {
1061 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1062 } elsif ($record->field('148')) {
1063 $heading.= $field->as_string('abvxyz68');
1064 } elsif ($record->field('150')) {
1065 # $heading.= $field->as_string('abvxyz68');
1066 $heading.= $field->as_formatted();
1067 my $tag=$field->tag();
1068 $heading=~s /^$tag//g;
1069 $heading =~s /\_/\$/g;
1070 } elsif ($record->field('151')) {
1071 $heading.= $field->as_string('avxyz68');
1072 } elsif ($record->field('155')) {
1073 $heading.= $field->as_string('abvxyz68');
1074 } elsif ($record->field('180')) {
1075 $heading.= $field->as_string('vxyz68');
1076 } elsif ($record->field('181')) {
1077 $heading.= $field->as_string('vxyz68');
1078 } elsif ($record->field('182')) {
1079 $heading.= $field->as_string('vxyz68');
1080 } elsif ($record->field('185')) {
1081 $heading.= $field->as_string('vxyz68');
1083 $heading.= $field->as_string();
1086 foreach my $field ($record->field('4..')) {
1087 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1089 foreach my $field ($record->field('5..')) {
1090 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1092 $summary .= ": " if $summary;
1093 $summary.=$heading.$seeheading.$altheading;
1099 =head2 BuildUnimarcHierarchies
1101 $text= &BuildUnimarcHierarchies( $authid, $force)
1103 return text containing trees for hierarchies
1104 for them to be stored in auth_header
1107 122,1314,2452;1324,2342,3,2452
1111 sub BuildUnimarcHierarchies{
1112 my $authid = shift @_;
1113 # warn "authid : $authid";
1114 my $force = shift @_;
1116 my $dbh=C4::Context->dbh;
1118 my $data = GetHeaderAuthority($authid);
1119 if ($data->{'authtrees'} and not $force){
1120 return $data->{'authtrees'};
1121 } elsif ($data->{'authtrees'}){
1122 $hierarchies=$data->{'authtrees'};
1124 my $record = GetAuthority($authid);
1127 foreach my $field ($record->field('550')){
1128 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1129 my $parentrecord = GetAuthority($field->subfield('3'));
1130 my $localresult=$hierarchies;
1132 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1135 @trees = split(/;/,$trees);
1137 push @trees, $trees;
1142 @globalresult = (@globalresult,@trees);
1145 $hierarchies=join(";",@globalresult);
1148 #Unless there is no ancestor, I am alone.
1149 $hierarchies="$authid" unless ($hierarchies);
1151 AddAuthorityTrees($authid,$hierarchies);
1152 return $hierarchies;
1155 =head2 BuildUnimarcHierarchy
1157 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1159 return a hashref in order to display hierarchy for record and final Authid $authid
1170 Those two latest ones should disappear soon.
1174 sub BuildUnimarcHierarchy{
1175 my $record = shift @_;
1176 my $class = shift @_;
1177 my $authid_constructed = shift @_;
1178 return undef unless ($record);
1179 my $authid=$record->subfield('2..','3');
1181 my $parents=""; my $children="";
1182 my (@loopparents,@loopchildren);
1183 foreach my $field ($record->field('550')){
1184 if ($field->subfield('5') && $field->subfield('a')){
1185 if ($field->subfield('5') eq 'h'){
1186 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1187 }elsif ($field->subfield('5') eq 'g'){
1188 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1190 # brothers could get in there with an else
1193 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1194 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1195 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1196 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1197 $cell{"class"}=$class;
1198 $cell{"loopauthid"}=$authid;
1199 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1200 $cell{"value"}=$record->subfield('2..',"a");
1204 =head2 GetHeaderAuthority
1206 $ref= &GetHeaderAuthority( $authid)
1208 return a hashref in order auth_header table data
1212 sub GetHeaderAuthority{
1213 my $authid = shift @_;
1214 my $sql= "SELECT * from auth_header WHERE authid = ?";
1215 my $dbh=C4::Context->dbh;
1216 my $rq= $dbh->prepare($sql);
1217 $rq->execute($authid);
1218 my $data= $rq->fetchrow_hashref;
1222 =head2 AddAuthorityTrees
1224 $ref= &AddAuthorityTrees( $authid, $trees)
1226 return success or failure
1230 sub AddAuthorityTrees{
1231 my $authid = shift @_;
1232 my $trees = shift @_;
1233 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1234 my $dbh=C4::Context->dbh;
1235 my $rq= $dbh->prepare($sql);
1236 return $rq->execute($trees,$authid);
1241 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1243 Could add some feature : Migrating from a typecode to an other for instance.
1244 Then we should add some new parameter : bibliotargettag, authtargettag
1249 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1250 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1251 my $dbh=C4::Context->dbh;
1252 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1253 my $authtypecodeto = GetAuthTypeCode($mergeto);
1254 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1255 # return if authority does not exist
1256 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1257 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1258 # search the tag to report
1259 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1260 $sth->execute($authtypecodefrom);
1261 my ($auth_tag_to_report_from) = $sth->fetchrow;
1262 $sth->execute($authtypecodeto);
1263 my ($auth_tag_to_report_to) = $sth->fetchrow;
1266 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1268 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1271 # search all biblio tags using this authority.
1272 #Getting marcbiblios impacted by the change.
1273 if (C4::Context->preference('NoZebra')) {
1275 my $dbh=C4::Context->dbh;
1276 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1278 while (my $biblionumbers=$rq->fetchrow){
1279 my @biblionumbers=split /;/,$biblionumbers;
1280 foreach (@biblionumbers) {
1281 if ($_=~/(\d+),.*/) {
1282 my $marc=GetMarcBiblio($1);
1283 push @reccache,$marc;
1289 my $oConnection=C4::Context->Zconn("biblioserver",0);
1290 $oConnection->option("preferredRecordSyntax"=>"XML");
1292 $query= "an=".$mergefrom;
1293 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1296 $count=$oResult->size();
1299 while ( $z<$count ) {
1301 $rec=$oResult->record($z);
1302 my $marcdata = $rec->raw();
1303 push @reccache, $marcdata;
1306 $oConnection->destroy();
1308 #warn scalar(@reccache)." biblios to update";
1309 # Get All candidate Tags for the change
1310 # (This will reduce the search scope in marc records).
1311 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1312 $sth->execute($authtypecodefrom);
1313 my @tags_using_authtype;
1314 while (my ($tagfield) = $sth->fetchrow) {
1315 push @tags_using_authtype,$tagfield ;
1318 if ($authtypecodeto ne $authtypecodefrom){
1319 # If many tags, take the first
1320 $sth->execute($authtypecodeto);
1321 $tag_to=$sth->fetchrow;
1324 # BulkEdit marc records
1325 # May be used as a template for a bulkedit field
1326 foreach my $marcrecord(@reccache){
1328 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1329 foreach my $tagfield (@tags_using_authtype){
1330 # warn "tagfield : $tagfield ";
1331 foreach my $field ($marcrecord->field($tagfield)){
1332 my $auth_number=$field->subfield("9");
1333 my $tag=$field->tag();
1334 if ($auth_number==$mergefrom) {
1335 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1337 foreach my $subfield (@record_to) {
1338 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1339 $exclude.= $subfield->[0];
1341 $exclude='['.$exclude.']';
1342 # add subfields in $field not included in @record_to
1343 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1344 foreach my $subfield (@restore) {
1345 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1347 $marcrecord->delete_field($field);
1348 $marcrecord->insert_grouped_field($field_to);
1353 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1356 $biblionumber=$marcrecord->field($bibliotag)->data;
1359 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1361 unless ($biblionumber){
1362 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1366 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1367 $counteditedbiblio++;
1368 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1371 return $counteditedbiblio;
1372 # now, find every other authority linked with this authority
1373 # now, find every other authority linked with this authority
1374 # my $oConnection=C4::Context->Zconn("authorityserver");
1376 # # att 9210 Auth-Internal-authtype
1377 # # att 9220 Auth-Internal-LN
1378 # # ccl.properties to add for authorities
1379 # $query= "= ".$mergefrom;
1380 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1381 # my $count=$oResult->size() if ($oResult);
1384 # while ( $z<$count ) {
1386 # $rec=$oResult->record($z);
1387 # my $marcdata = $rec->raw();
1388 # push @reccache, $marcdata;
1391 # $oResult->destroy();
1392 # foreach my $marc(@reccache){
1395 # $marcrecord = MARC::File::USMARC::decode($marc);
1396 # foreach my $tagfield (@tags_using_authtype){
1397 # $tagfield=substr($tagfield,0,3);
1398 # my @tags = $marcrecord->field($tagfield);
1399 # foreach my $tag (@tags){
1400 # my $tagsubs=$tag->subfield("9");
1401 # #warn "$tagfield:$tagsubs:$mergefrom";
1402 # if ($tagsubs== $mergefrom) {
1403 # $tag->update("9" =>$mergeto);
1404 # foreach my $subfield (@record_to) {
1405 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1406 # $tag->update($subfield->[0] =>$subfield->[1]);
1409 # $marcrecord->delete_field($tag);
1410 # $marcrecord->add_fields($tag);
1413 # }#foreach tagfield
1414 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1416 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1422 =head2 get_auth_type_location
1424 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1426 Get the tag and subfield used to store the heading type
1427 for indexing purposes. The C<$auth_type> parameter is
1428 optional; if it is not supplied, assume ''.
1430 This routine searches the MARC authority framework
1431 for the tag and subfield whose kohafield is
1432 C<auth_header.authtypecode>; if no such field is
1433 defined in the framework, default to the hardcoded value
1434 specific to the MARC format.
1438 sub get_auth_type_location {
1439 my $auth_type_code = @_ ? shift : '';
1441 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1442 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1443 return ($tag, $subfield);
1445 if (C4::Context->preference('marcflavour') eq "MARC21") {
1446 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1448 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1453 END { } # module clean-up code here (global destructor)
1460 Koha Development Team <http://koha-community.org/>
1462 Paul POULAIN paul.poulain@free.fr