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 #use Data::Dumper; map {warn "CALL : ".Data::Dumper::Dumper($_);} @_;
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] =~/mainentry|mainmainentry/) {
122 $query .= qq( AND @$tags[$i] );
126 if (@$operator[$i] eq 'is') {
127 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
128 }elsif (@$operator[$i] eq "="){
129 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
130 }elsif (@$operator[$i] eq "start"){
131 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
133 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
139 # do the query (if we had some search term
142 # warn "QUERY : $query";
143 my $result = C4::Search::NZanalyse($query,'authorityserver');
144 # warn "result : $result";
146 foreach (split /;/,$result) {
147 my ($authid,$title) = split /,/,$_;
148 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
149 # and we don't want to get only 1 result for each of them !!!
150 # hint & speed improvement : we can order without reading the record
151 # so order, and read records only for the requested page !
152 $result{$title.$authid}=$authid;
154 # sort the hash and return the same structure as GetRecords (Zebra querying)
157 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
158 foreach my $key (sort {$b cmp $a} (keys %result)) {
159 push @listresult, $result{$key};
160 # warn "push..."$#finalresult;
163 } else { # sort by mainmainentry ASC
164 foreach my $key (sort (keys %result)) {
165 push @listresult, $result{$key};
166 # warn "push..."$#finalresult;
170 # limit the $results_per_page to result size if it's more
171 $length = $numbers-$offset if $numbers < ($offset+$length);
172 # for the requested page, replace authid by the complete record
173 # speed improvement : avoid reading too much things
175 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
176 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
177 my $separator=C4::Context->preference('authoritysep');
178 my $authrecord =GetAuthority($listresult[$counter]);
179 my $authid=$listresult[$counter];
180 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
181 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
182 my $sth = $dbh->prepare($query_auth_tag);
183 $sth->execute($authtypecode);
184 my $auth_tag_to_report = $sth->fetchrow;
186 $newline{used}=CountUsage($authid);
187 $newline{summary} = $summary;
188 $newline{authid} = $authid;
189 $newline{even} = $counter % 2;
190 push @finalresult, \%newline;
192 return (\@finalresult, $numbers);
199 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
200 # the authtypecode. Then, search on $a of this tag_to_report
201 # also store main entry MARC tag, to extract it at end of search
203 ##first set the authtype search and may be multiple authorities
206 my @auths=split / /,$authtypecode ;
207 foreach my $auth (@auths){
208 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
209 push @authtypecode ,$auth;
213 while ($n>1){$query= "\@or ".$query;$n--;}
218 for(my $i = 0 ; $i <= $#{$value} ; $i++)
221 ##If mainentry search $a tag
222 if (@$tags[$i] eq "mainmainentry") {
223 $attr =" \@attr 1=Heading-Main ";
224 }elsif (@$tags[$i] eq "mainentry") {
225 $attr =" \@attr 1=Heading ";
227 $attr =" \@attr 1=Any ";
229 if (@$operator[$i] eq 'is') {
230 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
231 }elsif (@$operator[$i] eq "="){
232 $attr.=" \@attr 4=107 "; #Number Exact match
233 }elsif (@$operator[$i] eq "start"){
234 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
236 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
238 $attr =$attr."\"".@$value[$i]."\"";
239 $q2 =($q2 ne "" ?$and.$q2.$attr:$attr);
242 ##Add how many queries generated
243 if ($query=~/\S+/ && $q2 ne ""){
244 $query= $and.$query.$q2;
250 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
251 my $orderstring= ($sortby eq "HeadingAsc"?
252 '@attr 7=1 @attr 1=Heading 0'
254 $sortby eq "HeadingDsc"?
255 '@attr 7=2 @attr 1=Heading 0'
258 my $allrecords=" \@attr 1=_ALLRECORDS \@attr 2=103 '' ";
259 $query=($q2?"\@or $orderstring $query":"\@or $orderstring ".($query?"\@and $allrecords $query":$allrecords) );
261 $offset=0 unless $offset;
262 my $counter = $offset;
263 $length=10 unless $length;
266 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
267 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
269 $oAResult= $oAuth[0]->search($Anewq) ;
270 while (($i = ZOOM::event(\@oAuth)) != 0) {
271 my $ev = $oAuth[$i-1]->last_event();
272 last if $ev == ZOOM::Event::ZEND;
274 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
276 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
281 $nbresults=$oAResult->size();
282 my $nremains=$nbresults;
284 my @finalresult = ();
288 ##Find authid and linkid fields
289 ##we may be searching multiple authoritytypes.
290 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
291 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
292 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
293 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
295 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
296 my $rec=$oAResult->record($counter);
297 my $marcdata=$rec->raw();
299 my $separator=C4::Context->preference('authoritysep');
300 $authrecord = MARC::File::USMARC::decode($marcdata);
301 my $authid=$authrecord->field('001')->data();
302 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
303 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
304 my $sth = $dbh->prepare($query_auth_tag);
305 $sth->execute($authtypecode);
306 my $auth_tag_to_report = $sth->fetchrow;
308 my $mainentry = $authrecord->field($auth_tag_to_report);
310 foreach ($mainentry->subfields()) {
311 $reported_tag .='$'.$_->[0].$_->[1];
315 $newline{summary} = $summary;
316 $newline{authid} = $authid;
317 $newline{even} = $counter % 2;
318 $newline{reported_tag} = $reported_tag;
320 push @finalresult, \%newline;
323 for (my $z=0; $z<@finalresult; $z++){
324 my $count=CountUsage($finalresult[$z]{authid});
325 $finalresult[$z]{used}=$count;
330 # $oAResult->destroy();
331 # $oAuth[0]->destroy();
333 return (\@finalresult, $nbresults);
341 $count= &CountUsage($authid)
342 counts Usage of Authid in bibliorecords.
350 if (C4::Context->preference('NoZebra')) {
351 # Read the index Koha-Auth-Number for this authid and count the lines
352 my $result = C4::Search::NZanalyse("an=$authid");
353 my @tab = split /;/,$result;
357 my $oConnection=C4::Context->Zconn("biblioserver",1);
359 $query= "an=".$authid;
360 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
362 while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
363 my $ev = $oConnection->last_event();
364 if ($ev == ZOOM::Event::ZEND) {
365 $result = $oResult->size();
372 =head2 CountUsageChildren
376 $count= &CountUsageChildren($authid)
377 counts Usage of narrower terms of Authid in bibliorecords.
383 sub CountUsageChildren {
387 =head2 GetAuthTypeCode
391 $authtypecode= &GetAuthTypeCode($authid)
392 returns authtypecode of an authid
398 sub GetAuthTypeCode {
399 #AUTHfind_authtypecode
401 my $dbh=C4::Context->dbh;
402 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
403 $sth->execute($authid);
404 my $authtypecode = $sth->fetchrow;
405 return $authtypecode;
412 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
413 returns a ref to hashref of authorities tag and subfield structure.
416 $tagslabel->{$tag}->{$subfield}->{'attribute'}
417 where attribute takes values in :
436 my ($forlibrarian,$authtypecode)= @_;
437 my $dbh=C4::Context->dbh;
438 $authtypecode="" unless $authtypecode;
440 my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
443 # check that authority exists
444 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
445 $sth->execute($authtypecode);
446 my ($total) = $sth->fetchrow;
447 $authtypecode="" unless ($total >0);
449 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
450 FROM auth_tag_structure
455 $sth->execute($authtypecode);
456 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
458 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
459 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
460 $res->{$tag}->{tab} = " "; # XXX
461 $res->{$tag}->{mandatory} = $mandatory;
462 $res->{$tag}->{repeatable} = $repeatable;
465 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
466 FROM auth_subfield_structure
468 ORDER BY tagfield,tagsubfield"
470 $sth->execute($authtypecode);
473 my $authorised_value;
482 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
483 $mandatory, $repeatable, $authorised_value, $authtypecode,
484 $value_builder, $kohafield, $seealso, $hidden,
489 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
490 $res->{$tag}->{$subfield}->{tab} = $tab;
491 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
492 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
493 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
494 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
495 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
496 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
497 $res->{$tag}->{$subfield}->{seealso} = $seealso;
498 $res->{$tag}->{$subfield}->{hidden} = $hidden;
499 $res->{$tag}->{$subfield}->{isurl} = $isurl;
500 $res->{$tag}->{$subfield}->{link} = $link;
509 $authid= &AddAuthority($record, $authid,$authtypecode)
510 returns authid of the newly created authority
512 Either Create Or Modify existing authority.
519 # pass the MARC::Record to this function, and it will create the records in the authority table
520 my ($record,$authid,$authtypecode) = @_;
521 my $dbh=C4::Context->dbh;
522 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
524 # if authid empty => true add, find a new authid number
525 my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
526 $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
528 if ($format eq "MARC21") {
529 if (!$record->leader) {
530 $record->leader($leader);
532 if (!$record->field('003')) {
533 $record->insert_fields_ordered(
534 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
537 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
538 if (!$record->field('005')) {
539 $record->insert_fields_ordered(
540 MARC::Field->new('005',$time.".0")
543 my $date=POSIX::strftime("%y%m%d",localtime);
544 if (!$record->field('008')) {
545 $record->insert_fields_ordered(
546 MARC::Field->new('008',$date."|||a|||||| | ||| d")
549 if (!$record->field('040')) {
550 $record->insert_fields_ordered(
551 MARC::Field->new('040','','',
552 'a' => C4::Context->preference('MARCOrgCode'),
553 'c' => C4::Context->preference('MARCOrgCode')
559 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
560 $record->leader(" nx j22 ");
561 my $date=POSIX::strftime("%Y%m%d",localtime);
562 if ($record->field('100')){
563 $record->field('100')->update('a'=>$date."afrey50 ba0");
565 $record->append_fields(
566 MARC::Field->new('100',' ',' '
567 ,'a'=>$date."afrey50 ba0")
571 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
572 if (!$authid and $format eq "MARC21") {
573 # only need to do this fix when modifying an existing authority
574 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
576 if (my $field=$record->field($auth_type_tag)){
577 $field->update($auth_type_subfield=>$authtypecode);
580 $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));
596 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
597 # warn "auth_exists = $auth_exists";
600 $oldRecord=GetAuthority($authid);
601 $record->add_fields('001',$authid) unless ($record->field('001'));
602 # warn "\n\n\n enregistrement".$record->as_formatted;
603 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
604 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
608 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
609 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
612 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
621 $authid= &DelAuthority($authid)
631 my $dbh=C4::Context->dbh;
633 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
634 $dbh->do("delete from auth_header where authid=$authid") ;
639 my ($authid,$record,$authtypecode,$merge)=@_;
640 my $dbh=C4::Context->dbh;
641 #Now rewrite the $record to table with an add
642 my $oldrecord=GetAuthority($authid);
643 $authid=AddAuthority($record,$authid,$authtypecode);
645 ### 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
646 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
647 ### the $merge flag is now depreceated and will be removed at code cleaning
648 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
649 &merge($authid,$oldrecord,$authid,$record);
651 # save the file in tmp/modified_authorities
652 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
653 unless (opendir(DIR,"$cgidir")) {
654 $cgidir = C4::Context->intranetdir."/";
658 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
659 open AUTH, "> $filename";
666 =head2 GetAuthorityXML
670 $marcxml= &GetAuthorityXML( $authid)
671 returns xml form of record $authid
677 sub GetAuthorityXML {
678 # Returns MARC::XML of the authority passed in parameter.
680 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
681 my $dbh=C4::Context->dbh;
682 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
683 $sth->execute($authid);
684 my ($marcxml)=$sth->fetchrow;
688 # for MARC21, call GetAuthority instead of
689 # getting the XML directly since we may
690 # need to fix up the location of the authority
691 # code -- note that this is reasonably safe
692 # because GetAuthorityXML is used only by the
693 # indexing processes like zebraqueue_start.pl
694 my $record = GetAuthority($authid);
695 return $record->as_xml_record('MARC21');
703 $record= &GetAuthority( $authid)
704 Returns MARC::Record of the authority passed in parameter.
712 my $dbh=C4::Context->dbh;
713 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
714 $sth->execute($authid);
715 my ($authtypecode, $marcxml) = $sth->fetchrow;
716 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
717 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
718 return undef if ($@);
719 $record->encoding('UTF-8');
720 if (C4::Context->preference("marcflavour") eq "MARC21") {
721 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
722 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
731 $result = &GetAuthType($authtypecode)
735 If the authority type specified by C<$authtypecode> exists,
736 returns a hashref of the type's fields. If the type
737 does not exist, returns undef.
742 my ($authtypecode) = @_;
743 my $dbh=C4::Context->dbh;
745 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
746 # type (FIXME but why?)
747 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
748 $sth->execute($authtypecode);
749 if (my $res = $sth->fetchrow_hashref) {
758 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
759 my $dbh=C4::Context->dbh;
761 my $record = MARC::Record->new();
762 #---- TODO : the leader is missing
764 # my %subfieldlist=();
765 my $prevvalue; # if tag <10
766 my $field; # if tag >=10
767 for (my $i=0; $i< @$rtags; $i++) {
768 # rebuild MARC::Record
769 if (@$rtags[$i] ne $prevtag) {
772 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
776 $record->add_fields($field);
779 $indicators{@$rtags[$i]}.=' ';
780 if (@$rtags[$i] <10) {
781 $prevvalue= @$rvalues[$i];
785 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
787 $prevtag = @$rtags[$i];
789 if (@$rtags[$i] <10) {
790 $prevvalue=@$rvalues[$i];
792 if (length(@$rvalues[$i])>0) {
793 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
796 $prevtag= @$rtags[$i];
799 # the last has not been included inside the loop... do it now !
800 $record->add_fields($field) if $field;
804 =head2 FindDuplicateAuthority
808 $record= &FindDuplicateAuthority( $record, $authtypecode)
809 return $authid,Summary if duplicate is found.
811 Comments : an improvement would be to return All the records that match.
817 sub FindDuplicateAuthority {
819 my ($record,$authtypecode)=@_;
820 # warn "IN for ".$record->as_formatted;
821 my $dbh = C4::Context->dbh;
822 # warn "".$record->as_formatted;
823 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
824 $sth->execute($authtypecode);
825 my ($auth_tag_to_report) = $sth->fetchrow;
827 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
828 # build a request for SearchAuthorities
829 my $query='at='.$authtypecode.' ';
830 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
831 if ($record->field($auth_tag_to_report)) {
832 foreach ($record->field($auth_tag_to_report)->subfields()) {
833 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
836 my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
837 # there is at least 1 result => return the 1st one
839 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
840 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
842 # no result, returns nothing
850 $text= &BuildSummary( $record, $authid, $authtypecode)
851 return HTML encoded Summary
853 Comment : authtypecode can be infered from both record and authid.
854 Moreover, authid can also be inferred from $record.
855 Would it be interesting to delete those things.
862 ## give this a Marc record to return summary
863 my ($record,$authid,$authtypecode)=@_;
864 my $dbh=C4::Context->dbh;
866 # handle $authtypecode is NULL or eq ""
868 my $authref = GetAuthType($authtypecode);
869 $summary = $authref->{summary};
871 # FIXME: should use I18N.pm
873 $language{'fre'}="Français";
874 $language{'eng'}="Anglais";
875 $language{'ger'}="Allemand";
876 $language{'ita'}="Italien";
877 $language{'spa'}="Espagnol";
879 $thesaurus{'1'}="Peuples";
880 $thesaurus{'2'}="Anthroponymes";
881 $thesaurus{'3'}="Oeuvres";
882 $thesaurus{'4'}="Chronologie";
883 $thesaurus{'5'}="Lieux";
884 $thesaurus{'6'}="Sujets";
886 my @fields = $record->fields();
888 # if the library has a summary defined, use it. Otherwise, build a standard one
889 # FIXME - it appears that the summary field in the authority frameworks
890 # can work as a display template. However, this doesn't
891 # suit the MARC21 version, so for now the "templating"
892 # feature will be enabled only for UNIMARC for backwards
894 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
895 my @fields = $record->fields();
896 # $reported_tag = '$9'.$result[$counter];
897 foreach my $field (@fields) {
898 my $tag = $field->tag();
899 my $tagvalue = $field->as_string();
900 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
903 $reported_tag.='$3'.$field->data();
906 my @subf = $field->subfields;
907 for my $i (0..$#subf) {
908 my $subfieldcode = $subf[$i][0];
909 my $subfieldvalue = $subf[$i][1];
910 my $tagsubf = $tag.$subfieldcode;
911 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
915 $summary =~ s/\[(.*?)]//g;
916 $summary =~ s/\n/<br>/g;
927 my @fields = $record->fields();
928 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
929 # construct UNIMARC summary, that is quite different from MARC21 one
931 foreach my $field ($record->field('2..')) {
932 $heading.= $field->subfield('a');
933 $authid=$field->subfield('3');
936 foreach my $field ($record->field('3..')) {
937 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
939 foreach my $field ($record->field('4..')) {
940 if ($field->subfield('2')) {
941 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
942 $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
946 foreach my $field ($record->field('5..')) {
948 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
949 $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
950 } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
951 $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
952 } elsif ($field->subfield('a')) {
953 $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
957 foreach my $field ($record->field('7..')) {
958 my $lang = substr($field->subfield('8'),3,3);
959 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
961 $broaderterms =~s/-- \n$//;
962 $narrowerterms =~s/-- \n$//;
963 $seealso =~s/-- \n$//;
965 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
966 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
967 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
968 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
969 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
970 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
972 # construct MARC21 summary
973 # FIXME - looping over 1XX is questionable
974 # since MARC21 authority should have only one 1XX
975 foreach my $field ($record->field('1..')) {
976 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
977 # in MARC21 -- purely local tags really ought to be
979 if ($record->field('100')) {
980 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
981 } elsif ($record->field('110')) {
982 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
983 } elsif ($record->field('111')) {
984 $heading.= $field->as_string('acdefghklnpqstvxyz68');
985 } elsif ($record->field('130')) {
986 $heading.= $field->as_string('adfghklmnoprstvxyz68');
987 } elsif ($record->field('148')) {
988 $heading.= $field->as_string('abvxyz68');
989 } elsif ($record->field('150')) {
990 # $heading.= $field->as_string('abvxyz68');
991 $heading.= $field->as_formatted();
992 my $tag=$field->tag();
993 $heading=~s /^$tag//g;
994 $heading =~s /\_/\$/g;
995 } elsif ($record->field('151')) {
996 $heading.= $field->as_string('avxyz68');
997 } elsif ($record->field('155')) {
998 $heading.= $field->as_string('abvxyz68');
999 } elsif ($record->field('180')) {
1000 $heading.= $field->as_string('vxyz68');
1001 } elsif ($record->field('181')) {
1002 $heading.= $field->as_string('vxyz68');
1003 } elsif ($record->field('182')) {
1004 $heading.= $field->as_string('vxyz68');
1005 } elsif ($record->field('185')) {
1006 $heading.= $field->as_string('vxyz68');
1008 $heading.= $field->as_string();
1011 foreach my $field ($record->field('4..')) {
1012 $seeheading.= "<br /> <i>used for/see from:</i> ".$field->as_string();
1014 foreach my $field ($record->field('5..')) {
1015 $altheading.= "<br /> <i>see also:</i> ".$field->as_string();
1017 $summary .= ": " if $summary;
1018 $summary.=$heading.$seeheading.$altheading;
1024 =head2 BuildUnimarcHierarchies
1028 $text= &BuildUnimarcHierarchies( $authid, $force)
1029 return text containing trees for hierarchies
1030 for them to be stored in auth_header
1033 122,1314,2452;1324,2342,3,2452
1039 sub BuildUnimarcHierarchies{
1040 my $authid = shift @_;
1041 # warn "authid : $authid";
1042 my $force = shift @_;
1044 my $dbh=C4::Context->dbh;
1046 my $data = GetHeaderAuthority($authid);
1047 if ($data->{'authtrees'} and not $force){
1048 return $data->{'authtrees'};
1049 } elsif ($data->{'authtrees'}){
1050 $hierarchies=$data->{'authtrees'};
1052 my $record = GetAuthority($authid);
1054 foreach my $field ($record->field('550')){
1055 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1056 my $parentrecord = GetAuthority($field->subfield('3'));
1057 my $localresult=$hierarchies;
1059 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1062 @trees = split(/;/,$trees);
1064 push @trees, $trees;
1069 @globalresult = (@globalresult,@trees);
1072 $hierarchies=join(";",@globalresult);
1074 #Unless there is no ancestor, I am alone.
1075 $hierarchies="$authid" unless ($hierarchies);
1077 AddAuthorityTrees($authid,$hierarchies);
1078 return $hierarchies;
1081 =head2 BuildUnimarcHierarchy
1085 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1086 return a hashref in order to display hierarchy for record and final Authid $authid
1097 Those two latest ones should disappear soon.
1103 sub BuildUnimarcHierarchy{
1104 my $record = shift @_;
1105 my $class = shift @_;
1106 my $authid_constructed = shift @_;
1107 my $authid=$record->subfield('250','3');
1109 my $parents=""; my $children="";
1110 my (@loopparents,@loopchildren);
1111 foreach my $field ($record->field('550')){
1112 if ($field->subfield('5') && $field->subfield('a')){
1113 if ($field->subfield('5') eq 'h'){
1114 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1115 }elsif ($field->subfield('5') eq 'g'){
1116 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1118 # brothers could get in there with an else
1121 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1122 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1123 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1124 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1125 $cell{"class"}=$class;
1126 $cell{"loopauthid"}=$authid;
1127 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1128 $cell{"value"}=$record->subfield('250',"a");
1132 =head2 GetHeaderAuthority
1136 $ref= &GetHeaderAuthority( $authid)
1137 return a hashref in order auth_header table data
1143 sub GetHeaderAuthority{
1144 my $authid = shift @_;
1145 my $sql= "SELECT * from auth_header WHERE authid = ?";
1146 my $dbh=C4::Context->dbh;
1147 my $rq= $dbh->prepare($sql);
1148 $rq->execute($authid);
1149 my $data= $rq->fetchrow_hashref;
1153 =head2 AddAuthorityTrees
1157 $ref= &AddAuthorityTrees( $authid, $trees)
1158 return success or failure
1164 sub AddAuthorityTrees{
1165 my $authid = shift @_;
1166 my $trees = shift @_;
1167 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1168 my $dbh=C4::Context->dbh;
1169 my $rq= $dbh->prepare($sql);
1170 return $rq->execute($trees,$authid);
1177 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1180 Could add some feature : Migrating from a typecode to an other for instance.
1181 Then we should add some new parameter : bibliotargettag, authtargettag
1188 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1189 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1190 my $dbh=C4::Context->dbh;
1191 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1192 my $authtypecodeto = GetAuthTypeCode($mergeto);
1193 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1194 # return if authority does not exist
1195 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1196 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1197 # search the tag to report
1198 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1199 $sth->execute($authtypecodefrom);
1200 my ($auth_tag_to_report_from) = $sth->fetchrow;
1201 $sth->execute($authtypecodeto);
1202 my ($auth_tag_to_report_to) = $sth->fetchrow;
1205 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1207 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1210 # search all biblio tags using this authority.
1211 #Getting marcbiblios impacted by the change.
1212 if (C4::Context->preference('NoZebra')) {
1214 my $dbh=C4::Context->dbh;
1215 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1217 while (my $biblionumbers=$rq->fetchrow){
1218 my @biblionumbers=split /;/,$biblionumbers;
1219 foreach (@biblionumbers) {
1220 if ($_=~/(\d+),.*/) {
1221 my $marc=GetMarcBiblio($1);
1222 push @reccache,$marc;
1228 my $oConnection=C4::Context->Zconn("biblioserver",0);
1229 $oConnection->option("preferredRecordSyntax"=>"XML");
1231 $query= "an=".$mergefrom;
1232 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1235 $count=$oResult->size();
1238 while ( $z<$count ) {
1240 $rec=$oResult->record($z);
1241 my $marcdata = $rec->raw();
1242 push @reccache, $marcdata;
1245 $oConnection->destroy();
1247 #warn scalar(@reccache)." biblios to update";
1248 # Get All candidate Tags for the change
1249 # (This will reduce the search scope in marc records).
1250 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1251 $sth->execute($authtypecodefrom);
1252 my @tags_using_authtype;
1253 while (my ($tagfield) = $sth->fetchrow) {
1254 push @tags_using_authtype,$tagfield ;
1257 if ($authtypecodeto ne $authtypecodefrom){
1258 # If many tags, take the first
1259 $sth->execute($authtypecodeto);
1260 $tag_to=$sth->fetchrow;
1263 # BulkEdit marc records
1264 # May be used as a template for a bulkedit field
1265 foreach my $marcrecord(@reccache){
1267 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1268 foreach my $tagfield (@tags_using_authtype){
1269 # warn "tagfield : $tagfield ";
1270 foreach my $field ($marcrecord->field($tagfield)){
1271 my $auth_number=$field->subfield("9");
1272 my $tag=$field->tag();
1273 if ($auth_number==$mergefrom) {
1274 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1275 foreach my $subfield (@record_to) {
1276 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1278 $marcrecord->delete_field($field);
1279 $marcrecord->insert_grouped_field($field_to);
1284 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1287 $biblionumber=$marcrecord->field($bibliotag)->data;
1290 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1292 unless ($biblionumber){
1293 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1297 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1298 $counteditedbiblio++;
1299 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1302 return $counteditedbiblio;
1303 # now, find every other authority linked with this authority
1304 # now, find every other authority linked with this authority
1305 # my $oConnection=C4::Context->Zconn("authorityserver");
1307 # # att 9210 Auth-Internal-authtype
1308 # # att 9220 Auth-Internal-LN
1309 # # ccl.properties to add for authorities
1310 # $query= "= ".$mergefrom;
1311 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1312 # my $count=$oResult->size() if ($oResult);
1315 # while ( $z<$count ) {
1317 # $rec=$oResult->record($z);
1318 # my $marcdata = $rec->raw();
1319 # push @reccache, $marcdata;
1322 # $oResult->destroy();
1323 # foreach my $marc(@reccache){
1326 # $marcrecord = MARC::File::USMARC::decode($marc);
1327 # foreach my $tagfield (@tags_using_authtype){
1328 # $tagfield=substr($tagfield,0,3);
1329 # my @tags = $marcrecord->field($tagfield);
1330 # foreach my $tag (@tags){
1331 # my $tagsubs=$tag->subfield("9");
1332 # #warn "$tagfield:$tagsubs:$mergefrom";
1333 # if ($tagsubs== $mergefrom) {
1334 # $tag->update("9" =>$mergeto);
1335 # foreach my $subfield (@record_to) {
1336 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1337 # $tag->update($subfield->[0] =>$subfield->[1]);
1340 # $marcrecord->delete_field($tag);
1341 # $marcrecord->add_fields($tag);
1344 # }#foreach tagfield
1345 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1347 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1353 =head2 get_auth_type_location
1357 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1361 Get the tag and subfield used to store the heading type
1362 for indexing purposes. The C<$auth_type> parameter is
1363 optional; if it is not supplied, assume ''.
1365 This routine searches the MARC authority framework
1366 for the tag and subfield whose kohafield is
1367 C<auth_header.authtypecode>; if no such field is
1368 defined in the framework, default to the hardcoded value
1369 specific to the MARC format.
1373 sub get_auth_type_location {
1374 my $auth_type_code = @_ ? shift : '';
1376 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1377 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1378 return ($tag, $subfield);
1380 if (C4::Context->preference('marcflavour') eq "MARC21") {
1381 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1383 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1388 END { } # module clean-up code here (global destructor)
1395 Koha Developement team <info@koha.org>
1397 Paul POULAIN paul.poulain@free.fr