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-Main ";
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 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield 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 my $orderstring= ($sortby eq "HeadingAsc"?
256 '@attr 7=1 @attr 1=Heading 0'
258 $sortby eq "HeadingDsc"?
259 '@attr 7=2 @attr 1=Heading 0'
262 $query=($query?"\@or $orderstring $query":"\@or \@attr 1=_ALLRECORDS \@attr 2=103 '' $orderstring ");
264 $offset=0 unless $offset;
265 my $counter = $offset;
266 $length=10 unless $length;
269 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
270 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
272 $oAResult= $oAuth[0]->search($Anewq) ;
273 while (($i = ZOOM::event(\@oAuth)) != 0) {
274 my $ev = $oAuth[$i-1]->last_event();
275 last if $ev == ZOOM::Event::ZEND;
277 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
279 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
284 $nbresults=$oAResult->size();
285 my $nremains=$nbresults;
287 my @finalresult = ();
291 ##Find authid and linkid fields
292 ##we may be searching multiple authoritytypes.
293 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
294 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
295 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
296 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
298 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
299 my $rec=$oAResult->record($counter);
300 my $marcdata=$rec->raw();
302 my $separator=C4::Context->preference('authoritysep');
303 $authrecord = MARC::File::USMARC::decode($marcdata);
304 my $authid=$authrecord->field('001')->data();
305 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
306 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
307 my $sth = $dbh->prepare($query_auth_tag);
308 $sth->execute($authtypecode);
309 my $auth_tag_to_report = $sth->fetchrow;
311 my $mainentry = $authrecord->field($auth_tag_to_report);
313 foreach ($mainentry->subfields()) {
314 $reported_tag .='$'.$_->[0].$_->[1];
318 $newline{summary} = $summary;
319 $newline{authid} = $authid;
320 $newline{even} = $counter % 2;
321 $newline{reported_tag} = $reported_tag;
323 push @finalresult, \%newline;
326 for (my $z=0; $z<@finalresult; $z++){
327 my $count=CountUsage($finalresult[$z]{authid});
328 $finalresult[$z]{used}=$count;
333 # $oAResult->destroy();
334 # $oAuth[0]->destroy();
336 return (\@finalresult, $nbresults);
344 $count= &CountUsage($authid)
345 counts Usage of Authid in bibliorecords.
353 if (C4::Context->preference('NoZebra')) {
354 # Read the index Koha-Auth-Number for this authid and count the lines
355 my $result = C4::Search::NZanalyse("an=$authid");
356 my @tab = split /;/,$result;
360 my $oConnection=C4::Context->Zconn("biblioserver",1);
362 $query= "an=".$authid;
363 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
365 while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
366 my $ev = $oConnection->last_event();
367 if ($ev == ZOOM::Event::ZEND) {
368 $result = $oResult->size();
375 =head2 CountUsageChildren
379 $count= &CountUsageChildren($authid)
380 counts Usage of narrower terms of Authid in bibliorecords.
386 sub CountUsageChildren {
390 =head2 GetAuthTypeCode
394 $authtypecode= &GetAuthTypeCode($authid)
395 returns authtypecode of an authid
401 sub GetAuthTypeCode {
402 #AUTHfind_authtypecode
404 my $dbh=C4::Context->dbh;
405 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
406 $sth->execute($authid);
407 my ($authtypecode) = $sth->fetchrow;
408 return $authtypecode;
415 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
416 returns a ref to hashref of authorities tag and subfield structure.
419 $tagslabel->{$tag}->{$subfield}->{'attribute'}
420 where attribute takes values in :
439 my ($forlibrarian,$authtypecode)= @_;
440 my $dbh=C4::Context->dbh;
441 $authtypecode="" unless $authtypecode;
443 my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
446 # check that authority exists
447 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
448 $sth->execute($authtypecode);
449 my ($total) = $sth->fetchrow;
450 $authtypecode="" unless ($total >0);
452 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
453 FROM auth_tag_structure
458 $sth->execute($authtypecode);
459 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
461 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
462 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
463 $res->{$tag}->{tab} = " "; # XXX
464 $res->{$tag}->{mandatory} = $mandatory;
465 $res->{$tag}->{repeatable} = $repeatable;
468 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
469 FROM auth_subfield_structure
471 ORDER BY tagfield,tagsubfield"
473 $sth->execute($authtypecode);
476 my $authorised_value;
485 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
486 $mandatory, $repeatable, $authorised_value, $authtypecode,
487 $value_builder, $kohafield, $seealso, $hidden,
492 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
493 $res->{$tag}->{$subfield}->{tab} = $tab;
494 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
495 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
496 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
497 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
498 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
499 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
500 $res->{$tag}->{$subfield}->{seealso} = $seealso;
501 $res->{$tag}->{$subfield}->{hidden} = $hidden;
502 $res->{$tag}->{$subfield}->{isurl} = $isurl;
503 $res->{$tag}->{$subfield}->{link} = $link;
512 $authid= &AddAuthority($record, $authid,$authtypecode)
513 returns authid of the newly created authority
515 Either Create Or Modify existing authority.
522 # pass the MARC::Record to this function, and it will create the records in the authority table
523 my ($record,$authid,$authtypecode) = @_;
524 my $dbh=C4::Context->dbh;
525 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
527 # if authid empty => true add, find a new authid number
528 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
529 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
531 if ($format eq "MARC21") {
532 if (!$record->leader) {
533 $record->leader($leader);
535 if (!$record->field('003')) {
536 $record->insert_fields_ordered(
537 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
540 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
541 if (!$record->field('005')) {
542 $record->insert_fields_ordered(
543 MARC::Field->new('005',$time.".0")
546 my $date=POSIX::strftime("%y%m%d",localtime);
547 if (!$record->field('008')) {
548 $record->insert_fields_ordered(
549 MARC::Field->new('008',$date."|||a|||||| | ||| d")
552 if (!$record->field('040')) {
553 $record->insert_fields_ordered(
554 MARC::Field->new('040','','',
555 'a' => C4::Context->preference('MARCOrgCode'),
556 'c' => C4::Context->preference('MARCOrgCode')
562 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
563 $record->leader(" nx j22 ");
564 my $date=POSIX::strftime("%Y%m%d",localtime);
565 if ($record->field('100')){
566 $record->field('100')->update('a'=>$date."afrey50 ba0");
568 $record->append_fields(
569 MARC::Field->new('100',' ',' '
570 ,'a'=>$date."afrey50 ba0")
574 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
575 if (!$authid and $format eq "MARC21") {
576 # only need to do this fix when modifying an existing authority
577 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
580 unless ($record->field($auth_type_tag) && $record->subfield($auth_type_tag, $auth_type_subfield)) {
581 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
586 my $sth=$dbh->prepare("select max(authid) from auth_header");
588 ($authid)=$sth->fetchrow;
590 ##Insert the recordID in MARC record
591 unless ($record->field('001') && $record->field('001')->data() eq $authid){
592 $record->delete_field($record->field('001'));
593 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
595 # warn $record->as_formatted;
596 $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
597 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
600 if (C4::Context->preference('NoZebra')) {
601 $oldRecord = GetAuthority($authid);
603 $record->add_fields('001',$authid) unless ($record->field('001'));
604 my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
605 $sth->execute($record->as_usmarc,$record->as_xml_record($format),$authid);
607 $dbh->do("unlock tables");
609 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
618 $authid= &DelAuthority($authid)
628 my $dbh=C4::Context->dbh;
630 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
631 $dbh->do("delete from auth_header where authid=$authid") ;
636 my ($authid,$record,$authtypecode,$merge)=@_;
637 my $dbh=C4::Context->dbh;
638 #Now rewrite the $record to table with an add
639 my $oldrecord=GetAuthority($authid);
640 $authid=AddAuthority($record,$authid,$authtypecode);
642 ### 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
643 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
644 ### the $merge flag is now depreceated and will be removed at code cleaning
645 if (C4::Context->preference('dontmerge') ){
646 # save the file in tmp/modified_authorities
647 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
648 unless (opendir(DIR,"$cgidir")) {
649 $cgidir = C4::Context->intranetdir."/";
653 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
654 open AUTH, "> $filename";
658 &merge($authid,$oldrecord,$authid,$record);
663 =head2 GetAuthorityXML
667 $marcxml= &GetAuthorityXML( $authid)
668 returns xml form of record $authid
674 sub GetAuthorityXML {
675 # Returns MARC::XML of the authority passed in parameter.
677 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
678 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
679 if ($format eq "MARC21") {
680 # for MARC21, call GetAuthority instead of
681 # getting the XML directly since we may
682 # need to fix up the location of the authority
683 # code -- note that this is reasonably safe
684 # because GetAuthorityXML is used only by the
685 # indexing processes like zebraqueue_start.pl
686 my $record = GetAuthority($authid);
687 return $record->as_xml_record($format);
689 my $dbh=C4::Context->dbh;
690 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
691 $sth->execute($authid);
692 my ($marcxml)=$sth->fetchrow;
701 $record= &GetAuthority( $authid)
702 Returns MARC::Record of the authority passed in parameter.
710 my $dbh=C4::Context->dbh;
711 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
712 $sth->execute($authid);
713 my ($authtypecode, $marcxml) = $sth->fetchrow;
714 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
715 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
716 return undef if ($@);
717 $record->encoding('UTF-8');
718 if (C4::Context->preference("marcflavour") eq "MARC21") {
719 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
720 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
729 $result = &GetAuthType($authtypecode)
733 If the authority type specified by C<$authtypecode> exists,
734 returns a hashref of the type's fields. If the type
735 does not exist, returns undef.
740 my ($authtypecode) = @_;
741 my $dbh=C4::Context->dbh;
743 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
744 # type (FIXME but why?)
745 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
746 $sth->execute($authtypecode);
747 if (my $res = $sth->fetchrow_hashref) {
756 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
757 my $dbh=C4::Context->dbh;
759 my $record = MARC::Record->new();
760 #---- TODO : the leader is missing
762 # my %subfieldlist=();
763 my $prevvalue; # if tag <10
764 my $field; # if tag >=10
765 for (my $i=0; $i< @$rtags; $i++) {
766 # rebuild MARC::Record
767 if (@$rtags[$i] ne $prevtag) {
770 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
774 $record->add_fields($field);
777 $indicators{@$rtags[$i]}.=' ';
778 if (@$rtags[$i] <10) {
779 $prevvalue= @$rvalues[$i];
783 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
785 $prevtag = @$rtags[$i];
787 if (@$rtags[$i] <10) {
788 $prevvalue=@$rvalues[$i];
790 if (length(@$rvalues[$i])>0) {
791 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
794 $prevtag= @$rtags[$i];
797 # the last has not been included inside the loop... do it now !
798 $record->add_fields($field) if $field;
802 =head2 FindDuplicateAuthority
806 $record= &FindDuplicateAuthority( $record, $authtypecode)
807 return $authid,Summary if duplicate is found.
809 Comments : an improvement would be to return All the records that match.
815 sub FindDuplicateAuthority {
817 my ($record,$authtypecode)=@_;
818 # warn "IN for ".$record->as_formatted;
819 my $dbh = C4::Context->dbh;
820 # warn "".$record->as_formatted;
821 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
822 $sth->execute($authtypecode);
823 my ($auth_tag_to_report) = $sth->fetchrow;
825 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
826 # build a request for SearchAuthorities
827 my $query='at='.$authtypecode.' ';
828 map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)} $record->field($auth_tag_to_report)->subfields() if $record->field($auth_tag_to_report);
829 my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
830 # there is at least 1 result => return the 1st one
832 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
833 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
835 # no result, returns nothing
843 $text= &BuildSummary( $record, $authid, $authtypecode)
844 return HTML encoded Summary
846 Comment : authtypecode can be infered from both record and authid.
847 Moreover, authid can also be inferred from $record.
848 Would it be interesting to delete those things.
855 ## give this a Marc record to return summary
856 my ($record,$authid,$authtypecode)=@_;
857 my $dbh=C4::Context->dbh;
859 # handle $authtypecode is NULL or eq ""
861 my $authref = GetAuthType($authtypecode);
862 $summary = $authref->{summary};
864 # FIXME: should use I18N.pm
866 $language{'fre'}="Français";
867 $language{'eng'}="Anglais";
868 $language{'ger'}="Allemand";
869 $language{'ita'}="Italien";
870 $language{'spa'}="Espagnol";
872 $thesaurus{'1'}="Peuples";
873 $thesaurus{'2'}="Anthroponymes";
874 $thesaurus{'3'}="Oeuvres";
875 $thesaurus{'4'}="Chronologie";
876 $thesaurus{'5'}="Lieux";
877 $thesaurus{'6'}="Sujets";
879 my @fields = $record->fields();
881 # if the library has a summary defined, use it. Otherwise, build a standard one
882 # FIXME - it appears that the summary field in the authority frameworks
883 # can work as a display template. However, this doesn't
884 # suit the MARC21 version, so for now the "templating"
885 # feature will be enabled only for UNIMARC for backwards
887 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
888 my @fields = $record->fields();
889 # $reported_tag = '$9'.$result[$counter];
890 foreach my $field (@fields) {
891 my $tag = $field->tag();
892 my $tagvalue = $field->as_string();
893 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
896 $reported_tag.='$3'.$field->data();
899 my @subf = $field->subfields;
900 for my $i (0..$#subf) {
901 my $subfieldcode = $subf[$i][0];
902 my $subfieldvalue = $subf[$i][1];
903 my $tagsubf = $tag.$subfieldcode;
904 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
908 $summary =~ s/\[(.*?)]//g;
909 $summary =~ s/\n/<br>/g;
920 my @fields = $record->fields();
921 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
922 # construct UNIMARC summary, that is quite different from MARC21 one
924 foreach my $field ($record->field('2..')) {
925 $heading.= $field->subfield('a');
926 $authid=$field->subfield('3');
929 foreach my $field ($record->field('3..')) {
930 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
932 foreach my $field ($record->field('4..')) {
933 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : " if ($field->subfield('2'));
934 $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
937 foreach my $field ($record->field('5..')) {
939 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
940 $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
941 } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
942 $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
943 } elsif ($field->subfield('a')) {
944 $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
948 foreach my $field ($record->field('7..')) {
949 my $lang = substr($field->subfield('8'),3,3);
950 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
952 $broaderterms =~s/-- \n$//;
953 $narrowerterms =~s/-- \n$//;
954 $seealso =~s/-- \n$//;
956 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
957 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
958 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
959 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
960 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
961 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
963 # construct MARC21 summary
964 # FIXME - looping over 1XX is questionable
965 # since MARC21 authority should have only one 1XX
966 foreach my $field ($record->field('1..')) {
967 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
968 # in MARC21 -- purely local tags really ought to be
970 if ($record->field('100')) {
971 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
972 } elsif ($record->field('110')) {
973 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
974 } elsif ($record->field('111')) {
975 $heading.= $field->as_string('acdefghklnpqstvxyz68');
976 } elsif ($record->field('130')) {
977 $heading.= $field->as_string('adfghklmnoprstvxyz68');
978 } elsif ($record->field('148')) {
979 $heading.= $field->as_string('abvxyz68');
980 } elsif ($record->field('150')) {
981 # $heading.= $field->as_string('abvxyz68');
982 $heading.= $field->as_formatted();
983 my $tag=$field->tag();
984 $heading=~s /^$tag//g;
985 $heading =~s /\_/\$/g;
986 } elsif ($record->field('151')) {
987 $heading.= $field->as_string('avxyz68');
988 } elsif ($record->field('155')) {
989 $heading.= $field->as_string('abvxyz68');
990 } elsif ($record->field('180')) {
991 $heading.= $field->as_string('vxyz68');
992 } elsif ($record->field('181')) {
993 $heading.= $field->as_string('vxyz68');
994 } elsif ($record->field('182')) {
995 $heading.= $field->as_string('vxyz68');
996 } elsif ($record->field('185')) {
997 $heading.= $field->as_string('vxyz68');
999 $heading.= $field->as_string();
1002 foreach my $field ($record->field('4..')) {
1003 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1005 foreach my $field ($record->field('5..')) {
1006 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1008 $summary .= ": " if $summary;
1009 $summary.=$heading.$seeheading.$altheading;
1015 =head2 BuildUnimarcHierarchies
1019 $text= &BuildUnimarcHierarchies( $authid, $force)
1020 return text containing trees for hierarchies
1021 for them to be stored in auth_header
1024 122,1314,2452;1324,2342,3,2452
1030 sub BuildUnimarcHierarchies{
1031 my $authid = shift @_;
1032 # warn "authid : $authid";
1033 my $force = shift @_;
1035 my $dbh=C4::Context->dbh;
1037 my $data = GetHeaderAuthority($authid);
1038 if ($data->{'authtrees'} and not $force){
1039 return $data->{'authtrees'};
1040 } elsif ($data->{'authtrees'}){
1041 $hierarchies=$data->{'authtrees'};
1043 my $record = GetAuthority($authid);
1045 foreach my $field ($record->field('550')){
1046 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1047 my $parentrecord = GetAuthority($field->subfield('3'));
1048 my $localresult=$hierarchies;
1050 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1053 @trees = split(/;/,$trees);
1055 push @trees, $trees;
1060 @globalresult = (@globalresult,@trees);
1063 $hierarchies=join(";",@globalresult);
1065 #Unless there is no ancestor, I am alone.
1066 $hierarchies="$authid" unless ($hierarchies);
1068 AddAuthorityTrees($authid,$hierarchies);
1069 return $hierarchies;
1072 =head2 BuildUnimarcHierarchy
1076 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1077 return a hashref in order to display hierarchy for record and final Authid $authid
1088 Those two latest ones should disappear soon.
1094 sub BuildUnimarcHierarchy{
1095 my $record = shift @_;
1096 my $class = shift @_;
1097 my $authid_constructed = shift @_;
1098 my $authid=$record->subfield('250','3');
1100 my $parents=""; my $children="";
1101 my (@loopparents,@loopchildren);
1102 foreach my $field ($record->field('550')){
1103 if ($field->subfield('5') && $field->subfield('a')){
1104 if ($field->subfield('5') eq 'h'){
1105 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1106 }elsif ($field->subfield('5') eq 'g'){
1107 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1109 # brothers could get in there with an else
1112 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1113 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1114 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1115 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1116 $cell{"class"}=$class;
1117 $cell{"loopauthid"}=$authid;
1118 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1119 $cell{"value"}=$record->subfield('250',"a");
1123 =head2 GetHeaderAuthority
1127 $ref= &GetHeaderAuthority( $authid)
1128 return a hashref in order auth_header table data
1134 sub GetHeaderAuthority{
1135 my $authid = shift @_;
1136 my $sql= "SELECT * from auth_header WHERE authid = ?";
1137 my $dbh=C4::Context->dbh;
1138 my $rq= $dbh->prepare($sql);
1139 $rq->execute($authid);
1140 my $data= $rq->fetchrow_hashref;
1144 =head2 AddAuthorityTrees
1148 $ref= &AddAuthorityTrees( $authid, $trees)
1149 return success or failure
1155 sub AddAuthorityTrees{
1156 my $authid = shift @_;
1157 my $trees = shift @_;
1158 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1159 my $dbh=C4::Context->dbh;
1160 my $rq= $dbh->prepare($sql);
1161 return $rq->execute($trees,$authid);
1168 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1171 Could add some feature : Migrating from a typecode to an other for instance.
1172 Then we should add some new parameter : bibliotargettag, authtargettag
1179 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1180 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1181 my $dbh=C4::Context->dbh;
1182 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1183 my $authtypecodeto = GetAuthTypeCode($mergeto);
1184 # return if authority does not exist
1185 my @X = $MARCfrom->fields();
1186 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if $#X == -1;
1187 @X = $MARCto->fields();
1188 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if $#X == -1;
1189 # search the tag to report
1190 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1191 $sth->execute($authtypecodefrom);
1192 my ($auth_tag_to_report) = $sth->fetchrow;
1195 @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
1197 @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
1200 # search all biblio tags using this authority.
1201 #Getting marcbiblios impacted by the change.
1202 if (C4::Context->preference('NoZebra')) {
1204 my $dbh=C4::Context->dbh;
1205 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1207 while (my $biblionumbers=$rq->fetchrow){
1208 my @biblionumbers=split /;/,$biblionumbers;
1210 my $biblionumber=$1 if ($_=~/(\d+),.*/);
1211 my $marc=GetMarcBiblio($biblionumber);
1212 push @reccache,$marc;
1217 my $oConnection=C4::Context->Zconn("biblioserver",0);
1219 $query= "an=".$mergefrom;
1220 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1221 my $count=$oResult->size() if ($oResult);
1223 while ( $z<$count ) {
1225 $rec=$oResult->record($z);
1226 my $marcdata = $rec->raw();
1227 push @reccache, $marcdata;
1230 $oConnection->destroy();
1232 #warn scalar(@reccache)." biblios to update";
1233 # Get All candidate Tags for the change
1234 # (This will reduce the search scope in marc records).
1235 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1236 $sth->execute($authtypecodefrom);
1237 my @tags_using_authtype;
1238 while (my ($tagfield) = $sth->fetchrow) {
1239 push @tags_using_authtype,$tagfield ;
1242 if ($authtypecodeto ne $authtypecodefrom){
1243 # If many tags, take the first
1244 $sth->execute($authtypecodeto);
1245 $tag_to=$sth->fetchrow;
1248 # BulkEdit marc records
1249 # May be used as a template for a bulkedit field
1250 foreach my $marcrecord(@reccache){
1252 $marcrecord= MARC::File::USMARC::decode($marcrecord) unless(C4::Context->preference('NoZebra'));
1253 foreach my $tagfield (@tags_using_authtype){
1254 foreach my $field ($marcrecord->field($tagfield)){
1255 my $auth_number=$field->subfield("9");
1256 my $tag=$field->tag();
1257 if ($auth_number==$mergefrom) {
1258 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1259 foreach my $subfield (@record_to) {
1260 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1262 $marcrecord->delete_field($field);
1263 $marcrecord->insert_grouped_field($field_to);
1268 my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,"") ;
1270 &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},GetFrameworkCode($oldbiblio->{'biblionumber'})) ;
1271 $counteditedbiblio++;
1272 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1275 return $counteditedbiblio;
1276 # now, find every other authority linked with this authority
1277 # my $oConnection=C4::Context->Zconn("authorityserver");
1279 # # att 9210 Auth-Internal-authtype
1280 # # att 9220 Auth-Internal-LN
1281 # # ccl.properties to add for authorities
1282 # $query= "= ".$mergefrom;
1283 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1284 # my $count=$oResult->size() if ($oResult);
1287 # while ( $z<$count ) {
1289 # $rec=$oResult->record($z);
1290 # my $marcdata = $rec->raw();
1291 # push @reccache, $marcdata;
1294 # $oResult->destroy();
1295 # foreach my $marc(@reccache){
1298 # $marcrecord = MARC::File::USMARC::decode($marc);
1299 # foreach my $tagfield (@tags_using_authtype){
1300 # $tagfield=substr($tagfield,0,3);
1301 # my @tags = $marcrecord->field($tagfield);
1302 # foreach my $tag (@tags){
1303 # my $tagsubs=$tag->subfield("9");
1304 # #warn "$tagfield:$tagsubs:$mergefrom";
1305 # if ($tagsubs== $mergefrom) {
1306 # $tag->update("9" =>$mergeto);
1307 # foreach my $subfield (@record_to) {
1308 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1309 # $tag->update($subfield->[0] =>$subfield->[1]);
1312 # $marcrecord->delete_field($tag);
1313 # $marcrecord->add_fields($tag);
1316 # }#foreach tagfield
1317 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1319 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1325 =head2 get_auth_type_location
1329 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1333 Get the tag and subfield used to store the heading type
1334 for indexing purposes. The C<$auth_type> parameter is
1335 optional; if it is not supplied, assume ''.
1337 This routine searches the MARC authority framework
1338 for the tag and subfield whose kohafield is
1339 C<auth_header.authtypecode>; if no such field is
1340 defined in the framework, default to the hardcoded value
1341 specific to the MARC format.
1345 sub get_auth_type_location {
1346 my $auth_type_code = @_ ? shift : '';
1348 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1349 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1350 return ($tag, $subfield);
1352 if (C4::Context->preference('marcflavour') eq "MARC21") {
1353 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1355 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1360 END { } # module clean-up code here (global destructor)
1367 Koha Developement team <info@koha.org>
1369 Paul POULAIN paul.poulain@free.fr