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 mainentry search $a tag
227 if (@$tags[$i] eq "mainmainentry") {
229 # FIXME: 'Heading-Main' index not yet defined in zebra
230 # $attr =" \@attr 1=Heading-Main ";
231 $attr =" \@attr 1=Heading ";
233 }elsif (@$tags[$i] eq "mainentry") {
234 $attr =" \@attr 1=Heading ";
236 $attr =" \@attr 1=Any ";
238 if (@$operator[$i] eq 'is') {
239 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
240 }elsif (@$operator[$i] eq "="){
241 $attr.=" \@attr 4=107 "; #Number Exact match
242 }elsif (@$operator[$i] eq "start"){
243 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
245 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
247 $attr =$attr."\"".@$value[$i]."\"";
252 ##Add how many queries generated
254 $query= $and.$query.$q2
259 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
260 my $orderstring= ($sortby eq "HeadingAsc"?
261 '@attr 7=1 @attr 1=Heading 0'
263 $sortby eq "HeadingDsc"?
264 '@attr 7=2 @attr 1=Heading 0'
267 $query=($query?"\@or $orderstring $query":"\@or \@attr 1=_ALLRECORDS \@attr 2=103 '' $orderstring ");
269 $offset=0 unless $offset;
270 my $counter = $offset;
271 $length=10 unless $length;
274 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
275 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
277 $oAResult= $oAuth[0]->search($Anewq) ;
278 while (($i = ZOOM::event(\@oAuth)) != 0) {
279 my $ev = $oAuth[$i-1]->last_event();
280 last if $ev == ZOOM::Event::ZEND;
282 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
284 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
289 $nbresults=$oAResult->size();
290 my $nremains=$nbresults;
292 my @finalresult = ();
296 ##Find authid and linkid fields
297 ##we may be searching multiple authoritytypes.
298 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
299 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
300 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
301 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
303 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
304 my $rec=$oAResult->record($counter);
305 my $marcdata=$rec->raw();
307 my $separator=C4::Context->preference('authoritysep');
308 $authrecord = MARC::File::USMARC::decode($marcdata);
309 my $authid=$authrecord->field('001')->data();
310 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
311 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
312 my $sth = $dbh->prepare($query_auth_tag);
313 $sth->execute($authtypecode);
314 my $auth_tag_to_report = $sth->fetchrow;
316 my $mainentry = $authrecord->field($auth_tag_to_report);
318 foreach ($mainentry->subfields()) {
319 $reported_tag .='$'.$_->[0].$_->[1];
323 $newline{summary} = $summary;
324 $newline{authid} = $authid;
325 $newline{even} = $counter % 2;
326 $newline{reported_tag} = $reported_tag;
328 push @finalresult, \%newline;
331 for (my $z=0; $z<@finalresult; $z++){
332 my $count=CountUsage($finalresult[$z]{authid});
333 $finalresult[$z]{used}=$count;
338 # $oAResult->destroy();
339 # $oAuth[0]->destroy();
341 return (\@finalresult, $nbresults);
347 $count= &CountUsage($authid)
349 counts Usage of Authid in bibliorecords.
355 if (C4::Context->preference('NoZebra')) {
356 # Read the index Koha-Auth-Number for this authid and count the lines
357 my $result = C4::Search::NZanalyse("an=$authid");
358 my @tab = split /;/,$result;
363 $query= "an=".$authid;
364 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
369 =head2 CountUsageChildren
371 $count= &CountUsageChildren($authid)
373 counts Usage of narrower terms of Authid in bibliorecords.
377 sub CountUsageChildren {
381 =head2 GetAuthTypeCode
383 $authtypecode= &GetAuthTypeCode($authid)
385 returns authtypecode of an authid
389 sub GetAuthTypeCode {
390 #AUTHfind_authtypecode
392 my $dbh=C4::Context->dbh;
393 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
394 $sth->execute($authid);
395 my $authtypecode = $sth->fetchrow;
396 return $authtypecode;
399 =head2 GuessAuthTypeCode
401 my $authtypecode = GuessAuthTypeCode($record);
403 Get the record and tries to guess the adequate authtypecode from its content.
407 sub GuessAuthTypeCode {
409 return unless defined $record;
410 my $heading_fields = {
412 '100'=>{authtypecode=>'PERSO_NAME'},
413 '110'=>{authtypecode=>'CORPO_NAME'},
414 '111'=>{authtypecode=>'MEETI_NAME'},
415 '130'=>{authtypecode=>'UNIF_TITLE'},
416 '148'=>{authtypecode=>'CHRON_TERM'},
417 '150'=>{authtypecode=>'TOPIC_TERM'},
418 '151'=>{authtypecode=>'GEOGR_NAME'},
419 '155'=>{authtypecode=>'GENRE/FORM'},
420 '180'=>{authtypecode=>'GEN_SUBDIV'},
421 '181'=>{authtypecode=>'GEO_SUBDIV'},
422 '182'=>{authtypecode=>'CHRON_SUBD'},
423 '185'=>{authtypecode=>'FORM_SUBD'},
425 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
426 # 604 with embedded 700, 701, 702
427 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
428 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
429 #216 Trademark 716 [Reserved for future use]
430 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
431 #230 Title 500 4-- with embedded 500 605
432 #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
433 #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
434 #250 Topical subject 606
435 #260 Place access 620
436 #280 Form, genre or physical characteristics 608
439 # Could also be represented with :
441 #a = personal name entry
442 #b = corporate name entry
443 #c = territorial or geographical name
447 #g = collective uniform title
449 #i = name/collective uniform title
452 #l = form, genre or physical characteristics
454 '200'=>{authtypecode=>'NP'},
455 '210'=>{authtypecode=>'CO'},
456 '215'=>{authtypecode=>'SNG'},
457 '216'=>{authtypecode=>'TM'},
458 '220'=>{authtypecode=>'FAM'},
459 '230'=>{authtypecode=>'TU'},
460 '235'=>{authtypecode=>'CO_UNI_TI'},
461 '240'=>{authtypecode=>'SAUTTIT'},
462 '245'=>{authtypecode=>'NAME_COL'},
463 '250'=>{authtypecode=>'SNC'},
464 '260'=>{authtypecode=>'PA'},
465 '280'=>{authtypecode=>'GENRE/FORM'},
468 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
469 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
476 my $authtid = GuessAuthId($record);
478 Get the record and tries to guess the adequate authtypecode from its content.
484 return unless ($record && $record->field('001'));
485 # my $authtypecode=GuessAuthTypeCode($record);
486 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
487 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
488 # else {return $record->field($tag)->data}
489 return $record->field('001')->data;
494 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
496 returns a ref to hashref of authorities tag and subfield structure.
500 $tagslabel->{$tag}->{$subfield}->{'attribute'}
502 where attribute takes values in :
520 my ($forlibrarian,$authtypecode)= @_;
521 my $dbh=C4::Context->dbh;
522 $authtypecode="" unless $authtypecode;
524 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
527 # check that authority exists
528 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
529 $sth->execute($authtypecode);
530 my ($total) = $sth->fetchrow;
531 $authtypecode="" unless ($total >0);
533 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
534 FROM auth_tag_structure
539 $sth->execute($authtypecode);
540 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
542 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
543 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
544 $res->{$tag}->{tab} = " "; # XXX
545 $res->{$tag}->{mandatory} = $mandatory;
546 $res->{$tag}->{repeatable} = $repeatable;
549 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
550 FROM auth_subfield_structure
552 ORDER BY tagfield,tagsubfield"
554 $sth->execute($authtypecode);
557 my $authorised_value;
566 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
567 $mandatory, $repeatable, $authorised_value, $authtypecode,
568 $value_builder, $kohafield, $seealso, $hidden,
573 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
574 $res->{$tag}->{$subfield}->{tab} = $tab;
575 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
576 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
577 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
578 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
579 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
580 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
581 $res->{$tag}->{$subfield}->{seealso} = $seealso;
582 $res->{$tag}->{$subfield}->{hidden} = $hidden;
583 $res->{$tag}->{$subfield}->{isurl} = $isurl;
584 $res->{$tag}->{$subfield}->{link} = $link;
591 $authid= &AddAuthority($record, $authid,$authtypecode)
593 Either Create Or Modify existing authority.
594 returns authid of the newly created authority
599 # pass the MARC::Record to this function, and it will create the records in the authority table
600 my ($record,$authid,$authtypecode) = @_;
601 my $dbh=C4::Context->dbh;
602 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
604 # if authid empty => true add, find a new authid number
606 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
607 $format= 'UNIMARCAUTH';
613 #update date/time to 005 for marc and unimarc
614 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
615 my $f5=$record->field('005');
617 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
620 $f5->update($time.".0");
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") && (!$record->subfield('100','a'))){
649 $record->leader(" nx j22 ");
650 my $date=POSIX::strftime("%Y%m%d",localtime);
651 if ($record->field('100')){
652 $record->field('100')->update('a'=>$date."afrey50 ba0");
654 $record->append_fields(
655 MARC::Field->new('100',' ',' '
656 ,'a'=>$date."afrey50 ba0")
660 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
661 if (!$authid and $format eq "MARC21") {
662 # only need to do this fix when modifying an existing authority
663 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
665 if (my $field=$record->field($auth_type_tag)){
666 $field->update($auth_type_subfield=>$authtypecode);
669 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
675 my $sth=$dbh->prepare("select max(authid) from auth_header");
677 ($authid)=$sth->fetchrow;
679 ##Insert the recordID in MARC record
680 unless ($record->field('001') && $record->field('001')->data() eq $authid){
681 $record->delete_field($record->field('001'));
682 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
685 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
686 # warn "auth_exists = $auth_exists";
689 $oldRecord=GetAuthority($authid);
690 $record->add_fields('001',$authid) unless ($record->field('001'));
691 # warn "\n\n\n enregistrement".$record->as_formatted;
692 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
693 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
697 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
698 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
701 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
708 $authid= &DelAuthority($authid)
716 my $dbh=C4::Context->dbh;
718 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
719 $dbh->do("delete from auth_header where authid=$authid") ;
724 my ($authid,$record,$authtypecode,$merge)=@_;
725 my $dbh=C4::Context->dbh;
726 #Now rewrite the $record to table with an add
727 my $oldrecord=GetAuthority($authid);
728 $authid=AddAuthority($record,$authid,$authtypecode);
730 ### 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
731 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
732 ### the $merge flag is now depreceated and will be removed at code cleaning
733 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
734 &merge($authid,$oldrecord,$authid,$record);
736 # save the file in tmp/modified_authorities
737 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
738 unless (opendir(DIR,"$cgidir")) {
739 $cgidir = C4::Context->intranetdir."/";
743 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
744 open AUTH, "> $filename";
751 =head2 GetAuthorityXML
753 $marcxml= &GetAuthorityXML( $authid)
755 returns xml form of record $authid
759 sub GetAuthorityXML {
760 # Returns MARC::XML of the authority passed in parameter.
762 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
763 my $dbh=C4::Context->dbh;
764 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
765 $sth->execute($authid);
766 my ($marcxml)=$sth->fetchrow;
770 # for MARC21, call GetAuthority instead of
771 # getting the XML directly since we may
772 # need to fix up the location of the authority
773 # code -- note that this is reasonably safe
774 # because GetAuthorityXML is used only by the
775 # indexing processes like zebraqueue_start.pl
776 my $record = GetAuthority($authid);
777 return $record->as_xml_record('MARC21');
783 $record= &GetAuthority( $authid)
785 Returns MARC::Record of the authority passed in parameter.
791 my $dbh=C4::Context->dbh;
792 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
793 $sth->execute($authid);
794 my ($authtypecode, $marcxml) = $sth->fetchrow;
795 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
796 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
797 return undef if ($@);
798 $record->encoding('UTF-8');
799 if (C4::Context->preference("marcflavour") eq "MARC21") {
800 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
801 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
808 $result = &GetAuthType($authtypecode)
810 If the authority type specified by C<$authtypecode> exists,
811 returns a hashref of the type's fields. If the type
812 does not exist, returns undef.
817 my ($authtypecode) = @_;
818 my $dbh=C4::Context->dbh;
820 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
821 # type (FIXME but why?)
822 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
823 $sth->execute($authtypecode);
824 if (my $res = $sth->fetchrow_hashref) {
833 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
834 my $dbh=C4::Context->dbh;
836 my $record = MARC::Record->new();
837 #---- TODO : the leader is missing
839 # my %subfieldlist=();
840 my $prevvalue; # if tag <10
841 my $field; # if tag >=10
842 for (my $i=0; $i< @$rtags; $i++) {
843 # rebuild MARC::Record
844 if (@$rtags[$i] ne $prevtag) {
847 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
851 $record->add_fields($field);
854 $indicators{@$rtags[$i]}.=' ';
855 if (@$rtags[$i] <10) {
856 $prevvalue= @$rvalues[$i];
860 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
862 $prevtag = @$rtags[$i];
864 if (@$rtags[$i] <10) {
865 $prevvalue=@$rvalues[$i];
867 if (length(@$rvalues[$i])>0) {
868 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
871 $prevtag= @$rtags[$i];
874 # the last has not been included inside the loop... do it now !
875 $record->add_fields($field) if $field;
879 =head2 FindDuplicateAuthority
881 $record= &FindDuplicateAuthority( $record, $authtypecode)
883 return $authid,Summary if duplicate is found.
885 Comments : an improvement would be to return All the records that match.
889 sub FindDuplicateAuthority {
891 my ($record,$authtypecode)=@_;
892 # warn "IN for ".$record->as_formatted;
893 my $dbh = C4::Context->dbh;
894 # warn "".$record->as_formatted;
895 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
896 $sth->execute($authtypecode);
897 my ($auth_tag_to_report) = $sth->fetchrow;
899 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
900 # build a request for SearchAuthorities
901 my $query='at='.$authtypecode.' ';
902 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
903 if ($record->field($auth_tag_to_report)) {
904 foreach ($record->field($auth_tag_to_report)->subfields()) {
905 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
908 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
909 # there is at least 1 result => return the 1st one
911 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
912 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
914 # no result, returns nothing
920 $text= &BuildSummary( $record, $authid, $authtypecode)
922 return HTML encoded Summary
924 Comment : authtypecode can be infered from both record and authid.
925 Moreover, authid can also be inferred from $record.
926 Would it be interesting to delete those things.
931 ## give this a Marc record to return summary
932 my ($record,$authid,$authtypecode)=@_;
933 my $dbh=C4::Context->dbh;
935 # handle $authtypecode is NULL or eq ""
937 my $authref = GetAuthType($authtypecode);
938 $summary = $authref->{summary};
940 # FIXME: should use I18N.pm
942 $language{'fre'}="Français";
943 $language{'eng'}="Anglais";
944 $language{'ger'}="Allemand";
945 $language{'ita'}="Italien";
946 $language{'spa'}="Espagnol";
948 $thesaurus{'1'}="Peuples";
949 $thesaurus{'2'}="Anthroponymes";
950 $thesaurus{'3'}="Oeuvres";
951 $thesaurus{'4'}="Chronologie";
952 $thesaurus{'5'}="Lieux";
953 $thesaurus{'6'}="Sujets";
955 my @fields = $record->fields();
957 # if the library has a summary defined, use it. Otherwise, build a standard one
958 # FIXME - it appears that the summary field in the authority frameworks
959 # can work as a display template. However, this doesn't
960 # suit the MARC21 version, so for now the "templating"
961 # feature will be enabled only for UNIMARC for backwards
963 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
964 my @fields = $record->fields();
965 # $reported_tag = '$9'.$result[$counter];
967 foreach my $field (@fields) {
968 my $tag = $field->tag();
969 my $tagvalue = $field->as_string();
970 my $localsummary= $summary;
971 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
974 $reported_tag.='$3'.$field->data();
977 my @subf = $field->subfields;
978 for my $i (0..$#subf) {
979 my $subfieldcode = $subf[$i][0];
980 my $subfieldvalue = $subf[$i][1];
981 my $tagsubf = $tag.$subfieldcode;
982 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
985 push @stringssummary, $localsummary if ($localsummary ne $summary);
988 $resultstring = join(" -- ",@stringssummary);
989 $resultstring =~ s/\[(.*?)\]//g;
990 $resultstring =~ s/\n/<br>/g;
991 $summary = $resultstring;
1001 my @fields = $record->fields();
1002 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1003 # construct UNIMARC summary, that is quite different from MARC21 one
1005 foreach my $field ($record->field('2..')) {
1006 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1009 foreach my $field ($record->field('3..')) {
1010 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1012 foreach my $field ($record->field('4..')) {
1013 if ($field->subfield('2')) {
1014 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1015 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1019 foreach my $field ($record->field('5..')) {
1021 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1022 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1023 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1024 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1025 } elsif ($field->subfield('a')) {
1026 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1030 foreach my $field ($record->field('7..')) {
1031 my $lang = substr($field->subfield('8'),3,3);
1032 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1034 $broaderterms =~s/-- \n$//;
1035 $narrowerterms =~s/-- \n$//;
1036 $seealso =~s/-- \n$//;
1038 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1039 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1040 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1041 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1042 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1043 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1045 # construct MARC21 summary
1046 # FIXME - looping over 1XX is questionable
1047 # since MARC21 authority should have only one 1XX
1048 foreach my $field ($record->field('1..')) {
1049 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1050 # in MARC21 -- purely local tags really ought to be
1052 if ($record->field('100')) {
1053 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1054 } elsif ($record->field('110')) {
1055 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1056 } elsif ($record->field('111')) {
1057 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1058 } elsif ($record->field('130')) {
1059 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1060 } elsif ($record->field('148')) {
1061 $heading.= $field->as_string('abvxyz68');
1062 } elsif ($record->field('150')) {
1063 # $heading.= $field->as_string('abvxyz68');
1064 $heading.= $field->as_formatted();
1065 my $tag=$field->tag();
1066 $heading=~s /^$tag//g;
1067 $heading =~s /\_/\$/g;
1068 } elsif ($record->field('151')) {
1069 $heading.= $field->as_string('avxyz68');
1070 } elsif ($record->field('155')) {
1071 $heading.= $field->as_string('abvxyz68');
1072 } elsif ($record->field('180')) {
1073 $heading.= $field->as_string('vxyz68');
1074 } elsif ($record->field('181')) {
1075 $heading.= $field->as_string('vxyz68');
1076 } elsif ($record->field('182')) {
1077 $heading.= $field->as_string('vxyz68');
1078 } elsif ($record->field('185')) {
1079 $heading.= $field->as_string('vxyz68');
1081 $heading.= $field->as_string();
1084 foreach my $field ($record->field('4..')) {
1085 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1087 foreach my $field ($record->field('5..')) {
1088 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1090 $summary .= ": " if $summary;
1091 $summary.=$heading.$seeheading.$altheading;
1097 =head2 BuildUnimarcHierarchies
1099 $text= &BuildUnimarcHierarchies( $authid, $force)
1101 return text containing trees for hierarchies
1102 for them to be stored in auth_header
1105 122,1314,2452;1324,2342,3,2452
1109 sub BuildUnimarcHierarchies{
1110 my $authid = shift @_;
1111 # warn "authid : $authid";
1112 my $force = shift @_;
1114 my $dbh=C4::Context->dbh;
1116 my $data = GetHeaderAuthority($authid);
1117 if ($data->{'authtrees'} and not $force){
1118 return $data->{'authtrees'};
1119 } elsif ($data->{'authtrees'}){
1120 $hierarchies=$data->{'authtrees'};
1122 my $record = GetAuthority($authid);
1125 foreach my $field ($record->field('550')){
1126 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1127 my $parentrecord = GetAuthority($field->subfield('3'));
1128 my $localresult=$hierarchies;
1130 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1133 @trees = split(/;/,$trees);
1135 push @trees, $trees;
1140 @globalresult = (@globalresult,@trees);
1143 $hierarchies=join(";",@globalresult);
1146 #Unless there is no ancestor, I am alone.
1147 $hierarchies="$authid" unless ($hierarchies);
1149 AddAuthorityTrees($authid,$hierarchies);
1150 return $hierarchies;
1153 =head2 BuildUnimarcHierarchy
1155 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1157 return a hashref in order to display hierarchy for record and final Authid $authid
1168 Those two latest ones should disappear soon.
1172 sub BuildUnimarcHierarchy{
1173 my $record = shift @_;
1174 my $class = shift @_;
1175 my $authid_constructed = shift @_;
1176 return undef unless ($record);
1177 my $authid=$record->subfield('2..','3');
1179 my $parents=""; my $children="";
1180 my (@loopparents,@loopchildren);
1181 foreach my $field ($record->field('550')){
1182 if ($field->subfield('5') && $field->subfield('a')){
1183 if ($field->subfield('5') eq 'h'){
1184 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1185 }elsif ($field->subfield('5') eq 'g'){
1186 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1188 # brothers could get in there with an else
1191 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1192 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1193 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1194 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1195 $cell{"class"}=$class;
1196 $cell{"loopauthid"}=$authid;
1197 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1198 $cell{"value"}=$record->subfield('2..',"a");
1202 =head2 GetHeaderAuthority
1204 $ref= &GetHeaderAuthority( $authid)
1206 return a hashref in order auth_header table data
1210 sub GetHeaderAuthority{
1211 my $authid = shift @_;
1212 my $sql= "SELECT * from auth_header WHERE authid = ?";
1213 my $dbh=C4::Context->dbh;
1214 my $rq= $dbh->prepare($sql);
1215 $rq->execute($authid);
1216 my $data= $rq->fetchrow_hashref;
1220 =head2 AddAuthorityTrees
1222 $ref= &AddAuthorityTrees( $authid, $trees)
1224 return success or failure
1228 sub AddAuthorityTrees{
1229 my $authid = shift @_;
1230 my $trees = shift @_;
1231 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1232 my $dbh=C4::Context->dbh;
1233 my $rq= $dbh->prepare($sql);
1234 return $rq->execute($trees,$authid);
1239 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1241 Could add some feature : Migrating from a typecode to an other for instance.
1242 Then we should add some new parameter : bibliotargettag, authtargettag
1247 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1248 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1249 my $dbh=C4::Context->dbh;
1250 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1251 my $authtypecodeto = GetAuthTypeCode($mergeto);
1252 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1253 # return if authority does not exist
1254 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1255 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1256 # search the tag to report
1257 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1258 $sth->execute($authtypecodefrom);
1259 my ($auth_tag_to_report_from) = $sth->fetchrow;
1260 $sth->execute($authtypecodeto);
1261 my ($auth_tag_to_report_to) = $sth->fetchrow;
1264 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1266 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1269 # search all biblio tags using this authority.
1270 #Getting marcbiblios impacted by the change.
1271 if (C4::Context->preference('NoZebra')) {
1273 my $dbh=C4::Context->dbh;
1274 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1276 while (my $biblionumbers=$rq->fetchrow){
1277 my @biblionumbers=split /;/,$biblionumbers;
1278 foreach (@biblionumbers) {
1279 if ($_=~/(\d+),.*/) {
1280 my $marc=GetMarcBiblio($1);
1281 push @reccache,$marc;
1287 my $oConnection=C4::Context->Zconn("biblioserver",0);
1288 $oConnection->option("preferredRecordSyntax"=>"XML");
1290 $query= "an=".$mergefrom;
1291 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1294 $count=$oResult->size();
1297 while ( $z<$count ) {
1299 $rec=$oResult->record($z);
1300 my $marcdata = $rec->raw();
1301 push @reccache, $marcdata;
1304 $oConnection->destroy();
1306 #warn scalar(@reccache)." biblios to update";
1307 # Get All candidate Tags for the change
1308 # (This will reduce the search scope in marc records).
1309 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1310 $sth->execute($authtypecodefrom);
1311 my @tags_using_authtype;
1312 while (my ($tagfield) = $sth->fetchrow) {
1313 push @tags_using_authtype,$tagfield ;
1316 if ($authtypecodeto ne $authtypecodefrom){
1317 # If many tags, take the first
1318 $sth->execute($authtypecodeto);
1319 $tag_to=$sth->fetchrow;
1322 # BulkEdit marc records
1323 # May be used as a template for a bulkedit field
1324 foreach my $marcrecord(@reccache){
1326 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1327 foreach my $tagfield (@tags_using_authtype){
1328 # warn "tagfield : $tagfield ";
1329 foreach my $field ($marcrecord->field($tagfield)){
1330 my $auth_number=$field->subfield("9");
1331 my $tag=$field->tag();
1332 if ($auth_number==$mergefrom) {
1333 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1335 foreach my $subfield (@record_to) {
1336 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1337 $exclude.= $subfield->[0];
1339 $exclude='['.$exclude.']';
1340 # add subfields in $field not included in @record_to
1341 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1342 foreach my $subfield (@restore) {
1343 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1345 $marcrecord->delete_field($field);
1346 $marcrecord->insert_grouped_field($field_to);
1351 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1354 $biblionumber=$marcrecord->field($bibliotag)->data;
1357 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1359 unless ($biblionumber){
1360 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1364 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1365 $counteditedbiblio++;
1366 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1369 return $counteditedbiblio;
1370 # now, find every other authority linked with this authority
1371 # now, find every other authority linked with this authority
1372 # my $oConnection=C4::Context->Zconn("authorityserver");
1374 # # att 9210 Auth-Internal-authtype
1375 # # att 9220 Auth-Internal-LN
1376 # # ccl.properties to add for authorities
1377 # $query= "= ".$mergefrom;
1378 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1379 # my $count=$oResult->size() if ($oResult);
1382 # while ( $z<$count ) {
1384 # $rec=$oResult->record($z);
1385 # my $marcdata = $rec->raw();
1386 # push @reccache, $marcdata;
1389 # $oResult->destroy();
1390 # foreach my $marc(@reccache){
1393 # $marcrecord = MARC::File::USMARC::decode($marc);
1394 # foreach my $tagfield (@tags_using_authtype){
1395 # $tagfield=substr($tagfield,0,3);
1396 # my @tags = $marcrecord->field($tagfield);
1397 # foreach my $tag (@tags){
1398 # my $tagsubs=$tag->subfield("9");
1399 # #warn "$tagfield:$tagsubs:$mergefrom";
1400 # if ($tagsubs== $mergefrom) {
1401 # $tag->update("9" =>$mergeto);
1402 # foreach my $subfield (@record_to) {
1403 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1404 # $tag->update($subfield->[0] =>$subfield->[1]);
1407 # $marcrecord->delete_field($tag);
1408 # $marcrecord->add_fields($tag);
1411 # }#foreach tagfield
1412 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1414 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1420 =head2 get_auth_type_location
1422 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1424 Get the tag and subfield used to store the heading type
1425 for indexing purposes. The C<$auth_type> parameter is
1426 optional; if it is not supplied, assume ''.
1428 This routine searches the MARC authority framework
1429 for the tag and subfield whose kohafield is
1430 C<auth_header.authtypecode>; if no such field is
1431 defined in the framework, default to the hardcoded value
1432 specific to the MARC format.
1436 sub get_auth_type_location {
1437 my $auth_type_code = @_ ? shift : '';
1439 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1440 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1441 return ($tag, $subfield);
1443 if (C4::Context->preference('marcflavour') eq "MARC21") {
1444 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1446 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1451 END { } # module clean-up code here (global destructor)
1458 Koha Development Team <http://koha-community.org/>
1460 Paul POULAIN paul.poulain@free.fr