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 with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA 02111-1307 USA
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
29 use vars qw($VERSION @ISA @EXPORT);
32 # set the version for version checking
41 &GetAuthMARCFromKohaField
55 &BuildUnimarcHierarchies
56 &BuildUnimarcHierarchy
59 &FindDuplicateAuthority
63 =head2 GetAuthMARCFromKohaField
67 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
68 returns tag and subfield linked to kohafield
71 Suppose Kohafield is only linked to ONE subfield
77 sub GetAuthMARCFromKohaField {
78 #AUTHfind_marc_from_kohafield
79 my ( $kohafield,$authtypecode ) = @_;
80 my $dbh=C4::Context->dbh;
81 return 0, 0 unless $kohafield;
82 $authtypecode="" unless $authtypecode;
83 my $marcfromkohafield;
84 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
85 $sth->execute($kohafield,$authtypecode);
86 my ($tagfield,$tagsubfield) = $sth->fetchrow;
88 return ($tagfield,$tagsubfield);
91 =head2 SearchAuthorities
95 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
96 returns ref to array result and count of results returned
102 sub SearchAuthorities {
103 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
104 # warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
105 my $dbh=C4::Context->dbh;
106 if (C4::Context->preference('NoZebra')) {
112 my @auths=split / /,$authtypecode ;
113 foreach my $auth (@auths){
114 $query .="AND auth_type= $auth ";
118 for(my $i = 0 ; $i <= $#{$value} ; $i++)
121 if (@$tags[$i] eq "mainmainentry") {
122 $query .=" AND mainmainentry";
123 }elsif (@$tags[$i] eq "mainentry") {
124 $query .=" AND mainentry";
128 if (@$operator[$i] eq 'is') {
129 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
130 }elsif (@$operator[$i] eq "="){
131 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
132 }elsif (@$operator[$i] eq "start"){
133 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
135 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
141 # do the query (if we had some search term
144 # warn "QUERY : $query";
145 my $result = C4::Search::NZanalyse($query,'authorityserver');
146 # warn "result : $result";
148 foreach (split /;/,$result) {
149 my ($authid,$title) = split /,/,$_;
150 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
151 # and we don't want to get only 1 result for each of them !!!
152 # hint & speed improvement : we can order without reading the record
153 # so order, and read records only for the requested page !
154 $result{$title.$authid}=$authid;
156 # sort the hash and return the same structure as GetRecords (Zebra querying)
159 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
160 foreach my $key (sort {$b cmp $a} (keys %result)) {
161 push @listresult, $result{$key};
162 # warn "push..."$#finalresult;
165 } else { # sort by mainmainentry ASC
166 foreach my $key (sort (keys %result)) {
167 push @listresult, $result{$key};
168 # warn "push..."$#finalresult;
172 # limit the $results_per_page to result size if it's more
173 $length = $numbers-$offset if $numbers < ($offset+$length);
174 # for the requested page, replace authid by the complete record
175 # speed improvement : avoid reading too much things
177 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
178 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
179 my $separator=C4::Context->preference('authoritysep');
180 my $authrecord =GetAuthority($listresult[$counter]);
181 my $authid=$listresult[$counter];
182 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
183 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
184 my $sth = $dbh->prepare($query_auth_tag);
185 $sth->execute($authtypecode);
186 my $auth_tag_to_report = $sth->fetchrow;
188 $newline{used}=CountUsage($authid);
189 $newline{summary} = $summary;
190 $newline{authid} = $authid;
191 $newline{even} = $counter % 2;
192 push @finalresult, \%newline;
194 return (\@finalresult, $numbers);
201 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
202 # the authtypecode. Then, search on $a of this tag_to_report
203 # also store main entry MARC tag, to extract it at end of search
205 ##first set the authtype search and may be multiple authorities
208 my @auths=split / /,$authtypecode ;
209 foreach my $auth (@auths){
210 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
211 push @authtypecode ,$auth;
215 while ($n>1){$query= "\@or ".$query;$n--;}
221 for(my $i = 0 ; $i <= $#{$value} ; $i++)
224 ##If mainentry search $a tag
225 if (@$tags[$i] eq "mainmainentry") {
226 $attr =" \@attr 1=Heading ";
227 }elsif (@$tags[$i] eq "mainentry") {
228 $attr =" \@attr 1=Heading ";
230 $attr =" \@attr 1=Any ";
232 if (@$operator[$i] eq 'is') {
233 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
234 }elsif (@$operator[$i] eq "="){
235 $attr.=" \@attr 4=107 "; #Number Exact match
236 }elsif (@$operator[$i] eq "start"){
237 $attr.=" \@attr 4=1 \@attr 5=1 ";#Phrase, Right truncated
239 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
242 $attr =$attr."\"".@$value[$i]."\"";
247 ##Add how many queries generated
249 $query= $and.$query.$q2
254 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
255 $query=' @or @attr 7=1 @attr 1=Heading 0'.$query if ($sortby eq "HeadingAsc");
256 $query=' @or @attr 7=2 @attr 1=Heading 0'.$query if ($sortby eq "HeadingDsc");
258 $offset=0 unless $offset;
259 my $counter = $offset;
260 $length=10 unless $length;
263 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
264 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
266 $oAResult= $oAuth[0]->search($Anewq) ;
267 while (($i = ZOOM::event(\@oAuth)) != 0) {
268 my $ev = $oAuth[$i-1]->last_event();
269 last if $ev == ZOOM::Event::ZEND;
271 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
273 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
278 $nbresults=$oAResult->size();
279 my $nremains=$nbresults;
281 my @finalresult = ();
285 ##Find authid and linkid fields
286 ##we may be searching multiple authoritytypes.
287 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
288 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
289 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
290 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
292 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
293 my $rec=$oAResult->record($counter);
294 my $marcdata=$rec->raw();
296 my $separator=C4::Context->preference('authoritysep');
297 $authrecord = MARC::File::USMARC::decode($marcdata);
298 my $authid=$authrecord->field('001')->data();
299 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
300 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
301 my $sth = $dbh->prepare($query_auth_tag);
302 $sth->execute($authtypecode);
303 my $auth_tag_to_report = $sth->fetchrow;
305 my $mainentry = $authrecord->field($auth_tag_to_report);
307 foreach ($mainentry->subfields()) {
308 $reported_tag .='$'.$_->[0].$_->[1];
312 $newline{summary} = $summary;
313 $newline{authid} = $authid;
314 $newline{even} = $counter % 2;
315 $newline{reported_tag} = $reported_tag;
317 push @finalresult, \%newline;
320 for (my $z=0; $z<@finalresult; $z++){
321 my $count=CountUsage($finalresult[$z]{authid});
322 $finalresult[$z]{used}=$count;
327 # $oAResult->destroy();
328 # $oAuth[0]->destroy();
330 return (\@finalresult, $nbresults);
338 $count= &CountUsage($authid)
339 counts Usage of Authid in bibliorecords.
347 if (C4::Context->preference('NoZebra')) {
348 # Read the index Koha-Auth-Number for this authid and count the lines
349 my $result = C4::Search::NZanalyse("an=$authid");
350 my @tab = split /;/,$result;
354 my $oConnection=C4::Context->Zconn("biblioserver",1);
356 $query= "an=".$authid;
357 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
359 while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
360 my $ev = $oConnection->last_event();
361 if ($ev == ZOOM::Event::ZEND) {
362 $result = $oResult->size();
369 =head2 CountUsageChildren
373 $count= &CountUsageChildren($authid)
374 counts Usage of narrower terms of Authid in bibliorecords.
380 sub CountUsageChildren {
384 =head2 GetAuthTypeCode
388 $authtypecode= &GetAuthTypeCode($authid)
389 returns authtypecode of an authid
395 sub GetAuthTypeCode {
396 #AUTHfind_authtypecode
398 my $dbh=C4::Context->dbh;
399 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
400 $sth->execute($authid);
401 my ($authtypecode) = $sth->fetchrow;
402 return $authtypecode;
409 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
410 returns a ref to hashref of authorities tag and subfield structure.
413 $tagslabel->{$tag}->{$subfield}->{'attribute'}
414 where attribute takes values in :
433 my ($forlibrarian,$authtypecode)= @_;
434 my $dbh=C4::Context->dbh;
435 $authtypecode="" unless $authtypecode;
437 my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
440 # check that authority exists
441 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
442 $sth->execute($authtypecode);
443 my ($total) = $sth->fetchrow;
444 $authtypecode="" unless ($total >0);
446 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
447 FROM auth_tag_structure
452 $sth->execute($authtypecode);
453 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
455 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
456 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
457 $res->{$tag}->{tab} = " "; # XXX
458 $res->{$tag}->{mandatory} = $mandatory;
459 $res->{$tag}->{repeatable} = $repeatable;
462 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
463 FROM auth_subfield_structure
465 ORDER BY tagfield,tagsubfield"
467 $sth->execute($authtypecode);
470 my $authorised_value;
479 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
480 $mandatory, $repeatable, $authorised_value, $authtypecode,
481 $value_builder, $kohafield, $seealso, $hidden,
486 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
487 $res->{$tag}->{$subfield}->{tab} = $tab;
488 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
489 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
490 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
491 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
492 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
493 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
494 $res->{$tag}->{$subfield}->{seealso} = $seealso;
495 $res->{$tag}->{$subfield}->{hidden} = $hidden;
496 $res->{$tag}->{$subfield}->{isurl} = $isurl;
497 $res->{$tag}->{$subfield}->{link} = $link;
506 $authid= &AddAuthority($record, $authid,$authtypecode)
507 returns authid of the newly created authority
509 Either Create Or Modify existing authority.
516 # pass the MARC::Record to this function, and it will create the records in the authority table
517 my ($record,$authid,$authtypecode) = @_;
518 my $dbh=C4::Context->dbh;
519 my $leader=' a ';##Fixme correct leader as this one just adds utf8 to MARC21
521 # if authid empty => true add, find a new authid number
522 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
523 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
524 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
525 $record->leader(" nx j22 ");
526 my $date=POSIX::strftime("%Y%m%d",localtime);
527 if ($record->field('100')){
528 $record->field('100')->update('a'=>$date."afrey50 ba0");
530 $record->append_fields(
531 MARC::Field->new('100',' ',' '
532 ,'a'=>$date."afrey50 ba0")
537 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
538 if (!$authid and $format eq "MARC21") {
539 # only need to do this fix when modifying an existing authority
540 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
543 unless ($record->field($auth_type_tag) && $record->subfield($auth_type_tag, $auth_type_subfield)) {
544 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
549 my $sth=$dbh->prepare("select max(authid) from auth_header");
551 ($authid)=$sth->fetchrow;
553 ##Insert the recordID in MARC record
554 unless ($record->field('001') && $record->field('001')->data() eq $authid){
555 $record->delete_field($record->field('001'));
556 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
558 # warn $record->as_formatted;
559 $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
560 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
563 if (C4::Context->preference('NoZebra')) {
564 $oldRecord = GetAuthority($authid);
566 $record->add_fields('001',$authid) unless ($record->field('001'));
567 my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
568 $sth->execute($record->as_usmarc,$record->as_xml_record($format),$authid);
571 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
580 $authid= &DelAuthority($authid)
590 my $dbh=C4::Context->dbh;
592 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
593 $dbh->do("delete from auth_header where authid=$authid") ;
598 my ($authid,$record,$authtypecode,$merge)=@_;
599 my $dbh=C4::Context->dbh;
600 # my ($oldrecord)=&GetAuthority($authid);
601 # if ($oldrecord eq $record) {
604 # my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
605 #Now rewrite the $record to table with an add
606 $authid=AddAuthority($record,$authid,$authtypecode);
608 ### 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
609 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
610 ### the $merge flag is now depreceated and will be removed at code cleaning
611 if (C4::Context->preference('dontmerge') ){
612 # save the file in tmp/modified_authorities
613 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
614 unless (opendir(DIR,"$cgidir")) {
615 $cgidir = C4::Context->intranetdir."/";
619 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
620 open AUTH, "> $filename";
624 # &merge($authid,$record,$authid,$record);
629 =head2 GetAuthorityXML
633 $marcxml= &GetAuthorityXML( $authid)
634 returns xml form of record $authid
640 sub GetAuthorityXML {
641 # Returns MARC::XML of the authority passed in parameter.
643 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
644 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
645 if ($format eq "MARC21") {
646 # for MARC21, call GetAuthority instead of
647 # getting the XML directly since we may
648 # need to fix up the location of the authority
649 # code -- note that this is reasonably safe
650 # because GetAuthorityXML is used only by the
651 # indexing processes like zebraqueue_start.pl
652 my $record = GetAuthority($authid);
653 return $record->as_xml_record($format);
655 my $dbh=C4::Context->dbh;
656 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
657 $sth->execute($authid);
658 my ($marcxml)=$sth->fetchrow;
667 $record= &GetAuthority( $authid)
668 Returns MARC::Record of the authority passed in parameter.
676 my $dbh=C4::Context->dbh;
677 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
678 $sth->execute($authid);
679 my ($authtypecode, $marcxml) = $sth->fetchrow;
680 my $record=MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
681 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")));
682 $record->encoding('UTF-8');
683 if (C4::Context->preference("marcflavour") eq "MARC21") {
684 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
685 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
694 $result= &GetAuthType( $authtypecode)
695 If $authtypecode is not "" then
696 Returns hashref to authtypecode information
698 returns ref to array of hashref information of all Authtypes
705 my ($authtypecode) = @_;
706 my $dbh=C4::Context->dbh;
708 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
710 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
711 $sth->execute($authtypecode);
713 $sth=$dbh->prepare("select * from auth_types");
716 my $res=$sth->fetchall_arrayref({});
717 if (scalar(@$res)==1){
726 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
727 my $dbh=C4::Context->dbh;
729 my $record = MARC::Record->new();
730 #---- TODO : the leader is missing
732 # my %subfieldlist=();
733 my $prevvalue; # if tag <10
734 my $field; # if tag >=10
735 for (my $i=0; $i< @$rtags; $i++) {
736 # rebuild MARC::Record
737 if (@$rtags[$i] ne $prevtag) {
740 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
744 $record->add_fields($field);
747 $indicators{@$rtags[$i]}.=' ';
748 if (@$rtags[$i] <10) {
749 $prevvalue= @$rvalues[$i];
753 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
755 $prevtag = @$rtags[$i];
757 if (@$rtags[$i] <10) {
758 $prevvalue=@$rvalues[$i];
760 if (length(@$rvalues[$i])>0) {
761 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
764 $prevtag= @$rtags[$i];
767 # the last has not been included inside the loop... do it now !
768 $record->add_fields($field) if $field;
772 =head2 FindDuplicateAuthority
776 $record= &FindDuplicateAuthority( $record, $authtypecode)
777 return $authid,Summary if duplicate is found.
779 Comments : an improvement would be to return All the records that match.
785 sub FindDuplicateAuthority {
787 my ($record,$authtypecode)=@_;
788 # warn "IN for ".$record->as_formatted;
789 my $dbh = C4::Context->dbh;
790 # warn "".$record->as_formatted;
791 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
792 $sth->execute($authtypecode);
793 my ($auth_tag_to_report) = $sth->fetchrow;
795 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
796 # build a request for SearchAuthorities
797 my $query='at='.$authtypecode.' ';
798 map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)} $record->field($auth_tag_to_report)->subfields() if $record->field($auth_tag_to_report);
799 my ($error,$results)=SimpleSearch($query,"authorityserver");
800 # there is at least 1 result => return the 1st one
802 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
803 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
805 # no result, returns nothing
813 $text= &BuildSummary( $record, $authid, $authtypecode)
814 return HTML encoded Summary
816 Comment : authtypecode can be infered from both record and authid.
817 Moreover, authid can also be inferred from $record.
818 Would it be interesting to delete those things.
825 ## give this a Marc record to return summary
826 my ($record,$authid,$authtypecode)=@_;
827 my $dbh=C4::Context->dbh;
829 # handle $authtypecode is NULL or eq ""
831 my $authref = GetAuthType($authtypecode);
832 $summary = $authref->{summary};
834 # FIXME: should use I18N.pm
836 $language{'fre'}="Français";
837 $language{'eng'}="Anglais";
838 $language{'ger'}="Allemand";
839 $language{'ita'}="Italien";
840 $language{'spa'}="Espagnol";
842 $thesaurus{'1'}="Peuples";
843 $thesaurus{'2'}="Anthroponymes";
844 $thesaurus{'3'}="Oeuvres";
845 $thesaurus{'4'}="Chronologie";
846 $thesaurus{'5'}="Lieux";
847 $thesaurus{'6'}="Sujets";
849 my @fields = $record->fields();
851 # if the library has a summary defined, use it. Otherwise, build a standard one
852 # FIXME - it appears that the summary field in the authority frameworks
853 # can work as a display template. However, this doesn't
854 # suit the MARC21 version, so for now the "templating"
855 # feature will be enabled only for UNIMARC for backwards
857 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
858 my @fields = $record->fields();
859 # $reported_tag = '$9'.$result[$counter];
860 foreach my $field (@fields) {
861 my $tag = $field->tag();
862 my $tagvalue = $field->as_string();
863 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
866 $reported_tag.='$3'.$field->data();
869 my @subf = $field->subfields;
870 for my $i (0..$#subf) {
871 my $subfieldcode = $subf[$i][0];
872 my $subfieldvalue = $subf[$i][1];
873 my $tagsubf = $tag.$subfieldcode;
874 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
878 $summary =~ s/\[(.*?)]//g;
879 $summary =~ s/\n/<br>/g;
890 my @fields = $record->fields();
891 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
892 # construct UNIMARC summary, that is quite different from MARC21 one
894 foreach my $field ($record->field('2..')) {
895 $heading.= $field->subfield('a');
896 $authid=$field->subfield('3');
899 foreach my $field ($record->field('3..')) {
900 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
902 foreach my $field ($record->field('4..')) {
903 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : " if ($field->subfield('2'));
904 $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
907 foreach my $field ($record->field('5..')) {
909 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
910 $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
911 } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
912 $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
913 } elsif ($field->subfield('a')) {
914 $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
918 foreach my $field ($record->field('7..')) {
919 my $lang = substr($field->subfield('8'),3,3);
920 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
922 $broaderterms =~s/-- \n$//;
923 $narrowerterms =~s/-- \n$//;
924 $seealso =~s/-- \n$//;
926 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
927 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
928 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
929 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
930 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
931 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
933 # construct MARC21 summary
934 # FIXME - looping over 1XX is questionable
935 # since MARC21 authority should have only one 1XX
936 foreach my $field ($record->field('1..')) {
937 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
938 # in MARC21 -- purely local tags really ought to be
940 if ($record->field('100')) {
941 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
942 } elsif ($record->field('110')) {
943 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
944 } elsif ($record->field('111')) {
945 $heading.= $field->as_string('acdefghklnpqstvxyz68');
946 } elsif ($record->field('130')) {
947 $heading.= $field->as_string('adfghklmnoprstvxyz68');
948 } elsif ($record->field('148')) {
949 $heading.= $field->as_string('abvxyz68');
950 } elsif ($record->field('150')) {
951 # $heading.= $field->as_string('abvxyz68');
952 $heading.= $field->as_formatted();
953 my $tag=$field->tag();
954 $heading=~s /^$tag//g;
955 $heading =~s /\_/\$/g;
956 } elsif ($record->field('151')) {
957 $heading.= $field->as_string('avxyz68');
958 } elsif ($record->field('155')) {
959 $heading.= $field->as_string('abvxyz68');
960 } elsif ($record->field('180')) {
961 $heading.= $field->as_string('vxyz68');
962 } elsif ($record->field('181')) {
963 $heading.= $field->as_string('vxyz68');
964 } elsif ($record->field('182')) {
965 $heading.= $field->as_string('vxyz68');
966 } elsif ($record->field('185')) {
967 $heading.= $field->as_string('vxyz68');
969 $heading.= $field->as_string();
972 foreach my $field ($record->field('4..')) {
973 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
975 foreach my $field ($record->field('5..')) {
976 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
978 $summary .= ": " if $summary;
979 $summary.=$heading.$seeheading.$altheading;
985 =head2 BuildUnimarcHierarchies
989 $text= &BuildUnimarcHierarchies( $authid, $force)
990 return text containing trees for hierarchies
991 for them to be stored in auth_header
994 122,1314,2452;1324,2342,3,2452
1000 sub BuildUnimarcHierarchies{
1001 my $authid = shift @_;
1002 # warn "authid : $authid";
1003 my $force = shift @_;
1005 my $dbh=C4::Context->dbh;
1007 my $data = GetHeaderAuthority($authid);
1008 if ($data->{'authtrees'} and not $force){
1009 return $data->{'authtrees'};
1010 } elsif ($data->{'authtrees'}){
1011 $hierarchies=$data->{'authtrees'};
1013 my $record = GetAuthority($authid);
1015 foreach my $field ($record->field('550')){
1016 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1017 my $parentrecord = GetAuthority($field->subfield('3'));
1018 my $localresult=$hierarchies;
1020 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1023 @trees = split(/;/,$trees);
1025 push @trees, $trees;
1030 @globalresult = (@globalresult,@trees);
1033 $hierarchies=join(";",@globalresult);
1035 #Unless there is no ancestor, I am alone.
1036 $hierarchies="$authid" unless ($hierarchies);
1038 AddAuthorityTrees($authid,$hierarchies);
1039 return $hierarchies;
1042 =head2 BuildUnimarcHierarchy
1046 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1047 return a hashref in order to display hierarchy for record and final Authid $authid
1058 Those two latest ones should disappear soon.
1064 sub BuildUnimarcHierarchy{
1065 my $record = shift @_;
1066 my $class = shift @_;
1067 my $authid_constructed = shift @_;
1068 my $authid=$record->subfield('250','3');
1070 my $parents=""; my $children="";
1071 my (@loopparents,@loopchildren);
1072 foreach my $field ($record->field('550')){
1073 if ($field->subfield('5') && $field->subfield('a')){
1074 if ($field->subfield('5') eq 'h'){
1075 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1076 }elsif ($field->subfield('5') eq 'g'){
1077 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1079 # brothers could get in there with an else
1082 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1083 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1084 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1085 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1086 $cell{"class"}=$class;
1087 $cell{"loopauthid"}=$authid;
1088 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1089 $cell{"value"}=$record->subfield('250',"a");
1093 =head2 GetHeaderAuthority
1097 $ref= &GetHeaderAuthority( $authid)
1098 return a hashref in order auth_header table data
1104 sub GetHeaderAuthority{
1105 my $authid = shift @_;
1106 my $sql= "SELECT * from auth_header WHERE authid = ?";
1107 my $dbh=C4::Context->dbh;
1108 my $rq= $dbh->prepare($sql);
1109 $rq->execute($authid);
1110 my $data= $rq->fetchrow_hashref;
1114 =head2 AddAuthorityTrees
1118 $ref= &AddAuthorityTrees( $authid, $trees)
1119 return success or failure
1125 sub AddAuthorityTrees{
1126 my $authid = shift @_;
1127 my $trees = shift @_;
1128 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1129 my $dbh=C4::Context->dbh;
1130 my $rq= $dbh->prepare($sql);
1131 return $rq->execute($trees,$authid);
1138 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1141 Could add some feature : Migrating from a typecode to an other for instance.
1142 Then we should add some new parameter : bibliotargettag, authtargettag
1149 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1150 my $dbh=C4::Context->dbh;
1151 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1152 my $authtypecodeto = GetAuthTypeCode($mergeto);
1153 # return if authority does not exist
1154 my @X = $MARCfrom->fields();
1155 return if $#X == -1;
1156 @X = $MARCto->fields();
1157 return if $#X == -1;
1158 # search the tag to report
1159 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1160 $sth->execute($authtypecodefrom);
1161 my ($auth_tag_to_report) = $sth->fetchrow;
1164 @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
1166 @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
1168 # search all biblio tags using this authority.
1169 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1170 $sth->execute($authtypecodefrom);
1171 my @tags_using_authtype;
1172 while (my ($tagfield) = $sth->fetchrow) {
1173 push @tags_using_authtype,$tagfield."9" ;
1176 if (C4::Context->preference('NoZebra')) {
1179 # now, find every biblio using this authority
1180 my $oConnection=C4::Context->Zconn("biblioserver");
1182 $query= "an= ".$mergefrom;
1183 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1184 my $count=$oResult->size() if ($oResult);
1187 while ( $z<$count ) {
1189 $rec=$oResult->record($z);
1190 my $marcdata = $rec->raw();
1191 push @reccache, $marcdata;
1194 $oResult->destroy();
1195 foreach my $marc(@reccache){
1198 $marcrecord = MARC::File::USMARC::decode($marc);
1199 foreach my $tagfield (@tags_using_authtype){
1200 $tagfield=substr($tagfield,0,3);
1201 my @tags = $marcrecord->field($tagfield);
1202 foreach my $tag (@tags){
1203 my $tagsubs=$tag->subfield("9");
1204 #warn "$tagfield:$tagsubs:$mergefrom";
1205 if ($tagsubs== $mergefrom) {
1206 $tag->update("9" =>$mergeto);
1207 foreach my $subfield (@record_to) {
1208 # warn "$subfield,$subfield->[0],$subfield->[1]";
1209 $tag->update($subfield->[0] =>$subfield->[1]);
1212 $marcrecord->delete_field($tag);
1213 $marcrecord->add_fields($tag);
1217 my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,"") ;
1219 &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},GetFrameworkCode($oldbiblio->{'biblionumber'})) ;
1224 # now, find every other authority linked with this authority
1225 # my $oConnection=C4::Context->Zconn("authorityserver");
1227 # # att 9210 Auth-Internal-authtype
1228 # # att 9220 Auth-Internal-LN
1229 # # ccl.properties to add for authorities
1230 # $query= "= ".$mergefrom;
1231 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1232 # my $count=$oResult->size() if ($oResult);
1235 # while ( $z<$count ) {
1237 # $rec=$oResult->record($z);
1238 # my $marcdata = $rec->raw();
1239 # push @reccache, $marcdata;
1242 # $oResult->destroy();
1243 # foreach my $marc(@reccache){
1246 # $marcrecord = MARC::File::USMARC::decode($marc);
1247 # foreach my $tagfield (@tags_using_authtype){
1248 # $tagfield=substr($tagfield,0,3);
1249 # my @tags = $marcrecord->field($tagfield);
1250 # foreach my $tag (@tags){
1251 # my $tagsubs=$tag->subfield("9");
1252 # #warn "$tagfield:$tagsubs:$mergefrom";
1253 # if ($tagsubs== $mergefrom) {
1254 # $tag->update("9" =>$mergeto);
1255 # foreach my $subfield (@record_to) {
1256 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1257 # $tag->update($subfield->[0] =>$subfield->[1]);
1260 # $marcrecord->delete_field($tag);
1261 # $marcrecord->add_fields($tag);
1264 # }#foreach tagfield
1265 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1267 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1273 =head2 get_auth_type_location
1277 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1281 Get the tag and subfield used to store the heading type
1282 for indexing purposes. The C<$auth_type> parameter is
1283 optional; if it is not supplied, assume ''.
1285 This routine searches the MARC authority framework
1286 for the tag and subfield whose kohafield is
1287 C<auth_header.authtypecode>; if no such field is
1288 defined in the framework, default to the hardcoded value
1289 specific to the MARC format.
1293 sub get_auth_type_location {
1294 my $auth_type_code = @_ ? shift : '';
1296 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1297 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1298 return ($tag, $subfield);
1300 if (C4::Context->preference('marcflavour') eq "MARC21") {
1301 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1303 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1308 END { } # module clean-up code here (global destructor)
1315 Koha Developement team <info@koha.org>
1317 Paul POULAIN paul.poulain@free.fr