Bug 7936: Tools Help for 3.8
[koha.git] / C4 / AuthoritiesMarc.pm
blob703ea75a4fa4165a904d679cb762db3b351df654
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
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 use strict;
20 use warnings;
21 use C4::Context;
22 use MARC::Record;
23 use C4::Biblio;
24 use C4::Search;
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
27 use C4::Charset;
28 use C4::Log;
30 use vars qw($VERSION @ISA @EXPORT);
32 BEGIN {
33 # set the version for version checking
34 $VERSION = 3.01;
36 require Exporter;
37 @ISA = qw(Exporter);
38 @EXPORT = qw(
39 &GetTagsLabels
40 &GetAuthType
41 &GetAuthTypeCode
42 &GetAuthMARCFromKohaField
44 &AddAuthority
45 &ModAuthority
46 &DelAuthority
47 &GetAuthority
48 &GetAuthorityXML
50 &CountUsage
51 &CountUsageChildren
52 &SearchAuthorities
54 &BuildSummary
55 &BuildUnimarcHierarchies
56 &BuildUnimarcHierarchy
58 &merge
59 &FindDuplicateAuthority
61 &GuessAuthTypeCode
62 &GuessAuthId
67 =head1 NAME
69 C4::AuthoritiesMarc
71 =head2 GetAuthMARCFromKohaField
73 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
75 returns tag and subfield linked to kohafield
77 Comment :
78 Suppose Kohafield is only linked to ONE subfield
80 =cut
82 sub GetAuthMARCFromKohaField {
83 #AUTHfind_marc_from_kohafield
84 my ( $kohafield,$authtypecode ) = @_;
85 my $dbh=C4::Context->dbh;
86 return 0, 0 unless $kohafield;
87 $authtypecode="" unless $authtypecode;
88 my $marcfromkohafield;
89 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
90 $sth->execute($kohafield,$authtypecode);
91 my ($tagfield,$tagsubfield) = $sth->fetchrow;
93 return ($tagfield,$tagsubfield);
96 =head2 SearchAuthorities
98 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
99 $excluding, $operator, $value, $offset,$length,$authtypecode,
100 $sortby[, $skipmetadata])
102 returns ref to array result and count of results returned
104 =cut
106 sub SearchAuthorities {
107 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
108 # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
109 my $dbh=C4::Context->dbh;
110 if (C4::Context->preference('NoZebra')) {
113 # build the query
115 my $query;
116 my @auths=split / /,$authtypecode ;
117 foreach my $auth (@auths){
118 $query .="AND auth_type= $auth ";
120 $query =~ s/^AND //;
121 my $dosearch;
122 for(my $i = 0 ; $i <= $#{$value} ; $i++)
124 if (@$value[$i]){
125 if (@$tags[$i] =~/mainentry|mainmainentry/) {
126 $query .= qq( AND @$tags[$i] );
127 } else {
128 $query .=" AND ";
130 if (@$operator[$i] eq 'is') {
131 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
132 }elsif (@$operator[$i] eq "="){
133 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
134 }elsif (@$operator[$i] eq "start"){
135 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
136 } else {
137 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
139 $dosearch=1;
140 }#if value
143 # do the query (if we had some search term
145 if ($dosearch) {
146 # warn "QUERY : $query";
147 my $result = C4::Search::NZanalyse($query,'authorityserver');
148 # warn "result : $result";
149 my %result;
150 foreach (split /;/,$result) {
151 my ($authid,$title) = split /,/,$_;
152 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
153 # and we don't want to get only 1 result for each of them !!!
154 # hint & speed improvement : we can order without reading the record
155 # so order, and read records only for the requested page !
156 $result{$title.$authid}=$authid;
158 # sort the hash and return the same structure as GetRecords (Zebra querying)
159 my @listresult = ();
160 my $numbers=0;
161 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
162 foreach my $key (sort {$b cmp $a} (keys %result)) {
163 push @listresult, $result{$key};
164 # warn "push..."$#finalresult;
165 $numbers++;
167 } else { # sort by mainmainentry ASC
168 foreach my $key (sort (keys %result)) {
169 push @listresult, $result{$key};
170 # warn "push..."$#finalresult;
171 $numbers++;
174 # limit the $results_per_page to result size if it's more
175 $length = $numbers-$offset if $numbers < ($offset+$length);
176 # for the requested page, replace authid by the complete record
177 # speed improvement : avoid reading too much things
178 my @finalresult;
179 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
180 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
181 my $separator=C4::Context->preference('authoritysep');
182 my $authrecord =GetAuthority($listresult[$counter]);
183 my $authid=$listresult[$counter];
184 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
185 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
186 my $sth = $dbh->prepare($query_auth_tag);
187 $sth->execute($authtypecode);
188 my $auth_tag_to_report = $sth->fetchrow;
189 my %newline;
190 $newline{used}=CountUsage($authid);
191 $newline{summary} = $summary;
192 $newline{authid} = $authid;
193 $newline{even} = $counter % 2;
194 push @finalresult, \%newline;
196 return (\@finalresult, $numbers);
197 } else {
198 return;
200 } else {
201 my $query;
202 my $attr;
203 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
204 # the authtypecode. Then, search on $a of this tag_to_report
205 # also store main entry MARC tag, to extract it at end of search
206 my $mainentrytag;
207 ##first set the authtype search and may be multiple authorities
208 my $n=0;
209 my @authtypecode;
210 my @auths=split / /,$authtypecode ;
211 foreach my $auth (@auths){
212 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
213 push @authtypecode ,$auth;
214 $n++;
216 if ($n>1){
217 while ($n>1){$query= "\@or ".$query;$n--;}
220 my $dosearch;
221 my $and=" \@and " ;
222 my $q2;
223 my $attr_cnt = 0;
224 for(my $i = 0 ; $i <= $#{$value} ; $i++)
226 if (@$value[$i]){
227 if ( @$tags[$i] eq "mainmainentry" ) {
228 $attr = " \@attr 1=Heading-Main ";
230 elsif ( @$tags[$i] eq "mainentry" ) {
231 $attr = " \@attr 1=Heading ";
233 elsif ( @$tags[$i] eq "any" ) {
234 $attr = " \@attr 1=Any ";
236 elsif ( @$tags[$i] eq "match" ) {
237 $attr = " \@attr 1=Match ";
239 elsif ( @$tags[$i] eq "match-heading" ) {
240 $attr = " \@attr 1=Match-heading ";
242 elsif ( @$tags[$i] eq "see-from" ) {
243 $attr = " \@attr 1=Match-heading-see-from ";
245 elsif ( @$tags[$i] eq "thesaurus" ) {
246 $attr = " \@attr 1=Subject-heading-thesaurus ";
248 if ( @$operator[$i] eq 'is' ) {
249 $attr .= " \@attr 4=1 \@attr 5=100 "
250 ; ##Phrase, No truncation,all of subfield field must match
252 elsif ( @$operator[$i] eq "=" ) {
253 $attr .= " \@attr 4=107 "; #Number Exact match
255 elsif ( @$operator[$i] eq "start" ) {
256 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
257 ; #Firstinfield Phrase, Right truncated
259 elsif ( @$operator[$i] eq "exact" ) {
260 $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 "
261 ; ##Phrase, No truncation,all of subfield field must match
263 else {
264 $attr .= " \@attr 5=1 \@attr 4=6 "
265 ; ## Word list, right truncated, anywhere
267 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
268 $attr =$attr."\"".@$value[$i]."\"";
269 $q2 .=$attr;
270 $dosearch=1;
271 ++$attr_cnt;
272 }#if value
274 ##Add how many queries generated
275 if (defined $query && $query=~/\S+/){
276 $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
277 } else {
278 $query= $q2;
280 ## Adding order
281 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
282 my $orderstring;
283 if ($sortby eq 'HeadingAsc') {
284 $orderstring = '@attr 7=1 @attr 1=Heading 0';
285 } elsif ($sortby eq 'HeadingDsc') {
286 $orderstring = '@attr 7=2 @attr 1=Heading 0';
287 } elsif ($sortby eq 'AuthidAsc') {
288 $orderstring = '@attr 7=1 @attr 1=Local-Number 0';
289 } elsif ($sortby eq 'AuthidDsc') {
290 $orderstring = '@attr 7=2 @attr 1=Local-Number 0';
292 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
293 $query="\@or $orderstring $query" if $orderstring;
295 $offset=0 unless $offset;
296 my $counter = $offset;
297 $length=10 unless $length;
298 my @oAuth;
299 my $i;
300 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
301 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
302 my $oAResult;
303 $oAResult= $oAuth[0]->search($Anewq) ;
304 while (($i = ZOOM::event(\@oAuth)) != 0) {
305 my $ev = $oAuth[$i-1]->last_event();
306 last if $ev == ZOOM::Event::ZEND;
308 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
309 if ($error) {
310 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
311 goto NOLUCK;
314 my $nbresults;
315 $nbresults=$oAResult->size();
316 my $nremains=$nbresults;
317 my @result = ();
318 my @finalresult = ();
320 if ($nbresults>0){
322 ##Find authid and linkid fields
323 ##we may be searching multiple authoritytypes.
324 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
325 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
326 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
327 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
329 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
330 my $rec=$oAResult->record($counter);
331 my $marcdata=$rec->raw();
332 my $authrecord;
333 my $separator=C4::Context->preference('authoritysep');
334 $authrecord = MARC::File::USMARC::decode($marcdata);
335 my $authid=$authrecord->field('001')->data();
336 my %newline;
337 $newline{authid} = $authid;
338 if ( !$skipmetadata ) {
339 my $summary =
340 BuildSummary( $authrecord, $authid, $authtypecode );
341 my $query_auth_tag =
342 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
343 my $sth = $dbh->prepare($query_auth_tag);
344 $sth->execute($authtypecode);
345 my $auth_tag_to_report = $sth->fetchrow;
346 my $reported_tag;
347 my $mainentry = $authrecord->field($auth_tag_to_report);
348 if ($mainentry) {
350 foreach ( $mainentry->subfields() ) {
351 $reported_tag .= '$' . $_->[0] . $_->[1];
354 $newline{summary} = $summary;
355 $newline{even} = $counter % 2;
356 $newline{reported_tag} = $reported_tag;
358 $counter++;
359 push @finalresult, \%newline;
360 }## while counter
362 if (! $skipmetadata) {
363 for (my $z=0; $z<@finalresult; $z++){
364 my $count=CountUsage($finalresult[$z]{authid});
365 $finalresult[$z]{used}=$count;
366 }# all $z's
369 }## if nbresult
370 NOLUCK:
371 $oAResult->destroy();
372 # $oAuth[0]->destroy();
374 return (\@finalresult, $nbresults);
378 =head2 CountUsage
380 $count= &CountUsage($authid)
382 counts Usage of Authid in bibliorecords.
384 =cut
386 sub CountUsage {
387 my ($authid) = @_;
388 if (C4::Context->preference('NoZebra')) {
389 # Read the index Koha-Auth-Number for this authid and count the lines
390 my $result = C4::Search::NZanalyse("an=$authid");
391 my @tab = split /;/,$result;
392 return scalar @tab;
393 } else {
394 ### ZOOM search here
395 my $query;
396 $query= "an=".$authid;
397 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
398 if ($err) {
399 warn "Error: $err from search $query";
400 $result = 0;
403 return $result;
407 =head2 CountUsageChildren
409 $count= &CountUsageChildren($authid)
411 counts Usage of narrower terms of Authid in bibliorecords.
413 =cut
415 sub CountUsageChildren {
416 my ($authid) = @_;
419 =head2 GetAuthTypeCode
421 $authtypecode= &GetAuthTypeCode($authid)
423 returns authtypecode of an authid
425 =cut
427 sub GetAuthTypeCode {
428 #AUTHfind_authtypecode
429 my ($authid) = @_;
430 my $dbh=C4::Context->dbh;
431 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
432 $sth->execute($authid);
433 my $authtypecode = $sth->fetchrow;
434 return $authtypecode;
437 =head2 GuessAuthTypeCode
439 my $authtypecode = GuessAuthTypeCode($record);
441 Get the record and tries to guess the adequate authtypecode from its content.
443 =cut
445 sub GuessAuthTypeCode {
446 my ($record) = @_;
447 return unless defined $record;
448 my $heading_fields = {
449 "MARC21"=>{
450 '100'=>{authtypecode=>'PERSO_NAME'},
451 '110'=>{authtypecode=>'CORPO_NAME'},
452 '111'=>{authtypecode=>'MEETI_NAME'},
453 '130'=>{authtypecode=>'UNIF_TITLE'},
454 '148'=>{authtypecode=>'CHRON_TERM'},
455 '150'=>{authtypecode=>'TOPIC_TERM'},
456 '151'=>{authtypecode=>'GEOGR_NAME'},
457 '155'=>{authtypecode=>'GENRE/FORM'},
458 '180'=>{authtypecode=>'GEN_SUBDIV'},
459 '181'=>{authtypecode=>'GEO_SUBDIV'},
460 '182'=>{authtypecode=>'CHRON_SUBD'},
461 '185'=>{authtypecode=>'FORM_SUBD'},
463 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
464 # 604 with embedded 700, 701, 702
465 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
466 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
467 #216 Trademark 716 [Reserved for future use]
468 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
469 #230 Title 500 4-- with embedded 500 605
470 #240 Name and title (embedded 200, 210, 215, or 220 and 230) 4-- with embedded 7-- and 500 7-- 604 with embedded 7-- and 500 500
471 #245 Name and collective title (embedded 200, 210, 215, or 220 and 235) 4-- with embedded 7-- and 501 604 with embedded 7-- and 501 7-- 501
472 #250 Topical subject 606
473 #260 Place access 620
474 #280 Form, genre or physical characteristics 608
477 # Could also be represented with :
478 #leader position 9
479 #a = personal name entry
480 #b = corporate name entry
481 #c = territorial or geographical name
482 #d = trademark
483 #e = family name
484 #f = uniform title
485 #g = collective uniform title
486 #h = name/title
487 #i = name/collective uniform title
488 #j = topical subject
489 #k = place access
490 #l = form, genre or physical characteristics
491 "UNIMARC"=>{
492 '200'=>{authtypecode=>'NP'},
493 '210'=>{authtypecode=>'CO'},
494 '215'=>{authtypecode=>'SNG'},
495 '216'=>{authtypecode=>'TM'},
496 '220'=>{authtypecode=>'FAM'},
497 '230'=>{authtypecode=>'TU'},
498 '235'=>{authtypecode=>'CO_UNI_TI'},
499 '240'=>{authtypecode=>'SAUTTIT'},
500 '245'=>{authtypecode=>'NAME_COL'},
501 '250'=>{authtypecode=>'SNC'},
502 '260'=>{authtypecode=>'PA'},
503 '280'=>{authtypecode=>'GENRE/FORM'},
506 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
507 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
509 return;
512 =head2 GuessAuthId
514 my $authtid = GuessAuthId($record);
516 Get the record and tries to guess the adequate authtypecode from its content.
518 =cut
520 sub GuessAuthId {
521 my ($record) = @_;
522 return unless ($record && $record->field('001'));
523 # my $authtypecode=GuessAuthTypeCode($record);
524 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
525 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
526 # else {return $record->field($tag)->data}
527 return $record->field('001')->data;
530 =head2 GetTagsLabels
532 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
534 returns a ref to hashref of authorities tag and subfield structure.
536 tagslabel usage :
538 $tagslabel->{$tag}->{$subfield}->{'attribute'}
540 where attribute takes values in :
544 mandatory
545 repeatable
546 authorised_value
547 authtypecode
548 value_builder
549 kohafield
550 seealso
551 hidden
552 isurl
553 link
555 =cut
557 sub GetTagsLabels {
558 my ($forlibrarian,$authtypecode)= @_;
559 my $dbh=C4::Context->dbh;
560 $authtypecode="" unless $authtypecode;
561 my $sth;
562 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
565 # check that authority exists
566 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
567 $sth->execute($authtypecode);
568 my ($total) = $sth->fetchrow;
569 $authtypecode="" unless ($total >0);
570 $sth= $dbh->prepare(
571 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
572 FROM auth_tag_structure
573 WHERE authtypecode=?
574 ORDER BY tagfield"
577 $sth->execute($authtypecode);
578 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
580 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
581 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
582 $res->{$tag}->{tab} = " "; # XXX
583 $res->{$tag}->{mandatory} = $mandatory;
584 $res->{$tag}->{repeatable} = $repeatable;
586 $sth= $dbh->prepare(
587 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
588 FROM auth_subfield_structure
589 WHERE authtypecode=?
590 ORDER BY tagfield,tagsubfield"
592 $sth->execute($authtypecode);
594 my $subfield;
595 my $authorised_value;
596 my $value_builder;
597 my $kohafield;
598 my $seealso;
599 my $hidden;
600 my $isurl;
601 my $link;
603 while (
604 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
605 $mandatory, $repeatable, $authorised_value, $authtypecode,
606 $value_builder, $kohafield, $seealso, $hidden,
607 $isurl, $link )
608 = $sth->fetchrow
611 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
612 $res->{$tag}->{$subfield}->{tab} = $tab;
613 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
614 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
615 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
616 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
617 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
618 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
619 $res->{$tag}->{$subfield}->{seealso} = $seealso;
620 $res->{$tag}->{$subfield}->{hidden} = $hidden;
621 $res->{$tag}->{$subfield}->{isurl} = $isurl;
622 $res->{$tag}->{$subfield}->{link} = $link;
624 return $res;
627 =head2 AddAuthority
629 $authid= &AddAuthority($record, $authid,$authtypecode)
631 Either Create Or Modify existing authority.
632 returns authid of the newly created authority
634 =cut
636 sub AddAuthority {
637 # pass the MARC::Record to this function, and it will create the records in the authority table
638 my ($record,$authid,$authtypecode) = @_;
639 my $dbh=C4::Context->dbh;
640 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
642 # if authid empty => true add, find a new authid number
643 my $format;
644 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
645 $format= 'UNIMARCAUTH';
647 else {
648 $format= 'MARC21';
651 #update date/time to 005 for marc and unimarc
652 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
653 my $f5=$record->field('005');
654 if (!$f5) {
655 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
657 else {
658 $f5->update($time.".0");
661 SetUTF8Flag($record);
662 if ($format eq "MARC21") {
663 if (!$record->leader) {
664 $record->leader($leader);
666 if (!$record->field('003')) {
667 $record->insert_fields_ordered(
668 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
671 my $date=POSIX::strftime("%y%m%d",localtime);
672 if (!$record->field('008')) {
673 # Get a valid default value for field 008
674 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
675 if(!$default_008 or length($default_008)<34) {
676 $default_008 = '|| aca||aabn | a|a d';
678 else {
679 $default_008 = substr($default_008,0,34);
682 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
684 if (!$record->field('040')) {
685 $record->insert_fields_ordered(
686 MARC::Field->new('040','','',
687 'a' => C4::Context->preference('MARCOrgCode'),
688 'c' => C4::Context->preference('MARCOrgCode')
694 if ($format eq "UNIMARCAUTH") {
695 $record->leader(" nx j22 ") unless ($record->leader());
696 my $date=POSIX::strftime("%Y%m%d",localtime);
697 if (my $string=$record->subfield('100',"a")){
698 $string=~s/fre50/frey50/;
699 $record->field('100')->update('a'=>$string);
701 elsif ($record->field('100')){
702 $record->field('100')->update('a'=>$date."afrey50 ba0");
703 } else {
704 $record->append_fields(
705 MARC::Field->new('100',' ',' '
706 ,'a'=>$date."afrey50 ba0")
710 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
711 if (!$authid and $format eq "MARC21") {
712 # only need to do this fix when modifying an existing authority
713 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
715 if (my $field=$record->field($auth_type_tag)){
716 $field->update($auth_type_subfield=>$authtypecode);
718 else {
719 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
722 my $auth_exists=0;
723 my $oldRecord;
724 if (!$authid) {
725 my $sth=$dbh->prepare("select max(authid) from auth_header");
726 $sth->execute;
727 ($authid)=$sth->fetchrow;
728 $authid=$authid+1;
729 ##Insert the recordID in MARC record
730 unless ($record->field('001') && $record->field('001')->data() eq $authid){
731 $record->delete_field($record->field('001'));
732 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
734 } else {
735 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
736 # warn "auth_exists = $auth_exists";
738 if ($auth_exists>0){
739 $oldRecord=GetAuthority($authid);
740 $record->add_fields('001',$authid) unless ($record->field('001'));
741 # warn "\n\n\n enregistrement".$record->as_formatted;
742 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
743 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
744 $sth->finish;
746 else {
747 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
748 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
749 $sth->finish;
750 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
752 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
753 return ($authid);
757 =head2 DelAuthority
759 $authid= &DelAuthority($authid)
761 Deletes $authid
763 =cut
765 sub DelAuthority {
766 my ($authid) = @_;
767 my $dbh=C4::Context->dbh;
769 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
770 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
771 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
772 $sth->execute($authid);
775 =head2 ModAuthority
777 $authid= &ModAuthority($authid,$record,$authtypecode)
779 Modifies authority record, optionally updates attached biblios.
781 =cut
783 sub ModAuthority {
784 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
786 my $dbh=C4::Context->dbh;
787 #Now rewrite the $record to table with an add
788 my $oldrecord=GetAuthority($authid);
789 $authid=AddAuthority($record,$authid,$authtypecode);
791 # If a library thinks that updating all biblios is a long process and wishes
792 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
793 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
794 # be updated.
795 unless(C4::Context->preference('dontmerge') eq '1'){
796 &merge($authid,$oldrecord,$authid,$record);
797 } else {
798 # save a record in need_merge_authorities table
799 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
800 "VALUES (?,?)";
801 $dbh->do($sqlinsert,undef,($authid,0));
803 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
804 return $authid;
807 =head2 GetAuthorityXML
809 $marcxml= &GetAuthorityXML( $authid)
811 returns xml form of record $authid
813 =cut
815 sub GetAuthorityXML {
816 # Returns MARC::XML of the authority passed in parameter.
817 my ( $authid ) = @_;
818 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
819 my $dbh=C4::Context->dbh;
820 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
821 $sth->execute($authid);
822 my ($marcxml)=$sth->fetchrow;
823 return $marcxml;
825 else {
826 # for MARC21, call GetAuthority instead of
827 # getting the XML directly since we may
828 # need to fix up the location of the authority
829 # code -- note that this is reasonably safe
830 # because GetAuthorityXML is used only by the
831 # indexing processes like zebraqueue_start.pl
832 my $record = GetAuthority($authid);
833 return $record->as_xml_record('MARC21');
837 =head2 GetAuthority
839 $record= &GetAuthority( $authid)
841 Returns MARC::Record of the authority passed in parameter.
843 =cut
845 sub GetAuthority {
846 my ($authid)=@_;
847 my $dbh=C4::Context->dbh;
848 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
849 $sth->execute($authid);
850 my ($authtypecode, $marcxml) = $sth->fetchrow;
851 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
852 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
853 return undef if ($@);
854 $record->encoding('UTF-8');
855 if (C4::Context->preference("marcflavour") eq "MARC21") {
856 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
857 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
859 return ($record);
862 =head2 GetAuthType
864 $result = &GetAuthType($authtypecode)
866 If the authority type specified by C<$authtypecode> exists,
867 returns a hashref of the type's fields. If the type
868 does not exist, returns undef.
870 =cut
872 sub GetAuthType {
873 my ($authtypecode) = @_;
874 my $dbh=C4::Context->dbh;
875 my $sth;
876 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
877 # type (FIXME but why?)
878 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
879 $sth->execute($authtypecode);
880 if (my $res = $sth->fetchrow_hashref) {
881 return $res;
884 return;
888 =head2 FindDuplicateAuthority
890 $record= &FindDuplicateAuthority( $record, $authtypecode)
892 return $authid,Summary if duplicate is found.
894 Comments : an improvement would be to return All the records that match.
896 =cut
898 sub FindDuplicateAuthority {
900 my ($record,$authtypecode)=@_;
901 # warn "IN for ".$record->as_formatted;
902 my $dbh = C4::Context->dbh;
903 # warn "".$record->as_formatted;
904 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
905 $sth->execute($authtypecode);
906 my ($auth_tag_to_report) = $sth->fetchrow;
907 $sth->finish;
908 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
909 # build a request for SearchAuthorities
910 my $query='at='.$authtypecode.' ';
911 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
912 if ($record->field($auth_tag_to_report)) {
913 foreach ($record->field($auth_tag_to_report)->subfields()) {
914 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
917 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
918 # there is at least 1 result => return the 1st one
919 if (!defined $error && @{$results} ) {
920 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
921 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
923 # no result, returns nothing
924 return;
927 =head2 BuildSummary
929 $text= &BuildSummary( $record, $authid, $authtypecode)
931 return HTML encoded Summary
933 Comment : authtypecode can be infered from both record and authid.
934 Moreover, authid can also be inferred from $record.
935 Would it be interesting to delete those things.
937 =cut
939 sub BuildSummary{
940 ## give this a Marc record to return summary
941 my ($record,$authid,$authtypecode)=@_;
942 my $dbh=C4::Context->dbh;
943 my $summary;
944 # handle $authtypecode is NULL or eq ""
945 if ($authtypecode) {
946 my $authref = GetAuthType($authtypecode);
947 $summary = $authref->{summary};
949 # FIXME: should use I18N.pm
950 my %language;
951 $language{'fre'}="Français";
952 $language{'eng'}="Anglais";
953 $language{'ger'}="Allemand";
954 $language{'ita'}="Italien";
955 $language{'spa'}="Espagnol";
956 my %thesaurus;
957 $thesaurus{'1'}="Peuples";
958 $thesaurus{'2'}="Anthroponymes";
959 $thesaurus{'3'}="Oeuvres";
960 $thesaurus{'4'}="Chronologie";
961 $thesaurus{'5'}="Lieux";
962 $thesaurus{'6'}="Sujets";
963 #thesaurus a remplir
964 my @fields = $record->fields();
965 my $reported_tag;
966 # if the library has a summary defined, use it. Otherwise, build a standard one
967 # FIXME - it appears that the summary field in the authority frameworks
968 # can work as a display template. However, this doesn't
969 # suit the MARC21 version, so for now the "templating"
970 # feature will be enabled only for UNIMARC for backwards
971 # compatibility.
972 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
973 my @fields = $record->fields();
974 # $reported_tag = '$9'.$result[$counter];
975 my @stringssummary;
976 foreach my $field (@fields) {
977 my $tag = $field->tag();
978 my $tagvalue = $field->as_string();
979 my $localsummary= $summary;
980 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
981 if ($tag<10) {
982 if ($tag eq '001') {
983 $reported_tag.='$3'.$field->data();
985 } else {
986 my @subf = $field->subfields;
987 for my $i (0..$#subf) {
988 my $subfieldcode = $subf[$i][0];
989 my $subfieldvalue = $subf[$i][1];
990 my $tagsubf = $tag.$subfieldcode;
991 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
994 push @stringssummary, $localsummary if ($localsummary ne $summary);
996 my $resultstring;
997 $resultstring = join(" -- ",@stringssummary);
998 $resultstring =~ s/\[(.*?)\]//g;
999 $resultstring =~ s/\n/<br>/g;
1000 $summary = $resultstring;
1001 } else {
1002 my $heading = '';
1003 my $altheading = '';
1004 my $seealso = '';
1005 my $broaderterms = '';
1006 my $narrowerterms = '';
1007 my $see = '';
1008 my $seeheading = '';
1009 my $notes = '';
1010 my @fields = $record->fields();
1011 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1012 # construct UNIMARC summary, that is quite different from MARC21 one
1013 # accepted form
1014 foreach my $field ($record->field('2..')) {
1015 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1017 # rejected form(s)
1018 foreach my $field ($record->field('3..')) {
1019 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1021 foreach my $field ($record->field('4..')) {
1022 if ($field->subfield('2')) {
1023 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1024 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1027 # see :
1028 foreach my $field ($record->field('5..')) {
1030 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1031 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1032 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1033 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1034 } elsif ($field->subfield('a')) {
1035 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1038 # // form
1039 foreach my $field ($record->field('7..')) {
1040 my $lang = substr($field->subfield('8'),3,3);
1041 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1043 $broaderterms =~s/-- \n$//;
1044 $narrowerterms =~s/-- \n$//;
1045 $seealso =~s/-- \n$//;
1046 $see =~s/-- \n$//;
1047 $summary = $heading."<br />".($notes?"$notes <br />":"");
1048 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1049 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1050 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1051 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1052 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1053 } else {
1054 # construct MARC21 summary
1055 # FIXME - looping over 1XX is questionable
1056 # since MARC21 authority should have only one 1XX
1057 foreach my $field ($record->field('1..')) {
1058 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1059 # in MARC21 -- purely local tags really ought to be
1060 # 9XX
1061 if ($record->field('100')) {
1062 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1063 } elsif ($record->field('110')) {
1064 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1065 } elsif ($record->field('111')) {
1066 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1067 } elsif ($record->field('130')) {
1068 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1069 } elsif ($record->field('148')) {
1070 $heading.= $field->as_string('abvxyz68');
1071 } elsif ($record->field('150')) {
1072 $heading.= $field->as_string('abvxyz68');
1073 #$heading.= $field->as_formatted();
1074 my $tag=$field->tag();
1075 $heading=~s /^$tag//g;
1076 $heading =~s /\_/\$/g;
1077 } elsif ($record->field('151')) {
1078 $heading.= $field->as_string('avxyz68');
1079 } elsif ($record->field('155')) {
1080 $heading.= $field->as_string('abvxyz68');
1081 } elsif ($record->field('180')) {
1082 $heading.= $field->as_string('vxyz68');
1083 } elsif ($record->field('181')) {
1084 $heading.= $field->as_string('vxyz68');
1085 } elsif ($record->field('182')) {
1086 $heading.= $field->as_string('vxyz68');
1087 } elsif ($record->field('185')) {
1088 $heading.= $field->as_string('vxyz68');
1089 } else {
1090 $heading.= $field->as_string();
1092 } #See From
1093 foreach my $field ($record->field('4..')) {
1094 $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1095 } #See Also
1096 foreach my $field ($record->field('5..')) {
1097 $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1099 $summary .= ": " if $summary;
1100 $summary.=$heading.$seeheading.$altheading;
1103 return $summary;
1106 =head2 BuildUnimarcHierarchies
1108 $text= &BuildUnimarcHierarchies( $authid, $force)
1110 return text containing trees for hierarchies
1111 for them to be stored in auth_header
1113 Example of text:
1114 122,1314,2452;1324,2342,3,2452
1116 =cut
1118 sub BuildUnimarcHierarchies{
1119 my $authid = shift @_;
1120 # warn "authid : $authid";
1121 my $force = shift @_;
1122 my @globalresult;
1123 my $dbh=C4::Context->dbh;
1124 my $hierarchies;
1125 my $data = GetHeaderAuthority($authid);
1126 if ($data->{'authtrees'} and not $force){
1127 return $data->{'authtrees'};
1128 # } elsif ($data->{'authtrees'}){
1129 # $hierarchies=$data->{'authtrees'};
1130 } else {
1131 my $record = GetAuthority($authid);
1132 my $found;
1133 return unless $record;
1134 foreach my $field ($record->field('5..')){
1135 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1136 my $subfauthid=_get_authid_subfield($field);
1137 next if ($subfauthid eq $authid);
1138 my $parentrecord = GetAuthority($subfauthid);
1139 my $localresult=$hierarchies;
1140 my $trees;
1141 $trees = BuildUnimarcHierarchies($subfauthid);
1142 my @trees;
1143 if ($trees=~/;/){
1144 @trees = split(/;/,$trees);
1145 } else {
1146 push @trees, $trees;
1148 foreach (@trees){
1149 $_.= ",$authid";
1151 @globalresult = (@globalresult,@trees);
1152 $found=1;
1154 $hierarchies=join(";",@globalresult);
1156 #Unless there is no ancestor, I am alone.
1157 $hierarchies="$authid" unless ($hierarchies);
1159 AddAuthorityTrees($authid,$hierarchies);
1160 return $hierarchies;
1163 =head2 BuildUnimarcHierarchy
1165 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1167 return a hashref in order to display hierarchy for record and final Authid $authid
1169 "loopparents"
1170 "loopchildren"
1171 "class"
1172 "loopauthid"
1173 "current_value"
1174 "value"
1176 "ifparents"
1177 "ifchildren"
1178 Those two latest ones should disappear soon.
1180 =cut
1182 sub BuildUnimarcHierarchy{
1183 my $record = shift @_;
1184 my $class = shift @_;
1185 my $authid_constructed = shift @_;
1186 return undef unless ($record);
1187 my $authid=$record->field('001')->data();
1188 my %cell;
1189 my $parents=""; my $children="";
1190 my (@loopparents,@loopchildren);
1191 foreach my $field ($record->field('5..')){
1192 my $subfauthid=_get_authid_subfield($field);
1193 if ($subfauthid && $field->subfield('5') && $field->subfield('a')){
1194 if ($field->subfield('5') eq 'h'){
1195 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1197 elsif ($field->subfield('5') eq 'g'){
1198 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1200 # brothers could get in there with an else
1203 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1204 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1205 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1206 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1207 $cell{"class"}=$class;
1208 $cell{"loopauthid"}=$authid;
1209 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1210 $cell{"value"}=$record->subfield('2..',"a");
1211 return \%cell;
1214 sub _get_authid_subfield{
1215 my ($field)=@_;
1216 return $field->subfield('9')||$field->subfield('3');
1218 =head2 GetHeaderAuthority
1220 $ref= &GetHeaderAuthority( $authid)
1222 return a hashref in order auth_header table data
1224 =cut
1226 sub GetHeaderAuthority{
1227 my $authid = shift @_;
1228 my $sql= "SELECT * from auth_header WHERE authid = ?";
1229 my $dbh=C4::Context->dbh;
1230 my $rq= $dbh->prepare($sql);
1231 $rq->execute($authid);
1232 my $data= $rq->fetchrow_hashref;
1233 return $data;
1236 =head2 AddAuthorityTrees
1238 $ref= &AddAuthorityTrees( $authid, $trees)
1240 return success or failure
1242 =cut
1244 sub AddAuthorityTrees{
1245 my $authid = shift @_;
1246 my $trees = shift @_;
1247 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1248 my $dbh=C4::Context->dbh;
1249 my $rq= $dbh->prepare($sql);
1250 return $rq->execute($trees,$authid);
1253 =head2 merge
1255 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1257 Could add some feature : Migrating from a typecode to an other for instance.
1258 Then we should add some new parameter : bibliotargettag, authtargettag
1260 =cut
1262 sub merge {
1263 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1264 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1265 my $dbh=C4::Context->dbh;
1266 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1267 my $authtypecodeto = GetAuthTypeCode($mergeto);
1268 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1269 # return if authority does not exist
1270 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1271 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1272 # search the tag to report
1273 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1274 $sth->execute($authtypecodefrom);
1275 my ($auth_tag_to_report_from) = $sth->fetchrow;
1276 $sth->execute($authtypecodeto);
1277 my ($auth_tag_to_report_to) = $sth->fetchrow;
1279 my @record_to;
1280 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1281 my @record_from;
1282 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1284 my @reccache;
1285 # search all biblio tags using this authority.
1286 #Getting marcbiblios impacted by the change.
1287 if (C4::Context->preference('NoZebra')) {
1288 #nozebra way
1289 my $dbh=C4::Context->dbh;
1290 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1291 $rq->execute;
1292 while (my $biblionumbers=$rq->fetchrow){
1293 my @biblionumbers=split /;/,$biblionumbers;
1294 foreach (@biblionumbers) {
1295 if ($_=~/(\d+),.*/) {
1296 my $marc=GetMarcBiblio($1);
1297 push @reccache,$marc;
1301 } else {
1302 #zebra connection
1303 my $oConnection=C4::Context->Zconn("biblioserver",0);
1304 my $oldSyntax = $oConnection->option("preferredRecordSyntax");
1305 $oConnection->option("preferredRecordSyntax"=>"XML");
1306 my $query;
1307 $query= "an=".$mergefrom;
1308 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1309 my $count = 0;
1310 if ($oResult) {
1311 $count=$oResult->size();
1313 my $z=0;
1314 while ( $z<$count ) {
1315 my $rec;
1316 $rec=$oResult->record($z);
1317 my $marcdata = $rec->raw();
1318 my $marcrecordzebra= MARC::Record->new_from_xml($marcdata,"utf8",C4::Context->preference("marcflavour"));
1319 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1320 my $i = $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1321 my $marcrecorddb=GetMarcBiblio($i);
1322 push @reccache, $marcrecorddb;
1323 $z++;
1325 $oResult->destroy();
1326 $oConnection->option("preferredRecordSyntax"=>$oldSyntax);
1328 #warn scalar(@reccache)." biblios to update";
1329 # Get All candidate Tags for the change
1330 # (This will reduce the search scope in marc records).
1331 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1332 $sth->execute($authtypecodefrom);
1333 my @tags_using_authtype;
1334 while (my ($tagfield) = $sth->fetchrow) {
1335 push @tags_using_authtype,$tagfield ;
1337 my $tag_to=0;
1338 if ($authtypecodeto ne $authtypecodefrom){
1339 # If many tags, take the first
1340 $sth->execute($authtypecodeto);
1341 $tag_to=$sth->fetchrow;
1342 #warn $tag_to;
1344 # BulkEdit marc records
1345 # May be used as a template for a bulkedit field
1346 foreach my $marcrecord(@reccache){
1347 my $update;
1348 foreach my $tagfield (@tags_using_authtype){
1349 # warn "tagfield : $tagfield ";
1350 foreach my $field ($marcrecord->field($tagfield)){
1351 my $auth_number=$field->subfield("9");
1352 my $tag=$field->tag();
1353 if ($auth_number==$mergefrom) {
1354 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1355 my $exclude='9';
1356 foreach my $subfield (@record_to) {
1357 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1358 $exclude.= $subfield->[0];
1360 $exclude='['.$exclude.']';
1361 # add subfields in $field not included in @record_to
1362 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1363 foreach my $subfield (@restore) {
1364 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1366 $marcrecord->delete_field($field);
1367 $marcrecord->insert_grouped_field($field_to);
1368 $update=1;
1370 }#for each tag
1371 }#foreach tagfield
1372 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1373 my $biblionumber;
1374 if ($bibliotag<10){
1375 $biblionumber=$marcrecord->field($bibliotag)->data;
1377 else {
1378 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1380 unless ($biblionumber){
1381 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1382 next;
1384 if ($update==1){
1385 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1386 $counteditedbiblio++;
1387 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1389 }#foreach $marc
1390 return $counteditedbiblio;
1391 # now, find every other authority linked with this authority
1392 # now, find every other authority linked with this authority
1393 # my $oConnection=C4::Context->Zconn("authorityserver");
1394 # my $query;
1395 # # att 9210 Auth-Internal-authtype
1396 # # att 9220 Auth-Internal-LN
1397 # # ccl.properties to add for authorities
1398 # $query= "= ".$mergefrom;
1399 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1400 # my $count=$oResult->size() if ($oResult);
1401 # my @reccache;
1402 # my $z=0;
1403 # while ( $z<$count ) {
1404 # my $rec;
1405 # $rec=$oResult->record($z);
1406 # my $marcdata = $rec->raw();
1407 # push @reccache, $marcdata;
1408 # $z++;
1410 # $oResult->destroy();
1411 # foreach my $marc(@reccache){
1412 # my $update;
1413 # my $marcrecord;
1414 # $marcrecord = MARC::File::USMARC::decode($marc);
1415 # foreach my $tagfield (@tags_using_authtype){
1416 # $tagfield=substr($tagfield,0,3);
1417 # my @tags = $marcrecord->field($tagfield);
1418 # foreach my $tag (@tags){
1419 # my $tagsubs=$tag->subfield("9");
1420 # #warn "$tagfield:$tagsubs:$mergefrom";
1421 # if ($tagsubs== $mergefrom) {
1422 # $tag->update("9" =>$mergeto);
1423 # foreach my $subfield (@record_to) {
1424 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1425 # $tag->update($subfield->[0] =>$subfield->[1]);
1426 # }#for $subfield
1428 # $marcrecord->delete_field($tag);
1429 # $marcrecord->add_fields($tag);
1430 # $update=1;
1431 # }#for each tag
1432 # }#foreach tagfield
1433 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1434 # if ($update==1){
1435 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1438 # }#foreach $marc
1439 }#sub
1441 =head2 get_auth_type_location
1443 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1445 Get the tag and subfield used to store the heading type
1446 for indexing purposes. The C<$auth_type> parameter is
1447 optional; if it is not supplied, assume ''.
1449 This routine searches the MARC authority framework
1450 for the tag and subfield whose kohafield is
1451 C<auth_header.authtypecode>; if no such field is
1452 defined in the framework, default to the hardcoded value
1453 specific to the MARC format.
1455 =cut
1457 sub get_auth_type_location {
1458 my $auth_type_code = @_ ? shift : '';
1460 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1461 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1462 return ($tag, $subfield);
1463 } else {
1464 if (C4::Context->preference('marcflavour') eq "MARC21") {
1465 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1466 } else {
1467 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1472 END { } # module clean-up code here (global destructor)
1475 __END__
1477 =head1 AUTHOR
1479 Koha Development Team <http://koha-community.org/>
1481 Paul POULAIN paul.poulain@free.fr
1483 =cut