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 if ($format eq "MARC21") {
614 if (!$record->leader) {
615 $record->leader($leader);
617 if (!$record->field('003')) {
618 $record->insert_fields_ordered(
619 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
622 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
623 if (!$record->field('005')) {
624 $record->insert_fields_ordered(
625 MARC::Field->new('005',$time.".0")
628 my $date=POSIX::strftime("%y%m%d",localtime);
629 if (!$record->field('008')) {
630 $record->insert_fields_ordered(
631 MARC::Field->new('008',$date."|||a|||||| | ||| d")
634 if (!$record->field('040')) {
635 $record->insert_fields_ordered(
636 MARC::Field->new('040','','',
637 'a' => C4::Context->preference('MARCOrgCode'),
638 'c' => C4::Context->preference('MARCOrgCode')
644 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
645 $record->leader(" nx j22 ");
646 my $date=POSIX::strftime("%Y%m%d",localtime);
647 if ($record->field('100')){
648 $record->field('100')->update('a'=>$date."afrey50 ba0");
650 $record->append_fields(
651 MARC::Field->new('100',' ',' '
652 ,'a'=>$date."afrey50 ba0")
656 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
657 if (!$authid and $format eq "MARC21") {
658 # only need to do this fix when modifying an existing authority
659 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
661 if (my $field=$record->field($auth_type_tag)){
662 $field->update($auth_type_subfield=>$authtypecode);
665 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
671 my $sth=$dbh->prepare("select max(authid) from auth_header");
673 ($authid)=$sth->fetchrow;
675 ##Insert the recordID in MARC record
676 unless ($record->field('001') && $record->field('001')->data() eq $authid){
677 $record->delete_field($record->field('001'));
678 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
681 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
682 # warn "auth_exists = $auth_exists";
685 $oldRecord=GetAuthority($authid);
686 $record->add_fields('001',$authid) unless ($record->field('001'));
687 # warn "\n\n\n enregistrement".$record->as_formatted;
688 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
689 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
693 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
694 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
697 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
704 $authid= &DelAuthority($authid)
712 my $dbh=C4::Context->dbh;
714 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
715 $dbh->do("delete from auth_header where authid=$authid") ;
720 my ($authid,$record,$authtypecode,$merge)=@_;
721 my $dbh=C4::Context->dbh;
722 #Now rewrite the $record to table with an add
723 my $oldrecord=GetAuthority($authid);
724 $authid=AddAuthority($record,$authid,$authtypecode);
726 ### 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
727 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
728 ### the $merge flag is now depreceated and will be removed at code cleaning
729 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
730 &merge($authid,$oldrecord,$authid,$record);
732 # save the file in tmp/modified_authorities
733 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
734 unless (opendir(DIR,"$cgidir")) {
735 $cgidir = C4::Context->intranetdir."/";
739 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
740 open AUTH, "> $filename";
747 =head2 GetAuthorityXML
749 $marcxml= &GetAuthorityXML( $authid)
751 returns xml form of record $authid
755 sub GetAuthorityXML {
756 # Returns MARC::XML of the authority passed in parameter.
758 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
759 my $dbh=C4::Context->dbh;
760 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
761 $sth->execute($authid);
762 my ($marcxml)=$sth->fetchrow;
766 # for MARC21, call GetAuthority instead of
767 # getting the XML directly since we may
768 # need to fix up the location of the authority
769 # code -- note that this is reasonably safe
770 # because GetAuthorityXML is used only by the
771 # indexing processes like zebraqueue_start.pl
772 my $record = GetAuthority($authid);
773 return $record->as_xml_record('MARC21');
779 $record= &GetAuthority( $authid)
781 Returns MARC::Record of the authority passed in parameter.
787 my $dbh=C4::Context->dbh;
788 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
789 $sth->execute($authid);
790 my ($authtypecode, $marcxml) = $sth->fetchrow;
791 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
792 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
793 return undef if ($@);
794 $record->encoding('UTF-8');
795 if (C4::Context->preference("marcflavour") eq "MARC21") {
796 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
797 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
804 $result = &GetAuthType($authtypecode)
806 If the authority type specified by C<$authtypecode> exists,
807 returns a hashref of the type's fields. If the type
808 does not exist, returns undef.
813 my ($authtypecode) = @_;
814 my $dbh=C4::Context->dbh;
816 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
817 # type (FIXME but why?)
818 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
819 $sth->execute($authtypecode);
820 if (my $res = $sth->fetchrow_hashref) {
829 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
830 my $dbh=C4::Context->dbh;
832 my $record = MARC::Record->new();
833 #---- TODO : the leader is missing
835 # my %subfieldlist=();
836 my $prevvalue; # if tag <10
837 my $field; # if tag >=10
838 for (my $i=0; $i< @$rtags; $i++) {
839 # rebuild MARC::Record
840 if (@$rtags[$i] ne $prevtag) {
843 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
847 $record->add_fields($field);
850 $indicators{@$rtags[$i]}.=' ';
851 if (@$rtags[$i] <10) {
852 $prevvalue= @$rvalues[$i];
856 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
858 $prevtag = @$rtags[$i];
860 if (@$rtags[$i] <10) {
861 $prevvalue=@$rvalues[$i];
863 if (length(@$rvalues[$i])>0) {
864 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
867 $prevtag= @$rtags[$i];
870 # the last has not been included inside the loop... do it now !
871 $record->add_fields($field) if $field;
875 =head2 FindDuplicateAuthority
877 $record= &FindDuplicateAuthority( $record, $authtypecode)
879 return $authid,Summary if duplicate is found.
881 Comments : an improvement would be to return All the records that match.
885 sub FindDuplicateAuthority {
887 my ($record,$authtypecode)=@_;
888 # warn "IN for ".$record->as_formatted;
889 my $dbh = C4::Context->dbh;
890 # warn "".$record->as_formatted;
891 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
892 $sth->execute($authtypecode);
893 my ($auth_tag_to_report) = $sth->fetchrow;
895 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
896 # build a request for SearchAuthorities
897 my $query='at='.$authtypecode.' ';
898 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
899 if ($record->field($auth_tag_to_report)) {
900 foreach ($record->field($auth_tag_to_report)->subfields()) {
901 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
904 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
905 # there is at least 1 result => return the 1st one
907 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
908 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
910 # no result, returns nothing
916 $text= &BuildSummary( $record, $authid, $authtypecode)
918 return HTML encoded Summary
920 Comment : authtypecode can be infered from both record and authid.
921 Moreover, authid can also be inferred from $record.
922 Would it be interesting to delete those things.
927 ## give this a Marc record to return summary
928 my ($record,$authid,$authtypecode)=@_;
929 my $dbh=C4::Context->dbh;
931 # handle $authtypecode is NULL or eq ""
933 my $authref = GetAuthType($authtypecode);
934 $summary = $authref->{summary};
936 # FIXME: should use I18N.pm
938 $language{'fre'}="Français";
939 $language{'eng'}="Anglais";
940 $language{'ger'}="Allemand";
941 $language{'ita'}="Italien";
942 $language{'spa'}="Espagnol";
944 $thesaurus{'1'}="Peuples";
945 $thesaurus{'2'}="Anthroponymes";
946 $thesaurus{'3'}="Oeuvres";
947 $thesaurus{'4'}="Chronologie";
948 $thesaurus{'5'}="Lieux";
949 $thesaurus{'6'}="Sujets";
951 my @fields = $record->fields();
953 # if the library has a summary defined, use it. Otherwise, build a standard one
954 # FIXME - it appears that the summary field in the authority frameworks
955 # can work as a display template. However, this doesn't
956 # suit the MARC21 version, so for now the "templating"
957 # feature will be enabled only for UNIMARC for backwards
959 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
960 my @fields = $record->fields();
961 # $reported_tag = '$9'.$result[$counter];
963 foreach my $field (@fields) {
964 my $tag = $field->tag();
965 my $tagvalue = $field->as_string();
966 my $localsummary= $summary;
967 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
970 $reported_tag.='$3'.$field->data();
973 my @subf = $field->subfields;
974 for my $i (0..$#subf) {
975 my $subfieldcode = $subf[$i][0];
976 my $subfieldvalue = $subf[$i][1];
977 my $tagsubf = $tag.$subfieldcode;
978 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
981 push @stringssummary, $localsummary if ($localsummary ne $summary);
984 $resultstring = join(" -- ",@stringssummary);
985 $resultstring =~ s/\[(.*?)\]//g;
986 $resultstring =~ s/\n/<br>/g;
987 $summary = $resultstring;
997 my @fields = $record->fields();
998 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
999 # construct UNIMARC summary, that is quite different from MARC21 one
1001 foreach my $field ($record->field('2..')) {
1002 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1005 foreach my $field ($record->field('3..')) {
1006 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1008 foreach my $field ($record->field('4..')) {
1009 if ($field->subfield('2')) {
1010 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1011 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1015 foreach my $field ($record->field('5..')) {
1017 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1018 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1019 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1020 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1021 } elsif ($field->subfield('a')) {
1022 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1026 foreach my $field ($record->field('7..')) {
1027 my $lang = substr($field->subfield('8'),3,3);
1028 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1030 $broaderterms =~s/-- \n$//;
1031 $narrowerterms =~s/-- \n$//;
1032 $seealso =~s/-- \n$//;
1034 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1035 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1036 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1037 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1038 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1039 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1041 # construct MARC21 summary
1042 # FIXME - looping over 1XX is questionable
1043 # since MARC21 authority should have only one 1XX
1044 foreach my $field ($record->field('1..')) {
1045 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1046 # in MARC21 -- purely local tags really ought to be
1048 if ($record->field('100')) {
1049 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1050 } elsif ($record->field('110')) {
1051 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1052 } elsif ($record->field('111')) {
1053 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1054 } elsif ($record->field('130')) {
1055 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1056 } elsif ($record->field('148')) {
1057 $heading.= $field->as_string('abvxyz68');
1058 } elsif ($record->field('150')) {
1059 # $heading.= $field->as_string('abvxyz68');
1060 $heading.= $field->as_formatted();
1061 my $tag=$field->tag();
1062 $heading=~s /^$tag//g;
1063 $heading =~s /\_/\$/g;
1064 } elsif ($record->field('151')) {
1065 $heading.= $field->as_string('avxyz68');
1066 } elsif ($record->field('155')) {
1067 $heading.= $field->as_string('abvxyz68');
1068 } elsif ($record->field('180')) {
1069 $heading.= $field->as_string('vxyz68');
1070 } elsif ($record->field('181')) {
1071 $heading.= $field->as_string('vxyz68');
1072 } elsif ($record->field('182')) {
1073 $heading.= $field->as_string('vxyz68');
1074 } elsif ($record->field('185')) {
1075 $heading.= $field->as_string('vxyz68');
1077 $heading.= $field->as_string();
1080 foreach my $field ($record->field('4..')) {
1081 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1083 foreach my $field ($record->field('5..')) {
1084 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1086 $summary .= ": " if $summary;
1087 $summary.=$heading.$seeheading.$altheading;
1093 =head2 BuildUnimarcHierarchies
1095 $text= &BuildUnimarcHierarchies( $authid, $force)
1097 return text containing trees for hierarchies
1098 for them to be stored in auth_header
1101 122,1314,2452;1324,2342,3,2452
1105 sub BuildUnimarcHierarchies{
1106 my $authid = shift @_;
1107 # warn "authid : $authid";
1108 my $force = shift @_;
1110 my $dbh=C4::Context->dbh;
1112 my $data = GetHeaderAuthority($authid);
1113 if ($data->{'authtrees'} and not $force){
1114 return $data->{'authtrees'};
1115 } elsif ($data->{'authtrees'}){
1116 $hierarchies=$data->{'authtrees'};
1118 my $record = GetAuthority($authid);
1121 foreach my $field ($record->field('550')){
1122 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1123 my $parentrecord = GetAuthority($field->subfield('3'));
1124 my $localresult=$hierarchies;
1126 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1129 @trees = split(/;/,$trees);
1131 push @trees, $trees;
1136 @globalresult = (@globalresult,@trees);
1139 $hierarchies=join(";",@globalresult);
1142 #Unless there is no ancestor, I am alone.
1143 $hierarchies="$authid" unless ($hierarchies);
1145 AddAuthorityTrees($authid,$hierarchies);
1146 return $hierarchies;
1149 =head2 BuildUnimarcHierarchy
1151 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1153 return a hashref in order to display hierarchy for record and final Authid $authid
1164 Those two latest ones should disappear soon.
1168 sub BuildUnimarcHierarchy{
1169 my $record = shift @_;
1170 my $class = shift @_;
1171 my $authid_constructed = shift @_;
1172 return undef unless ($record);
1173 my $authid=$record->subfield('2..','3');
1175 my $parents=""; my $children="";
1176 my (@loopparents,@loopchildren);
1177 foreach my $field ($record->field('550')){
1178 if ($field->subfield('5') && $field->subfield('a')){
1179 if ($field->subfield('5') eq 'h'){
1180 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1181 }elsif ($field->subfield('5') eq 'g'){
1182 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1184 # brothers could get in there with an else
1187 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1188 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1189 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1190 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1191 $cell{"class"}=$class;
1192 $cell{"loopauthid"}=$authid;
1193 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1194 $cell{"value"}=$record->subfield('2..',"a");
1198 =head2 GetHeaderAuthority
1200 $ref= &GetHeaderAuthority( $authid)
1202 return a hashref in order auth_header table data
1206 sub GetHeaderAuthority{
1207 my $authid = shift @_;
1208 my $sql= "SELECT * from auth_header WHERE authid = ?";
1209 my $dbh=C4::Context->dbh;
1210 my $rq= $dbh->prepare($sql);
1211 $rq->execute($authid);
1212 my $data= $rq->fetchrow_hashref;
1216 =head2 AddAuthorityTrees
1218 $ref= &AddAuthorityTrees( $authid, $trees)
1220 return success or failure
1224 sub AddAuthorityTrees{
1225 my $authid = shift @_;
1226 my $trees = shift @_;
1227 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1228 my $dbh=C4::Context->dbh;
1229 my $rq= $dbh->prepare($sql);
1230 return $rq->execute($trees,$authid);
1235 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1237 Could add some feature : Migrating from a typecode to an other for instance.
1238 Then we should add some new parameter : bibliotargettag, authtargettag
1243 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1244 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1245 my $dbh=C4::Context->dbh;
1246 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1247 my $authtypecodeto = GetAuthTypeCode($mergeto);
1248 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1249 # return if authority does not exist
1250 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1251 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1252 # search the tag to report
1253 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1254 $sth->execute($authtypecodefrom);
1255 my ($auth_tag_to_report_from) = $sth->fetchrow;
1256 $sth->execute($authtypecodeto);
1257 my ($auth_tag_to_report_to) = $sth->fetchrow;
1260 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1262 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1265 # search all biblio tags using this authority.
1266 #Getting marcbiblios impacted by the change.
1267 if (C4::Context->preference('NoZebra')) {
1269 my $dbh=C4::Context->dbh;
1270 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1272 while (my $biblionumbers=$rq->fetchrow){
1273 my @biblionumbers=split /;/,$biblionumbers;
1274 foreach (@biblionumbers) {
1275 if ($_=~/(\d+),.*/) {
1276 my $marc=GetMarcBiblio($1);
1277 push @reccache,$marc;
1283 my $oConnection=C4::Context->Zconn("biblioserver",0);
1284 $oConnection->option("preferredRecordSyntax"=>"XML");
1286 $query= "an=".$mergefrom;
1287 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1290 $count=$oResult->size();
1293 while ( $z<$count ) {
1295 $rec=$oResult->record($z);
1296 my $marcdata = $rec->raw();
1297 push @reccache, $marcdata;
1300 $oConnection->destroy();
1302 #warn scalar(@reccache)." biblios to update";
1303 # Get All candidate Tags for the change
1304 # (This will reduce the search scope in marc records).
1305 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1306 $sth->execute($authtypecodefrom);
1307 my @tags_using_authtype;
1308 while (my ($tagfield) = $sth->fetchrow) {
1309 push @tags_using_authtype,$tagfield ;
1312 if ($authtypecodeto ne $authtypecodefrom){
1313 # If many tags, take the first
1314 $sth->execute($authtypecodeto);
1315 $tag_to=$sth->fetchrow;
1318 # BulkEdit marc records
1319 # May be used as a template for a bulkedit field
1320 foreach my $marcrecord(@reccache){
1322 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1323 foreach my $tagfield (@tags_using_authtype){
1324 # warn "tagfield : $tagfield ";
1325 foreach my $field ($marcrecord->field($tagfield)){
1326 my $auth_number=$field->subfield("9");
1327 my $tag=$field->tag();
1328 if ($auth_number==$mergefrom) {
1329 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1331 foreach my $subfield (@record_to) {
1332 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1333 $exclude.= $subfield->[0];
1335 $exclude='['.$exclude.']';
1336 # add subfields in $field not included in @record_to
1337 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1338 foreach my $subfield (@restore) {
1339 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1341 $marcrecord->delete_field($field);
1342 $marcrecord->insert_grouped_field($field_to);
1347 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1350 $biblionumber=$marcrecord->field($bibliotag)->data;
1353 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1355 unless ($biblionumber){
1356 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1360 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1361 $counteditedbiblio++;
1362 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1365 return $counteditedbiblio;
1366 # now, find every other authority linked with this authority
1367 # now, find every other authority linked with this authority
1368 # my $oConnection=C4::Context->Zconn("authorityserver");
1370 # # att 9210 Auth-Internal-authtype
1371 # # att 9220 Auth-Internal-LN
1372 # # ccl.properties to add for authorities
1373 # $query= "= ".$mergefrom;
1374 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1375 # my $count=$oResult->size() if ($oResult);
1378 # while ( $z<$count ) {
1380 # $rec=$oResult->record($z);
1381 # my $marcdata = $rec->raw();
1382 # push @reccache, $marcdata;
1385 # $oResult->destroy();
1386 # foreach my $marc(@reccache){
1389 # $marcrecord = MARC::File::USMARC::decode($marc);
1390 # foreach my $tagfield (@tags_using_authtype){
1391 # $tagfield=substr($tagfield,0,3);
1392 # my @tags = $marcrecord->field($tagfield);
1393 # foreach my $tag (@tags){
1394 # my $tagsubs=$tag->subfield("9");
1395 # #warn "$tagfield:$tagsubs:$mergefrom";
1396 # if ($tagsubs== $mergefrom) {
1397 # $tag->update("9" =>$mergeto);
1398 # foreach my $subfield (@record_to) {
1399 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1400 # $tag->update($subfield->[0] =>$subfield->[1]);
1403 # $marcrecord->delete_field($tag);
1404 # $marcrecord->add_fields($tag);
1407 # }#foreach tagfield
1408 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1410 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1416 =head2 get_auth_type_location
1418 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1420 Get the tag and subfield used to store the heading type
1421 for indexing purposes. The C<$auth_type> parameter is
1422 optional; if it is not supplied, assume ''.
1424 This routine searches the MARC authority framework
1425 for the tag and subfield whose kohafield is
1426 C<auth_header.authtypecode>; if no such field is
1427 defined in the framework, default to the hardcoded value
1428 specific to the MARC format.
1432 sub get_auth_type_location {
1433 my $auth_type_code = @_ ? shift : '';
1435 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1436 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1437 return ($tag, $subfield);
1439 if (C4::Context->preference('marcflavour') eq "MARC21") {
1440 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1442 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1447 END { } # module clean-up code here (global destructor)
1454 Koha Development Team <http://koha-community.org/>
1456 Paul POULAIN paul.poulain@free.fr