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
27 use vars qw($VERSION @ISA @EXPORT);
29 # set the version for version checking
30 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
37 &GetAuthMARCFromKohaField
51 &BuildUnimarcHierarchies
52 &BuildUnimarcHierarchy
55 &FindDuplicateAuthority
58 =head2 GetAuthMARCFromKohaField
62 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
63 returns tag and subfield linked to kohafield
66 Suppose Kohafield is only linked to ONE subfield
70 sub GetAuthMARCFromKohaField {
71 #AUTHfind_marc_from_kohafield
72 my ( $kohafield,$authtypecode ) = @_;
73 my $dbh=C4::Context->dbh;
74 return 0, 0 unless $kohafield;
75 $authtypecode="" unless $authtypecode;
76 my $marcfromkohafield;
77 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
78 $sth->execute($kohafield,$authtypecode);
79 my ($tagfield,$tagsubfield) = $sth->fetchrow;
81 return ($tagfield,$tagsubfield);
84 =head2 SearchAuthorities
88 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
89 returns ref to array result and count of results returned
94 sub SearchAuthorities {
95 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
96 # warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
97 my $dbh=C4::Context->dbh;
98 if (C4::Context->preference('NoZebra')) {
104 my @auths=split / /,$authtypecode ;
105 foreach my $auth (@auths){
106 $query .="AND auth_type= $auth ";
110 for(my $i = 0 ; $i <= $#{$value} ; $i++)
113 if (@$tags[$i] eq "mainmainentry") {
114 $query .=" AND mainmainentry";
115 }elsif (@$tags[$i] eq "mainentry") {
116 $query .=" AND mainentry";
120 if (@$operator[$i] eq 'is') {
121 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
122 }elsif (@$operator[$i] eq "="){
123 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
124 }elsif (@$operator[$i] eq "start"){
125 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
127 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
133 # do the query (if we had some search term
136 # warn "QUERY : $query";
137 my $result = C4::Search::NZanalyse($query,'authorityserver');
138 # warn "result : $result";
140 foreach (split /;/,$result) {
141 my ($authid,$title) = split /,/,$_;
142 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
143 # and we don't want to get only 1 result for each of them !!!
144 # hint & speed improvement : we can order without reading the record
145 # so order, and read records only for the requested page !
146 $result{$title.$authid}=$authid;
148 # sort the hash and return the same structure as GetRecords (Zebra querying)
149 my @finalresult = ();
151 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
152 foreach my $key (sort {$b cmp $a} (keys %result)) {
153 push @finalresult, $result{$key};
154 # warn "push..."$#finalresult;
157 } else { # sort by mainmainentry ASC
158 foreach my $key (sort (keys %result)) {
159 push @finalresult, $result{$key};
160 # warn "push..."$#finalresult;
164 # limit the $results_per_page to result size if it's more
165 $length = $numbers-1 if $numbers < $length;
166 # for the requested page, replace authid by the complete record
167 # speed improvement : avoid reading too much things
168 for (my $counter=$offset;$counter<=$offset+$length;$counter++) {
169 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
170 my $separator=C4::Context->preference('authoritysep');
171 my $authrecord = MARC::File::USMARC::decode(GetAuthority($finalresult[$counter])->as_usmarc);
172 my $authid=$authrecord->field('001')->data();
173 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
174 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
175 my $sth = $dbh->prepare($query_auth_tag);
176 $sth->execute($authtypecode);
177 my $auth_tag_to_report = $sth->fetchrow;
179 $newline{used}=CountUsage($authid);
180 $newline{summary} = $summary;
181 $newline{authid} = $authid;
182 $newline{even} = $counter % 2;
183 $finalresult[$counter]= \%newline;
185 return (\@finalresult, $numbers);
192 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
193 # the authtypecode. Then, search on $a of this tag_to_report
194 # also store main entry MARC tag, to extract it at end of search
196 ##first set the authtype search and may be multiple authorities
199 my @auths=split / /,$authtypecode ;
200 foreach my $auth (@auths){
201 $query .=" \@attr 1=Authority/format-id \@attr 5=100 ".$auth; ##No truncation on authtype
202 push @authtypecode ,$auth;
206 $query= "\@or ".$query;
212 for(my $i = 0 ; $i <= $#{$value} ; $i++)
215 ##If mainentry search $a tag
216 if (@$tags[$i] eq "mainmainentry") {
217 $attr =" \@attr 1=Heading ";
218 }elsif (@$tags[$i] eq "mainentry") {
219 $attr =" \@attr 1=Heading-Entity ";
221 $attr =" \@attr 1=Any ";
223 if (@$operator[$i] eq 'is') {
224 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
225 }elsif (@$operator[$i] eq "="){
226 $attr.=" \@attr 4=107 "; #Number Exact match
227 }elsif (@$operator[$i] eq "start"){
228 $attr.=" \@attr 4=1 \@attr 5=1 ";#Phrase, Right truncated
230 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
233 $attr =$attr."\"".@$value[$i]."\"";
238 ##Add how many queries generated
239 $query= $and.$query.$q2;
241 $query=' @or @attr 7=1 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading-Entity 1'.$query if ($sortby eq "HeadingAsc");
242 $query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading-Entity 1'.$query if ($sortby eq "HeadingDsc");
244 $offset=0 unless $offset;
245 my $counter = $offset;
246 $length=10 unless $length;
249 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
250 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
252 $oAResult= $oAuth[0]->search($Anewq) ;
253 while (($i = ZOOM::event(\@oAuth)) != 0) {
254 my $ev = $oAuth[$i-1]->last_event();
255 last if $ev == ZOOM::Event::ZEND;
257 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
259 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
264 $nbresults=$oAResult->size();
265 my $nremains=$nbresults;
267 my @finalresult = ();
271 ##Find authid and linkid fields
272 ##we may be searching multiple authoritytypes.
273 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
274 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
275 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
276 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
278 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
279 my $rec=$oAResult->record($counter);
280 my $marcdata=$rec->raw();
282 my $separator=C4::Context->preference('authoritysep');
283 $authrecord = MARC::File::USMARC::decode($marcdata);
284 my $authid=$authrecord->field('001')->data();
285 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
286 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
287 my $sth = $dbh->prepare($query_auth_tag);
288 $sth->execute($authtypecode);
289 my $auth_tag_to_report = $sth->fetchrow;
291 $newline{summary} = $summary;
292 $newline{authid} = $authid;
293 $newline{even} = $counter % 2;
295 push @finalresult, \%newline;
298 for (my $z=0; $z<@finalresult; $z++){
299 my $count=CountUsage($finalresult[$z]{authid});
300 $finalresult[$z]{used}=$count;
305 # $oAResult->destroy();
306 # $oAuth[0]->destroy();
308 return (\@finalresult, $nbresults);
316 $count= &CountUsage($authid)
317 counts Usage of Authid in bibliorecords.
325 if (C4::Context->preference('NoZebra')) {
326 # Read the index Koha-Auth-Number for this authid and count the lines
327 my $result = C4::Search::NZanalyse("an=$authid");
328 my @tab = split /;/,$result;
332 my $oConnection=C4::Context->Zconn("biblioserver",1);
334 $query= "an=".$authid;
335 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
337 while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
338 my $ev = $oConnection->last_event();
339 if ($ev == ZOOM::Event::ZEND) {
340 $result = $oResult->size();
347 =head2 CountUsageChildren
351 $count= &CountUsageChildren($authid)
352 counts Usage of narrower terms of Authid in bibliorecords.
357 sub CountUsageChildren {
361 =head2 GetAuthTypeCode
365 $authtypecode= &GetAuthTypeCode($authid)
366 returns authtypecode of an authid
371 sub GetAuthTypeCode {
372 #AUTHfind_authtypecode
374 my $dbh=C4::Context->dbh;
375 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
376 $sth->execute($authid);
377 my ($authtypecode) = $sth->fetchrow;
378 return $authtypecode;
385 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
386 returns a ref to hashref of authorities tag and subfield structure.
389 $tagslabel->{$tag}->{$subfield}->{'attribute'}
390 where attribute takes values in :
408 my ($forlibrarian,$authtypecode)= @_;
409 my $dbh=C4::Context->dbh;
410 $authtypecode="" unless $authtypecode;
412 my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
415 # check that authority exists
416 $sth=$dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?");
417 $sth->execute($authtypecode);
418 my ($total) = $sth->fetchrow;
419 $authtypecode="" unless ($total >0);
421 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
422 FROM auth_tag_structure
427 $sth->execute($authtypecode);
428 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
430 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
431 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
432 $res->{$tag}->{tab} = " "; # XXX
433 $res->{$tag}->{mandatory} = $mandatory;
434 $res->{$tag}->{repeatable} = $repeatable;
437 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl
438 FROM auth_subfield_structure
440 ORDER BY tagfield,tagsubfield"
442 $sth->execute($authtypecode);
445 my $authorised_value;
454 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
455 $mandatory, $repeatable, $authorised_value, $authtypecode,
456 $value_builder, $kohafield, $seealso, $hidden,
461 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
462 $res->{$tag}->{$subfield}->{tab} = $tab;
463 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
464 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
465 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
466 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
467 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
468 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
469 $res->{$tag}->{$subfield}->{seealso} = $seealso;
470 $res->{$tag}->{$subfield}->{hidden} = $hidden;
471 $res->{$tag}->{$subfield}->{isurl} = $isurl;
472 $res->{$tag}->{$subfield}->{link} = $link;
481 $authid= &AddAuthority($record, $authid,$authtypecode)
482 returns authid of the newly created authority
484 Either Create Or Modify existing authority.
490 # pass the MARC::Record to this function, and it will create the records in the authority table
491 my ($record,$authid,$authtypecode) = @_;
492 my $dbh=C4::Context->dbh;
493 my $leader=' a ';##Fixme correct leader as this one just adds utf8 to MARC21
495 # if authid empty => true add, find a new authid number
496 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
497 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
499 my $sth=$dbh->prepare("select max(authid) from auth_header");
501 ($authid)=$sth->fetchrow;
503 ##Insert the recordID in MARC record
504 ##Both authid and authtypecode is expected to be in the same field. Modify if other requirements arise
505 $record->add_fields('001',$authid) unless $record->field('001');
506 $record->add_fields('152','','','b'=>$authtypecode) unless $record->field('152');
507 # warn $record->as_formatted;
508 $dbh->do("lock tables auth_header WRITE");
509 $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
510 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
513 $record->add_fields('001',$authid) unless ($record->field('001'));
514 $record->add_fields('100',$authid) unless ($record->field('100'));
515 $record->add_fields('152','','','b'=>$authtypecode) unless ($record->field('152'));
516 $dbh->do("lock tables auth_header WRITE");
517 my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
518 $sth->execute($record->as_usmarc,$record->as_xml_record($format),$authid);
521 $dbh->do("unlock tables");
522 ModZebra($authid,'specialUpdate',"authorityserver",$record);
531 $authid= &DelAuthority($authid)
541 my $dbh=C4::Context->dbh;
543 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid));
544 $dbh->do("delete from auth_header where authid=$authid") ;
549 my ($authid,$record,$authtypecode,$merge)=@_;
550 my $dbh=C4::Context->dbh;
551 # my ($oldrecord)=&GetAuthority($authid);
552 # if ($oldrecord eq $record) {
555 # my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
556 #Now rewrite the $record to table with an add
557 $authid=AddAuthority($record,$authid,$authtypecode);
559 ### 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
560 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
561 ### the $merge flag is now depreceated and will be removed at code cleaning
562 if (C4::Context->preference('dontmerge') ){
563 # save the file in localfile/modified_authorities
564 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
565 unless (opendir(DIR,"$cgidir")) {
566 $cgidir = C4::Context->intranetdir."/";
569 my $filename = $cgidir."/localfile/modified_authorities/$authid.authid";
570 open AUTH, "> $filename";
574 # &merge($authid,$record,$authid,$record);
579 =head2 GetAuthorityXML
583 $marcxml= &GetAuthorityXML( $authid)
584 returns xml form of record $authid
589 sub GetAuthorityXML {
590 # Returns MARC::XML of the authority passed in parameter.
592 my $dbh=C4::Context->dbh;
594 $dbh->prepare("select marcxml from auth_header where authid=? " );
595 $sth->execute($authid);
596 my ($marcxml)=$sth->fetchrow;
605 $record= &GetAuthority( $authid)
606 Returns MARC::Record of the authority passed in parameter.
613 my $dbh=C4::Context->dbh;
614 my $sth=$dbh->prepare("select marcxml from auth_header where authid=?");
615 $sth->execute($authid);
616 my ($marcxml) = $sth->fetchrow;
617 my $record=MARC::Record->new_from_xml($marcxml,'UTF-8',(C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")));
618 $record->encoding('UTF-8');
626 $result= &GetAuthType( $authtypecode)
627 If $authtypecode is not "" then
628 Returns hashref to authtypecode information
630 returns ref to array of hashref information of all Authtypes
636 my ($authtypecode) = @_;
637 my $dbh=C4::Context->dbh;
640 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
641 $sth->execute($authtypecode);
643 $sth=$dbh->prepare("select * from auth_types");
646 my $res=$sth->fetchall_arrayref({});
647 if (scalar(@$res)==1){
656 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
657 my $dbh=C4::Context->dbh;
659 my $record = MARC::Record->new();
660 #---- TODO : the leader is missing
662 # my %subfieldlist=();
663 my $prevvalue; # if tag <10
664 my $field; # if tag >=10
665 for (my $i=0; $i< @$rtags; $i++) {
666 # rebuild MARC::Record
667 if (@$rtags[$i] ne $prevtag) {
670 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
674 $record->add_fields($field);
677 $indicators{@$rtags[$i]}.=' ';
678 if (@$rtags[$i] <10) {
679 $prevvalue= @$rvalues[$i];
683 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
685 $prevtag = @$rtags[$i];
687 if (@$rtags[$i] <10) {
688 $prevvalue=@$rvalues[$i];
690 if (length(@$rvalues[$i])>0) {
691 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
694 $prevtag= @$rtags[$i];
697 # the last has not been included inside the loop... do it now !
698 $record->add_fields($field) if $field;
702 =head2 FindDuplicateAuthority
706 $record= &FindDuplicateAuthority( $record, $authtypecode)
707 return $authid,Summary if duplicate is found.
709 Comments : an improvement would be to return All the records that match.
715 sub FindDuplicateAuthority {
717 my ($record,$authtypecode)=@_;
718 # warn "IN for ".$record->as_formatted;
719 my $dbh = C4::Context->dbh;
720 # warn "".$record->as_formatted;
721 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
722 $sth->execute($authtypecode);
723 my ($auth_tag_to_report) = $sth->fetchrow;
725 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
726 # build a request for SearchAuthorities
727 my $query='at='.$authtypecode.' ';
728 map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)} $record->field($auth_tag_to_report)->subfields() if $record->field($auth_tag_to_report);
729 my ($error,$results)=SimpleSearch($query,"authorityserver");
730 # there is at least 1 result => return the 1st one
732 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
733 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
735 # no result, returns nothing
743 $text= &BuildSummary( $record, $authid, $authtypecode)
744 return HTML encoded Summary
746 Comment : authtypecode can be infered from both record and authid.
747 Moreover, authid can also be inferred from $record.
748 Would it be interesting to delete those things.
755 ## give this a Marc record to return summary
756 my ($record,$authid,$authtypecode)=@_;
757 my $dbh=C4::Context->dbh;
758 my $authref = GetAuthType($authtypecode);
759 my $summary = $authref->{summary};
761 $language{'fre'}="Français";
762 $language{'eng'}="Anglais";
763 $language{'ger'}="Allemand";
764 $language{'ita'}="Italien";
765 $language{'spa'}="Espagnol";
767 $thesaurus{'1'}="Peuples";
768 $thesaurus{'2'}="Anthroponymes";
769 $thesaurus{'3'}="Oeuvres";
770 $thesaurus{'4'}="Chronologie";
771 $thesaurus{'5'}="Lieux";
772 $thesaurus{'6'}="Sujets";
774 my @fields = $record->fields();
776 # if the library has a summary defined, use it. Otherwise, build a standard one
778 my @fields = $record->fields();
779 # $reported_tag = '$9'.$result[$counter];
780 foreach my $field (@fields) {
781 my $tag = $field->tag();
782 my $tagvalue = $field->as_string();
783 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
786 $reported_tag.='$3'.$field->data();
789 my @subf = $field->subfields;
790 for my $i (0..$#subf) {
791 my $subfieldcode = $subf[$i][0];
792 my $subfieldvalue = $subf[$i][1];
793 my $tagsubf = $tag.$subfieldcode;
794 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
798 $summary =~ s/\[(.*?)]//g;
799 $summary =~ s/\n/<br>/g;
810 my @fields = $record->fields();
811 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
812 # construct UNIMARC summary, that is quite different from MARC21 one
814 foreach my $field ($record->field('2..')) {
815 $heading.= $field->subfield('a');
816 $authid=$field->subfield('3');
819 foreach my $field ($record->field('3..')) {
820 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
822 foreach my $field ($record->field('4..')) {
823 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : " if ($field->subfield('2'));
824 $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
827 foreach my $field ($record->field('5..')) {
829 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
830 $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
831 } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
832 $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
833 } elsif ($field->subfield('a')) {
834 $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
838 foreach my $field ($record->field('7..')) {
839 my $lang = substr($field->subfield('8'),3,3);
840 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
842 $broaderterms =~s/-- \n$//;
843 $narrowerterms =~s/-- \n$//;
844 $seealso =~s/-- \n$//;
846 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
847 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
848 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
849 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
850 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
851 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
853 # construct MARC21 summary
854 foreach my $field ($record->field('1..')) {
855 if ($record->field('100')) {
856 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
857 } elsif ($record->field('110')) {
858 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
859 } elsif ($record->field('111')) {
860 $heading.= $field->as_string('acdefghklnpqstvxyz68');
861 } elsif ($record->field('130')) {
862 $heading.= $field->as_string('adfghklmnoprstvxyz68');
863 } elsif ($record->field('148')) {
864 $heading.= $field->as_string('abvxyz68');
865 } elsif ($record->field('150')) {
866 # $heading.= $field->as_string('abvxyz68');
867 $heading.= $field->as_formatted();
868 my $tag=$field->tag();
869 $heading=~s /^$tag//g;
870 $heading =~s /\_/\$/g;
871 } elsif ($record->field('151')) {
872 $heading.= $field->as_string('avxyz68');
873 } elsif ($record->field('155')) {
874 $heading.= $field->as_string('abvxyz68');
875 } elsif ($record->field('180')) {
876 $heading.= $field->as_string('vxyz68');
877 } elsif ($record->field('181')) {
878 $heading.= $field->as_string('vxyz68');
879 } elsif ($record->field('182')) {
880 $heading.= $field->as_string('vxyz68');
881 } elsif ($record->field('185')) {
882 $heading.= $field->as_string('vxyz68');
884 $heading.= $field->as_string();
887 foreach my $field ($record->field('4..')) {
888 $seeheading.= " ".$field->as_string()."<br />";
889 $seeheading.= " <i>see:</i> ".$seeheading."<br />";
891 foreach my $field ($record->field('5..')) {
892 $altheading.= " <i>see also:</i> ".$field->as_string()."<br />";
893 $altheading.= " ".$field->as_string()."<br />";
894 $altheading.= " <i>see also:</i> ".$altheading."<br />";
896 $summary.=$heading.$seeheading.$altheading;
902 =head2 BuildUnimarcHierarchies
906 $text= &BuildUnimarcHierarchies( $authid, $force)
907 return text containing trees for hierarchies
908 for them to be stored in auth_header
911 122,1314,2452;1324,2342,3,2452
916 sub BuildUnimarcHierarchies{
917 my $authid = shift @_;
918 # warn "authid : $authid";
919 my $force = shift @_;
921 my $dbh=C4::Context->dbh;
923 my $data = GetHeaderAuthority($authid);
924 if ($data->{'authtrees'} and not $force){
925 return $data->{'authtrees'};
926 } elsif ($data->{'authtrees'}){
927 $hierarchies=$data->{'authtrees'};
929 my $record = GetAuthority($authid);
931 foreach my $field ($record->field('550')){
932 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
933 my $parentrecord = GetAuthority($field->subfield('3'));
934 my $localresult=$hierarchies;
936 $trees = BuildUnimarcHierarchies($field->subfield('3'));
939 @trees = split(/;/,$trees);
946 @globalresult = (@globalresult,@trees);
949 $hierarchies=join(";",@globalresult);
951 #Unless there is no ancestor, I am alone.
952 $hierarchies="$authid" unless ($hierarchies);
954 AddAuthorityTrees($authid,$hierarchies);
958 =head2 BuildUnimarcHierarchy
962 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
963 return a hashref in order to display hierarchy for record and final Authid $authid
974 Those two latest ones should disappear soon.
979 sub BuildUnimarcHierarchy{
980 my $record = shift @_;
981 my $class = shift @_;
982 my $authid_constructed = shift @_;
983 my $authid=$record->subfield('250','3');
985 my $parents=""; my $children="";
986 my (@loopparents,@loopchildren);
987 foreach my $field ($record->field('550')){
988 if ($field->subfield('5') && $field->subfield('a')){
989 if ($field->subfield('5') eq 'h'){
990 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
991 }elsif ($field->subfield('5') eq 'g'){
992 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
994 # brothers could get in there with an else
997 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
998 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
999 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1000 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1001 $cell{"class"}=$class;
1002 $cell{"loopauthid"}=$authid;
1003 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1004 $cell{"value"}=$record->subfield('250',"a");
1008 =head2 GetHeaderAuthority
1012 $ref= &GetHeaderAuthority( $authid)
1013 return a hashref in order auth_header table data
1018 sub GetHeaderAuthority{
1019 my $authid = shift @_;
1020 my $sql= "SELECT * from auth_header WHERE authid = ?";
1021 my $dbh=C4::Context->dbh;
1022 my $rq= $dbh->prepare($sql);
1023 $rq->execute($authid);
1024 my $data= $rq->fetchrow_hashref;
1028 =head2 AddAuthorityTrees
1032 $ref= &AddAuthorityTrees( $authid, $trees)
1033 return success or failure
1039 sub AddAuthorityTrees{
1040 my $authid = shift @_;
1041 my $trees = shift @_;
1042 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1043 my $dbh=C4::Context->dbh;
1044 my $rq= $dbh->prepare($sql);
1045 return $rq->execute($trees,$authid);
1052 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1055 Could add some feature : Migrating from a typecode to an other for instance.
1056 Then we should add some new parameter : bibliotargettag, authtargettag
1062 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1063 my $dbh=C4::Context->dbh;
1064 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1065 my $authtypecodeto = GetAuthTypeCode($mergeto);
1066 # return if authority does not exist
1067 my @X = $MARCfrom->fields();
1068 return if $#X == -1;
1069 @X = $MARCto->fields();
1070 return if $#X == -1;
1071 # search the tag to report
1072 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1073 $sth->execute($authtypecodefrom);
1074 my ($auth_tag_to_report) = $sth->fetchrow;
1077 @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
1079 @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
1081 # search all biblio tags using this authority.
1082 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1083 $sth->execute($authtypecodefrom);
1084 my @tags_using_authtype;
1085 while (my ($tagfield) = $sth->fetchrow) {
1086 push @tags_using_authtype,$tagfield."9" ;
1089 if (C4::Context->preference('NoZebra')) {
1092 # now, find every biblio using this authority
1093 my $oConnection=C4::Context->Zconn("biblioserver");
1095 $query= "an= ".$mergefrom;
1096 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1097 my $count=$oResult->size() if ($oResult);
1100 while ( $z<$count ) {
1102 $rec=$oResult->record($z);
1103 my $marcdata = $rec->raw();
1104 push @reccache, $marcdata;
1107 $oResult->destroy();
1108 foreach my $marc(@reccache){
1111 $marcrecord = MARC::File::USMARC::decode($marc);
1112 foreach my $tagfield (@tags_using_authtype){
1113 $tagfield=substr($tagfield,0,3);
1114 my @tags = $marcrecord->field($tagfield);
1115 foreach my $tag (@tags){
1116 my $tagsubs=$tag->subfield("9");
1117 #warn "$tagfield:$tagsubs:$mergefrom";
1118 if ($tagsubs== $mergefrom) {
1119 $tag->update("9" =>$mergeto);
1120 foreach my $subfield (@record_to) {
1121 # warn "$subfield,$subfield->[0],$subfield->[1]";
1122 $tag->update($subfield->[0] =>$subfield->[1]);
1125 $marcrecord->delete_field($tag);
1126 $marcrecord->add_fields($tag);
1130 my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,"") ;
1132 &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},GetFrameworkCode($oldbiblio->{'biblionumber'})) ;
1137 # now, find every other authority linked with this authority
1138 # my $oConnection=C4::Context->Zconn("authorityserver");
1140 # # att 9210 Auth-Internal-authtype
1141 # # att 9220 Auth-Internal-LN
1142 # # ccl.properties to add for authorities
1143 # $query= "= ".$mergefrom;
1144 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1145 # my $count=$oResult->size() if ($oResult);
1148 # while ( $z<$count ) {
1150 # $rec=$oResult->record($z);
1151 # my $marcdata = $rec->raw();
1152 # push @reccache, $marcdata;
1155 # $oResult->destroy();
1156 # foreach my $marc(@reccache){
1159 # $marcrecord = MARC::File::USMARC::decode($marc);
1160 # foreach my $tagfield (@tags_using_authtype){
1161 # $tagfield=substr($tagfield,0,3);
1162 # my @tags = $marcrecord->field($tagfield);
1163 # foreach my $tag (@tags){
1164 # my $tagsubs=$tag->subfield("9");
1165 # #warn "$tagfield:$tagsubs:$mergefrom";
1166 # if ($tagsubs== $mergefrom) {
1167 # $tag->update("9" =>$mergeto);
1168 # foreach my $subfield (@record_to) {
1169 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1170 # $tag->update($subfield->[0] =>$subfield->[1]);
1173 # $marcrecord->delete_field($tag);
1174 # $marcrecord->add_fields($tag);
1177 # }#foreach tagfield
1178 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1180 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1185 END { } # module clean-up code here (global destructor)
1191 Koha Developement team <info@koha.org>
1193 Paul POULAIN paul.poulain@free.fr
1199 # Revision 1.50 2007/07/26 15:14:05 toins
1200 # removing warn compilation.
1202 # Revision 1.49 2007/07/16 15:45:28 hdl
1203 # Adding Summary for UNIMARC authorities
1205 # Revision 1.48 2007/06/25 15:01:45 tipaul
1206 # bugfixes on unimarc 100 handling (the field used for encoding)
1208 # Revision 1.47 2007/06/06 13:08:35 tipaul
1209 # bugfixes (various), handling utf-8 without guessencoding (as suggested by joshua, fixing some zebra config files -for french but should be interesting for other languages-
1211 # Revision 1.46 2007/05/10 14:45:15 tipaul
1213 # - support for authorities
1214 # - some bugfixes in ordering and "CCL" parsing
1215 # - support for authorities <=> biblios walking
1217 # Seems I can do what I want now, so I consider its done, except for bugfixes that will be needed i m sure !
1219 # Revision 1.45 2007/04/06 14:48:45 hdl
1220 # Code Cleaning : AuthoritiesMARC.
1222 # Revision 1.44 2007/04/05 12:17:55 btoumi
1223 # add "sort by" with heading-entity in authorities search
1225 # Revision 1.43 2007/03/30 11:59:16 tipaul
1226 # some cleaning (minor, the main one will come later) : removing some unused subs
1228 # Revision 1.42 2007/03/29 16:45:53 tipaul
1229 # Code cleaning of Biblio.pm (continued)
1231 # All subs have be cleaned :
1234 # - reordering Biblio.pm completly
1235 # - using only naming conventions
1237 # Seems to have broken nothing, but it still has to be heavily tested.
1238 # Note that Biblio.pm is now much more efficient than previously & probably more reliable as well.
1240 # Revision 1.41 2007/03/29 13:30:31 tipaul
1242 # == Biblio.pm cleaning (useless) ==
1243 # * some sub declaration dropped
1244 # * removed modbiblio sub
1245 # * removed moditem sub
1246 # * removed newitems. It was used only in finishrecieve. Replaced by a TransformKohaToMarc+AddItem, that is better.
1247 # * removed MARCkoha2marcItem
1248 # * removed MARCdelsubfield declaration
1249 # * removed MARCkoha2marcBiblio
1251 # == Biblio.pm cleaning (naming conventions) ==
1252 # * MARCgettagslib renamed to GetMarcStructure
1253 # * MARCgetitems renamed to GetMarcItem
1254 # * MARCfind_frameworkcode renamed to GetFrameworkCode
1255 # * MARCmarc2koha renamed to TransformMarcToKoha
1256 # * MARChtml2marc renamed to TransformHtmlToMarc
1257 # * MARChtml2xml renamed to TranformeHtmlToXml
1258 # * zebraop renamed to ModZebra
1261 # * removing MARC=OFF related scripts (in cataloguing directory)
1262 # * removed checkitems (function related to MARC=off feature, that is completly broken in head. If someone want to reintroduce it, hard work coming...)
1263 # * removed getitemsbybiblioitem (used only by MARC=OFF scripts, that is removed as well)
1265 # Revision 1.40 2007/03/28 10:39:16 hdl
1266 # removing $dbh as a parameter in AuthoritiesMarc functions
1267 # And reporting all differences into the scripts taht relies on those functions.
1269 # Revision 1.39 2007/03/16 01:25:08 kados
1270 # Using my precrash CVS copy I did the following:
1272 # cvs -z3 -d:ext:kados@cvs.savannah.nongnu.org:/sources/koha co -P koha
1273 # find koha.precrash -type d -name "CVS" -exec rm -v {} \;
1274 # cp -r koha.precrash/* koha/
1278 # This should in theory put us right back where we were before the crash
1280 # Revision 1.39 2007/03/12 22:16:31 kados
1281 # chcking for field before calling subfields
1283 # Revision 1.38 2007/03/09 14:31:47 tipaul
1284 # rel_3_0 moved to HEAD
1286 # Revision 1.28.2.17 2007/02/05 13:16:08 hdl
1287 # Removing Link from AuthoritiesMARC summary (caused a problem owed to the API differences between opac and intranet)
1288 # + removing $dbh in SearchAuthorities
1289 # + adding links in templates on summaries to go to full view.
1290 # (no more links in popup authorities. or should we add it ?)
1292 # Revision 1.28.2.16 2007/02/02 18:07:42 hdl
1293 # Sorting and searching for exact term now works.
1295 # Revision 1.28.2.15 2007/01/24 10:17:47 hdl
1296 # FindDuplicate Now works.
1297 # Be AWARE that it needs a change ccl.properties.
1299 # Revision 1.28.2.14 2007/01/10 14:40:11 hdl
1300 # Adding Authorities tree.
1302 # Revision 1.28.2.13 2007/01/09 15:18:09 hdl
1303 # Adding an to ccl.properties to allow ccl search for authority-numbers.
1304 # Fixing Some problems with the previous modification to allow pqf search to work for more than one page.
1305 # Using search for an= for an authority-Number.
1307 # Revision 1.28.2.12 2007/01/09 13:51:31 hdl
1308 # Bug Fixing : CountUsage used *synchronous* connection where biblio used ****asynchronous**** one.
1309 # First try to get it work.
1311 # Revision 1.28.2.11 2007/01/05 14:37:26 btoumi
1312 # bug fix : remove wrong field in sql syntaxe from auth_subfield_structure table
1314 # Revision 1.28.2.10 2007/01/04 13:11:08 tipaul
1315 # commenting 2 zconn destroy
1317 # Revision 1.28.2.9 2006/12/22 15:09:53 toins
1318 # removing C4::Database;
1320 # Revision 1.28.2.8 2006/12/20 17:13:19 hdl
1321 # modifying use of GILS into use of @attr 1=Koha-Auth-Number
1323 # Revision 1.28.2.7 2006/12/18 16:45:38 tipaul
1326 # Revision 1.28.2.6 2006/12/07 16:45:43 toins
1327 # removing warn compilation. (perl -wc)
1329 # Revision 1.28.2.5 2006/12/06 14:19:59 hdl
1330 # ABugFixing : Authority count Management.
1332 # Revision 1.28.2.4 2006/11/17 13:18:58 tipaul
1333 # code cleaning : removing use of "bib", and replacing with "biblionumber"
1335 # WARNING : I tried to do carefully, but there are probably some mistakes.
1336 # So if you encounter a problem you didn't have before, look for this change !!!
1337 # anyway, I urge everybody to use only "biblionumber", instead of "bib", "bi", "biblio" or anything else. will be easier to maintain !!!
1339 # Revision 1.28.2.3 2006/11/17 11:17:30 tipaul
1340 # code cleaning : removing use of "bib", and replacing with "biblionumber"
1342 # WARNING : I tried to do carefully, but there are probably some mistakes.
1343 # So if you encounter a problem you didn't have before, look for this change !!!
1344 # anyway, I urge everybody to use only "biblionumber", instead of "bib", "bi", "biblio" or anything else. will be easier to maintain !!!
1346 # Revision 1.28.2.2 2006/10/12 22:04:47 hdl
1347 # Authorities working with zebra.
1348 # zebra Configuration files are comitted next.