Bug 7767 - acqui/basketgroup.pl: our $template scoping for plack
[koha.git] / C4 / AuthoritiesMarc.pm
blobf35b885881f1ae2b549ad0b94f178af6510a677b
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= ($sortby eq "HeadingAsc"?
283 '@attr 7=1 @attr 1=Heading 0'
285 $sortby eq "HeadingDsc"?
286 '@attr 7=2 @attr 1=Heading 0'
289 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
290 $query="\@or $orderstring $query" if $orderstring;
292 $offset=0 unless $offset;
293 my $counter = $offset;
294 $length=10 unless $length;
295 my @oAuth;
296 my $i;
297 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
298 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
299 my $oAResult;
300 $oAResult= $oAuth[0]->search($Anewq) ;
301 while (($i = ZOOM::event(\@oAuth)) != 0) {
302 my $ev = $oAuth[$i-1]->last_event();
303 last if $ev == ZOOM::Event::ZEND;
305 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
306 if ($error) {
307 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
308 goto NOLUCK;
311 my $nbresults;
312 $nbresults=$oAResult->size();
313 my $nremains=$nbresults;
314 my @result = ();
315 my @finalresult = ();
317 if ($nbresults>0){
319 ##Find authid and linkid fields
320 ##we may be searching multiple authoritytypes.
321 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
322 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
323 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
324 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
326 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
327 my $rec=$oAResult->record($counter);
328 my $marcdata=$rec->raw();
329 my $authrecord;
330 my $separator=C4::Context->preference('authoritysep');
331 $authrecord = MARC::File::USMARC::decode($marcdata);
332 my $authid=$authrecord->field('001')->data();
333 my %newline;
334 $newline{authid} = $authid;
335 if ( !$skipmetadata ) {
336 my $summary =
337 BuildSummary( $authrecord, $authid, $authtypecode );
338 my $query_auth_tag =
339 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
340 my $sth = $dbh->prepare($query_auth_tag);
341 $sth->execute($authtypecode);
342 my $auth_tag_to_report = $sth->fetchrow;
343 my $reported_tag;
344 my $mainentry = $authrecord->field($auth_tag_to_report);
345 if ($mainentry) {
347 foreach ( $mainentry->subfields() ) {
348 $reported_tag .= '$' . $_->[0] . $_->[1];
351 $newline{summary} = $summary;
352 $newline{even} = $counter % 2;
353 $newline{reported_tag} = $reported_tag;
355 $counter++;
356 push @finalresult, \%newline;
357 }## while counter
359 if (! $skipmetadata) {
360 for (my $z=0; $z<@finalresult; $z++){
361 my $count=CountUsage($finalresult[$z]{authid});
362 $finalresult[$z]{used}=$count;
363 }# all $z's
366 }## if nbresult
367 NOLUCK:
368 $oAResult->destroy();
369 # $oAuth[0]->destroy();
371 return (\@finalresult, $nbresults);
375 =head2 CountUsage
377 $count= &CountUsage($authid)
379 counts Usage of Authid in bibliorecords.
381 =cut
383 sub CountUsage {
384 my ($authid) = @_;
385 if (C4::Context->preference('NoZebra')) {
386 # Read the index Koha-Auth-Number for this authid and count the lines
387 my $result = C4::Search::NZanalyse("an=$authid");
388 my @tab = split /;/,$result;
389 return scalar @tab;
390 } else {
391 ### ZOOM search here
392 my $query;
393 $query= "an=".$authid;
394 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
395 if ($err) {
396 warn "Error: $err from search $query";
397 $result = 0;
400 return $result;
404 =head2 CountUsageChildren
406 $count= &CountUsageChildren($authid)
408 counts Usage of narrower terms of Authid in bibliorecords.
410 =cut
412 sub CountUsageChildren {
413 my ($authid) = @_;
416 =head2 GetAuthTypeCode
418 $authtypecode= &GetAuthTypeCode($authid)
420 returns authtypecode of an authid
422 =cut
424 sub GetAuthTypeCode {
425 #AUTHfind_authtypecode
426 my ($authid) = @_;
427 my $dbh=C4::Context->dbh;
428 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
429 $sth->execute($authid);
430 my $authtypecode = $sth->fetchrow;
431 return $authtypecode;
434 =head2 GuessAuthTypeCode
436 my $authtypecode = GuessAuthTypeCode($record);
438 Get the record and tries to guess the adequate authtypecode from its content.
440 =cut
442 sub GuessAuthTypeCode {
443 my ($record) = @_;
444 return unless defined $record;
445 my $heading_fields = {
446 "MARC21"=>{
447 '100'=>{authtypecode=>'PERSO_NAME'},
448 '110'=>{authtypecode=>'CORPO_NAME'},
449 '111'=>{authtypecode=>'MEETI_NAME'},
450 '130'=>{authtypecode=>'UNIF_TITLE'},
451 '148'=>{authtypecode=>'CHRON_TERM'},
452 '150'=>{authtypecode=>'TOPIC_TERM'},
453 '151'=>{authtypecode=>'GEOGR_NAME'},
454 '155'=>{authtypecode=>'GENRE/FORM'},
455 '180'=>{authtypecode=>'GEN_SUBDIV'},
456 '181'=>{authtypecode=>'GEO_SUBDIV'},
457 '182'=>{authtypecode=>'CHRON_SUBD'},
458 '185'=>{authtypecode=>'FORM_SUBD'},
460 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
461 # 604 with embedded 700, 701, 702
462 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
463 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
464 #216 Trademark 716 [Reserved for future use]
465 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
466 #230 Title 500 4-- with embedded 500 605
467 #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
468 #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
469 #250 Topical subject 606
470 #260 Place access 620
471 #280 Form, genre or physical characteristics 608
474 # Could also be represented with :
475 #leader position 9
476 #a = personal name entry
477 #b = corporate name entry
478 #c = territorial or geographical name
479 #d = trademark
480 #e = family name
481 #f = uniform title
482 #g = collective uniform title
483 #h = name/title
484 #i = name/collective uniform title
485 #j = topical subject
486 #k = place access
487 #l = form, genre or physical characteristics
488 "UNIMARC"=>{
489 '200'=>{authtypecode=>'NP'},
490 '210'=>{authtypecode=>'CO'},
491 '215'=>{authtypecode=>'SNG'},
492 '216'=>{authtypecode=>'TM'},
493 '220'=>{authtypecode=>'FAM'},
494 '230'=>{authtypecode=>'TU'},
495 '235'=>{authtypecode=>'CO_UNI_TI'},
496 '240'=>{authtypecode=>'SAUTTIT'},
497 '245'=>{authtypecode=>'NAME_COL'},
498 '250'=>{authtypecode=>'SNC'},
499 '260'=>{authtypecode=>'PA'},
500 '280'=>{authtypecode=>'GENRE/FORM'},
503 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
504 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
506 return;
509 =head2 GuessAuthId
511 my $authtid = GuessAuthId($record);
513 Get the record and tries to guess the adequate authtypecode from its content.
515 =cut
517 sub GuessAuthId {
518 my ($record) = @_;
519 return unless ($record && $record->field('001'));
520 # my $authtypecode=GuessAuthTypeCode($record);
521 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
522 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
523 # else {return $record->field($tag)->data}
524 return $record->field('001')->data;
527 =head2 GetTagsLabels
529 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
531 returns a ref to hashref of authorities tag and subfield structure.
533 tagslabel usage :
535 $tagslabel->{$tag}->{$subfield}->{'attribute'}
537 where attribute takes values in :
541 mandatory
542 repeatable
543 authorised_value
544 authtypecode
545 value_builder
546 kohafield
547 seealso
548 hidden
549 isurl
550 link
552 =cut
554 sub GetTagsLabels {
555 my ($forlibrarian,$authtypecode)= @_;
556 my $dbh=C4::Context->dbh;
557 $authtypecode="" unless $authtypecode;
558 my $sth;
559 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
562 # check that authority exists
563 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
564 $sth->execute($authtypecode);
565 my ($total) = $sth->fetchrow;
566 $authtypecode="" unless ($total >0);
567 $sth= $dbh->prepare(
568 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
569 FROM auth_tag_structure
570 WHERE authtypecode=?
571 ORDER BY tagfield"
574 $sth->execute($authtypecode);
575 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
577 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
578 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
579 $res->{$tag}->{tab} = " "; # XXX
580 $res->{$tag}->{mandatory} = $mandatory;
581 $res->{$tag}->{repeatable} = $repeatable;
583 $sth= $dbh->prepare(
584 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
585 FROM auth_subfield_structure
586 WHERE authtypecode=?
587 ORDER BY tagfield,tagsubfield"
589 $sth->execute($authtypecode);
591 my $subfield;
592 my $authorised_value;
593 my $value_builder;
594 my $kohafield;
595 my $seealso;
596 my $hidden;
597 my $isurl;
598 my $link;
600 while (
601 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
602 $mandatory, $repeatable, $authorised_value, $authtypecode,
603 $value_builder, $kohafield, $seealso, $hidden,
604 $isurl, $link )
605 = $sth->fetchrow
608 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
609 $res->{$tag}->{$subfield}->{tab} = $tab;
610 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
611 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
612 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
613 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
614 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
615 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
616 $res->{$tag}->{$subfield}->{seealso} = $seealso;
617 $res->{$tag}->{$subfield}->{hidden} = $hidden;
618 $res->{$tag}->{$subfield}->{isurl} = $isurl;
619 $res->{$tag}->{$subfield}->{link} = $link;
621 return $res;
624 =head2 AddAuthority
626 $authid= &AddAuthority($record, $authid,$authtypecode)
628 Either Create Or Modify existing authority.
629 returns authid of the newly created authority
631 =cut
633 sub AddAuthority {
634 # pass the MARC::Record to this function, and it will create the records in the authority table
635 my ($record,$authid,$authtypecode) = @_;
636 my $dbh=C4::Context->dbh;
637 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
639 # if authid empty => true add, find a new authid number
640 my $format;
641 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
642 $format= 'UNIMARCAUTH';
644 else {
645 $format= 'MARC21';
648 #update date/time to 005 for marc and unimarc
649 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
650 my $f5=$record->field('005');
651 if (!$f5) {
652 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
654 else {
655 $f5->update($time.".0");
658 SetUTF8Flag($record);
659 if ($format eq "MARC21") {
660 if (!$record->leader) {
661 $record->leader($leader);
663 if (!$record->field('003')) {
664 $record->insert_fields_ordered(
665 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
668 my $date=POSIX::strftime("%y%m%d",localtime);
669 if (!$record->field('008')) {
670 # Get a valid default value for field 008
671 my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
672 if(!$default_008 or length($default_008)<34) {
673 $default_008 = '|| aca||aabn | a|a d';
675 else {
676 $default_008 = substr($default_008,0,34);
679 $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
681 if (!$record->field('040')) {
682 $record->insert_fields_ordered(
683 MARC::Field->new('040','','',
684 'a' => C4::Context->preference('MARCOrgCode'),
685 'c' => C4::Context->preference('MARCOrgCode')
691 if ($format eq "UNIMARCAUTH") {
692 $record->leader(" nx j22 ") unless ($record->leader());
693 my $date=POSIX::strftime("%Y%m%d",localtime);
694 if (my $string=$record->subfield('100',"a")){
695 $string=~s/fre50/frey50/;
696 $record->field('100')->update('a'=>$string);
698 elsif ($record->field('100')){
699 $record->field('100')->update('a'=>$date."afrey50 ba0");
700 } else {
701 $record->append_fields(
702 MARC::Field->new('100',' ',' '
703 ,'a'=>$date."afrey50 ba0")
707 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
708 if (!$authid and $format eq "MARC21") {
709 # only need to do this fix when modifying an existing authority
710 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
712 if (my $field=$record->field($auth_type_tag)){
713 $field->update($auth_type_subfield=>$authtypecode);
715 else {
716 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
719 my $auth_exists=0;
720 my $oldRecord;
721 if (!$authid) {
722 my $sth=$dbh->prepare("select max(authid) from auth_header");
723 $sth->execute;
724 ($authid)=$sth->fetchrow;
725 $authid=$authid+1;
726 ##Insert the recordID in MARC record
727 unless ($record->field('001') && $record->field('001')->data() eq $authid){
728 $record->delete_field($record->field('001'));
729 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
731 } else {
732 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
733 # warn "auth_exists = $auth_exists";
735 if ($auth_exists>0){
736 $oldRecord=GetAuthority($authid);
737 $record->add_fields('001',$authid) unless ($record->field('001'));
738 # warn "\n\n\n enregistrement".$record->as_formatted;
739 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
740 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
741 $sth->finish;
743 else {
744 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
745 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
746 $sth->finish;
747 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
749 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
750 return ($authid);
754 =head2 DelAuthority
756 $authid= &DelAuthority($authid)
758 Deletes $authid
760 =cut
762 sub DelAuthority {
763 my ($authid) = @_;
764 my $dbh=C4::Context->dbh;
766 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
767 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
768 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
769 $sth->execute($authid);
772 =head2 ModAuthority
774 $authid= &ModAuthority($authid,$record,$authtypecode)
776 Modifies authority record, optionally updates attached biblios.
778 =cut
780 sub ModAuthority {
781 my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
783 my $dbh=C4::Context->dbh;
784 #Now rewrite the $record to table with an add
785 my $oldrecord=GetAuthority($authid);
786 $authid=AddAuthority($record,$authid,$authtypecode);
788 # If a library thinks that updating all biblios is a long process and wishes
789 # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
790 # In that case set system preference "dontmerge" to 1. Otherwise biblios will
791 # be updated.
792 unless(C4::Context->preference('dontmerge') eq '1'){
793 &merge($authid,$oldrecord,$authid,$record);
794 } else {
795 # save a record in need_merge_authorities table
796 my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
797 "VALUES (?,?)";
798 $dbh->do($sqlinsert,undef,($authid,0));
800 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
801 return $authid;
804 =head2 GetAuthorityXML
806 $marcxml= &GetAuthorityXML( $authid)
808 returns xml form of record $authid
810 =cut
812 sub GetAuthorityXML {
813 # Returns MARC::XML of the authority passed in parameter.
814 my ( $authid ) = @_;
815 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
816 my $dbh=C4::Context->dbh;
817 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
818 $sth->execute($authid);
819 my ($marcxml)=$sth->fetchrow;
820 return $marcxml;
822 else {
823 # for MARC21, call GetAuthority instead of
824 # getting the XML directly since we may
825 # need to fix up the location of the authority
826 # code -- note that this is reasonably safe
827 # because GetAuthorityXML is used only by the
828 # indexing processes like zebraqueue_start.pl
829 my $record = GetAuthority($authid);
830 return $record->as_xml_record('MARC21');
834 =head2 GetAuthority
836 $record= &GetAuthority( $authid)
838 Returns MARC::Record of the authority passed in parameter.
840 =cut
842 sub GetAuthority {
843 my ($authid)=@_;
844 my $dbh=C4::Context->dbh;
845 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
846 $sth->execute($authid);
847 my ($authtypecode, $marcxml) = $sth->fetchrow;
848 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
849 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
850 return undef if ($@);
851 $record->encoding('UTF-8');
852 if (C4::Context->preference("marcflavour") eq "MARC21") {
853 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
854 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
856 return ($record);
859 =head2 GetAuthType
861 $result = &GetAuthType($authtypecode)
863 If the authority type specified by C<$authtypecode> exists,
864 returns a hashref of the type's fields. If the type
865 does not exist, returns undef.
867 =cut
869 sub GetAuthType {
870 my ($authtypecode) = @_;
871 my $dbh=C4::Context->dbh;
872 my $sth;
873 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
874 # type (FIXME but why?)
875 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
876 $sth->execute($authtypecode);
877 if (my $res = $sth->fetchrow_hashref) {
878 return $res;
881 return;
885 =head2 FindDuplicateAuthority
887 $record= &FindDuplicateAuthority( $record, $authtypecode)
889 return $authid,Summary if duplicate is found.
891 Comments : an improvement would be to return All the records that match.
893 =cut
895 sub FindDuplicateAuthority {
897 my ($record,$authtypecode)=@_;
898 # warn "IN for ".$record->as_formatted;
899 my $dbh = C4::Context->dbh;
900 # warn "".$record->as_formatted;
901 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
902 $sth->execute($authtypecode);
903 my ($auth_tag_to_report) = $sth->fetchrow;
904 $sth->finish;
905 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
906 # build a request for SearchAuthorities
907 my $query='at='.$authtypecode.' ';
908 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
909 if ($record->field($auth_tag_to_report)) {
910 foreach ($record->field($auth_tag_to_report)->subfields()) {
911 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
914 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
915 # there is at least 1 result => return the 1st one
916 if (!defined $error && @{$results} ) {
917 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
918 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
920 # no result, returns nothing
921 return;
924 =head2 BuildSummary
926 $text= &BuildSummary( $record, $authid, $authtypecode)
928 return HTML encoded Summary
930 Comment : authtypecode can be infered from both record and authid.
931 Moreover, authid can also be inferred from $record.
932 Would it be interesting to delete those things.
934 =cut
936 sub BuildSummary{
937 ## give this a Marc record to return summary
938 my ($record,$authid,$authtypecode)=@_;
939 my $dbh=C4::Context->dbh;
940 my $summary;
941 # handle $authtypecode is NULL or eq ""
942 if ($authtypecode) {
943 my $authref = GetAuthType($authtypecode);
944 $summary = $authref->{summary};
946 # FIXME: should use I18N.pm
947 my %language;
948 $language{'fre'}="Français";
949 $language{'eng'}="Anglais";
950 $language{'ger'}="Allemand";
951 $language{'ita'}="Italien";
952 $language{'spa'}="Espagnol";
953 my %thesaurus;
954 $thesaurus{'1'}="Peuples";
955 $thesaurus{'2'}="Anthroponymes";
956 $thesaurus{'3'}="Oeuvres";
957 $thesaurus{'4'}="Chronologie";
958 $thesaurus{'5'}="Lieux";
959 $thesaurus{'6'}="Sujets";
960 #thesaurus a remplir
961 my @fields = $record->fields();
962 my $reported_tag;
963 # if the library has a summary defined, use it. Otherwise, build a standard one
964 # FIXME - it appears that the summary field in the authority frameworks
965 # can work as a display template. However, this doesn't
966 # suit the MARC21 version, so for now the "templating"
967 # feature will be enabled only for UNIMARC for backwards
968 # compatibility.
969 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
970 my @fields = $record->fields();
971 # $reported_tag = '$9'.$result[$counter];
972 my @stringssummary;
973 foreach my $field (@fields) {
974 my $tag = $field->tag();
975 my $tagvalue = $field->as_string();
976 my $localsummary= $summary;
977 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
978 if ($tag<10) {
979 if ($tag eq '001') {
980 $reported_tag.='$3'.$field->data();
982 } else {
983 my @subf = $field->subfields;
984 for my $i (0..$#subf) {
985 my $subfieldcode = $subf[$i][0];
986 my $subfieldvalue = $subf[$i][1];
987 my $tagsubf = $tag.$subfieldcode;
988 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
991 push @stringssummary, $localsummary if ($localsummary ne $summary);
993 my $resultstring;
994 $resultstring = join(" -- ",@stringssummary);
995 $resultstring =~ s/\[(.*?)\]//g;
996 $resultstring =~ s/\n/<br>/g;
997 $summary = $resultstring;
998 } else {
999 my $heading = '';
1000 my $altheading = '';
1001 my $seealso = '';
1002 my $broaderterms = '';
1003 my $narrowerterms = '';
1004 my $see = '';
1005 my $seeheading = '';
1006 my $notes = '';
1007 my @fields = $record->fields();
1008 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1009 # construct UNIMARC summary, that is quite different from MARC21 one
1010 # accepted form
1011 foreach my $field ($record->field('2..')) {
1012 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1014 # rejected form(s)
1015 foreach my $field ($record->field('3..')) {
1016 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1018 foreach my $field ($record->field('4..')) {
1019 if ($field->subfield('2')) {
1020 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1021 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1024 # see :
1025 foreach my $field ($record->field('5..')) {
1027 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1028 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1029 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1030 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1031 } elsif ($field->subfield('a')) {
1032 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1035 # // form
1036 foreach my $field ($record->field('7..')) {
1037 my $lang = substr($field->subfield('8'),3,3);
1038 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1040 $broaderterms =~s/-- \n$//;
1041 $narrowerterms =~s/-- \n$//;
1042 $seealso =~s/-- \n$//;
1043 $see =~s/-- \n$//;
1044 $summary = $heading."<br />".($notes?"$notes <br />":"");
1045 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1046 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1047 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1048 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1049 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1050 } else {
1051 # construct MARC21 summary
1052 # FIXME - looping over 1XX is questionable
1053 # since MARC21 authority should have only one 1XX
1054 foreach my $field ($record->field('1..')) {
1055 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1056 # in MARC21 -- purely local tags really ought to be
1057 # 9XX
1058 if ($record->field('100')) {
1059 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1060 } elsif ($record->field('110')) {
1061 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1062 } elsif ($record->field('111')) {
1063 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1064 } elsif ($record->field('130')) {
1065 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1066 } elsif ($record->field('148')) {
1067 $heading.= $field->as_string('abvxyz68');
1068 } elsif ($record->field('150')) {
1069 $heading.= $field->as_string('abvxyz68');
1070 #$heading.= $field->as_formatted();
1071 my $tag=$field->tag();
1072 $heading=~s /^$tag//g;
1073 $heading =~s /\_/\$/g;
1074 } elsif ($record->field('151')) {
1075 $heading.= $field->as_string('avxyz68');
1076 } elsif ($record->field('155')) {
1077 $heading.= $field->as_string('abvxyz68');
1078 } elsif ($record->field('180')) {
1079 $heading.= $field->as_string('vxyz68');
1080 } elsif ($record->field('181')) {
1081 $heading.= $field->as_string('vxyz68');
1082 } elsif ($record->field('182')) {
1083 $heading.= $field->as_string('vxyz68');
1084 } elsif ($record->field('185')) {
1085 $heading.= $field->as_string('vxyz68');
1086 } else {
1087 $heading.= $field->as_string();
1089 } #See From
1090 foreach my $field ($record->field('4..')) {
1091 $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1092 } #See Also
1093 foreach my $field ($record->field('5..')) {
1094 $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1096 $summary .= ": " if $summary;
1097 $summary.=$heading.$seeheading.$altheading;
1100 return $summary;
1103 =head2 BuildUnimarcHierarchies
1105 $text= &BuildUnimarcHierarchies( $authid, $force)
1107 return text containing trees for hierarchies
1108 for them to be stored in auth_header
1110 Example of text:
1111 122,1314,2452;1324,2342,3,2452
1113 =cut
1115 sub BuildUnimarcHierarchies{
1116 my $authid = shift @_;
1117 # warn "authid : $authid";
1118 my $force = shift @_;
1119 my @globalresult;
1120 my $dbh=C4::Context->dbh;
1121 my $hierarchies;
1122 my $data = GetHeaderAuthority($authid);
1123 if ($data->{'authtrees'} and not $force){
1124 return $data->{'authtrees'};
1125 # } elsif ($data->{'authtrees'}){
1126 # $hierarchies=$data->{'authtrees'};
1127 } else {
1128 my $record = GetAuthority($authid);
1129 my $found;
1130 return unless $record;
1131 foreach my $field ($record->field('5..')){
1132 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1133 my $subfauthid=_get_authid_subfield($field);
1134 next if ($subfauthid eq $authid);
1135 my $parentrecord = GetAuthority($subfauthid);
1136 my $localresult=$hierarchies;
1137 my $trees;
1138 $trees = BuildUnimarcHierarchies($subfauthid);
1139 my @trees;
1140 if ($trees=~/;/){
1141 @trees = split(/;/,$trees);
1142 } else {
1143 push @trees, $trees;
1145 foreach (@trees){
1146 $_.= ",$authid";
1148 @globalresult = (@globalresult,@trees);
1149 $found=1;
1151 $hierarchies=join(";",@globalresult);
1153 #Unless there is no ancestor, I am alone.
1154 $hierarchies="$authid" unless ($hierarchies);
1156 AddAuthorityTrees($authid,$hierarchies);
1157 return $hierarchies;
1160 =head2 BuildUnimarcHierarchy
1162 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1164 return a hashref in order to display hierarchy for record and final Authid $authid
1166 "loopparents"
1167 "loopchildren"
1168 "class"
1169 "loopauthid"
1170 "current_value"
1171 "value"
1173 "ifparents"
1174 "ifchildren"
1175 Those two latest ones should disappear soon.
1177 =cut
1179 sub BuildUnimarcHierarchy{
1180 my $record = shift @_;
1181 my $class = shift @_;
1182 my $authid_constructed = shift @_;
1183 return undef unless ($record);
1184 my $authid=$record->field('001')->data();
1185 my %cell;
1186 my $parents=""; my $children="";
1187 my (@loopparents,@loopchildren);
1188 foreach my $field ($record->field('5..')){
1189 my $subfauthid=_get_authid_subfield($field);
1190 if ($subfauthid && $field->subfield('5') && $field->subfield('a')){
1191 if ($field->subfield('5') eq 'h'){
1192 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1194 elsif ($field->subfield('5') eq 'g'){
1195 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1197 # brothers could get in there with an else
1200 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1201 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1202 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1203 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1204 $cell{"class"}=$class;
1205 $cell{"loopauthid"}=$authid;
1206 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1207 $cell{"value"}=$record->subfield('2..',"a");
1208 return \%cell;
1211 sub _get_authid_subfield{
1212 my ($field)=@_;
1213 return $field->subfield('9')||$field->subfield('3');
1215 =head2 GetHeaderAuthority
1217 $ref= &GetHeaderAuthority( $authid)
1219 return a hashref in order auth_header table data
1221 =cut
1223 sub GetHeaderAuthority{
1224 my $authid = shift @_;
1225 my $sql= "SELECT * from auth_header WHERE authid = ?";
1226 my $dbh=C4::Context->dbh;
1227 my $rq= $dbh->prepare($sql);
1228 $rq->execute($authid);
1229 my $data= $rq->fetchrow_hashref;
1230 return $data;
1233 =head2 AddAuthorityTrees
1235 $ref= &AddAuthorityTrees( $authid, $trees)
1237 return success or failure
1239 =cut
1241 sub AddAuthorityTrees{
1242 my $authid = shift @_;
1243 my $trees = shift @_;
1244 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1245 my $dbh=C4::Context->dbh;
1246 my $rq= $dbh->prepare($sql);
1247 return $rq->execute($trees,$authid);
1250 =head2 merge
1252 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1254 Could add some feature : Migrating from a typecode to an other for instance.
1255 Then we should add some new parameter : bibliotargettag, authtargettag
1257 =cut
1259 sub merge {
1260 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1261 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1262 my $dbh=C4::Context->dbh;
1263 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1264 my $authtypecodeto = GetAuthTypeCode($mergeto);
1265 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1266 # return if authority does not exist
1267 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1268 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1269 # search the tag to report
1270 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1271 $sth->execute($authtypecodefrom);
1272 my ($auth_tag_to_report_from) = $sth->fetchrow;
1273 $sth->execute($authtypecodeto);
1274 my ($auth_tag_to_report_to) = $sth->fetchrow;
1276 my @record_to;
1277 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1278 my @record_from;
1279 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1281 my @reccache;
1282 # search all biblio tags using this authority.
1283 #Getting marcbiblios impacted by the change.
1284 if (C4::Context->preference('NoZebra')) {
1285 #nozebra way
1286 my $dbh=C4::Context->dbh;
1287 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1288 $rq->execute;
1289 while (my $biblionumbers=$rq->fetchrow){
1290 my @biblionumbers=split /;/,$biblionumbers;
1291 foreach (@biblionumbers) {
1292 if ($_=~/(\d+),.*/) {
1293 my $marc=GetMarcBiblio($1);
1294 push @reccache,$marc;
1298 } else {
1299 #zebra connection
1300 my $oConnection=C4::Context->Zconn("biblioserver",0);
1301 my $oldSyntax = $oConnection->option("preferredRecordSyntax");
1302 $oConnection->option("preferredRecordSyntax"=>"XML");
1303 my $query;
1304 $query= "an=".$mergefrom;
1305 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1306 my $count = 0;
1307 if ($oResult) {
1308 $count=$oResult->size();
1310 my $z=0;
1311 while ( $z<$count ) {
1312 my $rec;
1313 $rec=$oResult->record($z);
1314 my $marcdata = $rec->raw();
1315 my $marcrecordzebra= MARC::Record->new_from_xml($marcdata,"utf8",C4::Context->preference("marcflavour"));
1316 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1317 my $i = $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1318 my $marcrecorddb=GetMarcBiblio($i);
1319 push @reccache, $marcrecorddb;
1320 $z++;
1322 $oResult->destroy();
1323 $oConnection->option("preferredRecordSyntax"=>$oldSyntax);
1325 #warn scalar(@reccache)." biblios to update";
1326 # Get All candidate Tags for the change
1327 # (This will reduce the search scope in marc records).
1328 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1329 $sth->execute($authtypecodefrom);
1330 my @tags_using_authtype;
1331 while (my ($tagfield) = $sth->fetchrow) {
1332 push @tags_using_authtype,$tagfield ;
1334 my $tag_to=0;
1335 if ($authtypecodeto ne $authtypecodefrom){
1336 # If many tags, take the first
1337 $sth->execute($authtypecodeto);
1338 $tag_to=$sth->fetchrow;
1339 #warn $tag_to;
1341 # BulkEdit marc records
1342 # May be used as a template for a bulkedit field
1343 foreach my $marcrecord(@reccache){
1344 my $update;
1345 foreach my $tagfield (@tags_using_authtype){
1346 # warn "tagfield : $tagfield ";
1347 foreach my $field ($marcrecord->field($tagfield)){
1348 my $auth_number=$field->subfield("9");
1349 my $tag=$field->tag();
1350 if ($auth_number==$mergefrom) {
1351 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1352 my $exclude='9';
1353 foreach my $subfield (@record_to) {
1354 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1355 $exclude.= $subfield->[0];
1357 $exclude='['.$exclude.']';
1358 # add subfields in $field not included in @record_to
1359 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1360 foreach my $subfield (@restore) {
1361 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1363 $marcrecord->delete_field($field);
1364 $marcrecord->insert_grouped_field($field_to);
1365 $update=1;
1367 }#for each tag
1368 }#foreach tagfield
1369 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1370 my $biblionumber;
1371 if ($bibliotag<10){
1372 $biblionumber=$marcrecord->field($bibliotag)->data;
1374 else {
1375 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1377 unless ($biblionumber){
1378 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1379 next;
1381 if ($update==1){
1382 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1383 $counteditedbiblio++;
1384 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1386 }#foreach $marc
1387 return $counteditedbiblio;
1388 # now, find every other authority linked with this authority
1389 # now, find every other authority linked with this authority
1390 # my $oConnection=C4::Context->Zconn("authorityserver");
1391 # my $query;
1392 # # att 9210 Auth-Internal-authtype
1393 # # att 9220 Auth-Internal-LN
1394 # # ccl.properties to add for authorities
1395 # $query= "= ".$mergefrom;
1396 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1397 # my $count=$oResult->size() if ($oResult);
1398 # my @reccache;
1399 # my $z=0;
1400 # while ( $z<$count ) {
1401 # my $rec;
1402 # $rec=$oResult->record($z);
1403 # my $marcdata = $rec->raw();
1404 # push @reccache, $marcdata;
1405 # $z++;
1407 # $oResult->destroy();
1408 # foreach my $marc(@reccache){
1409 # my $update;
1410 # my $marcrecord;
1411 # $marcrecord = MARC::File::USMARC::decode($marc);
1412 # foreach my $tagfield (@tags_using_authtype){
1413 # $tagfield=substr($tagfield,0,3);
1414 # my @tags = $marcrecord->field($tagfield);
1415 # foreach my $tag (@tags){
1416 # my $tagsubs=$tag->subfield("9");
1417 # #warn "$tagfield:$tagsubs:$mergefrom";
1418 # if ($tagsubs== $mergefrom) {
1419 # $tag->update("9" =>$mergeto);
1420 # foreach my $subfield (@record_to) {
1421 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1422 # $tag->update($subfield->[0] =>$subfield->[1]);
1423 # }#for $subfield
1425 # $marcrecord->delete_field($tag);
1426 # $marcrecord->add_fields($tag);
1427 # $update=1;
1428 # }#for each tag
1429 # }#foreach tagfield
1430 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1431 # if ($update==1){
1432 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1435 # }#foreach $marc
1436 }#sub
1438 =head2 get_auth_type_location
1440 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1442 Get the tag and subfield used to store the heading type
1443 for indexing purposes. The C<$auth_type> parameter is
1444 optional; if it is not supplied, assume ''.
1446 This routine searches the MARC authority framework
1447 for the tag and subfield whose kohafield is
1448 C<auth_header.authtypecode>; if no such field is
1449 defined in the framework, default to the hardcoded value
1450 specific to the MARC format.
1452 =cut
1454 sub get_auth_type_location {
1455 my $auth_type_code = @_ ? shift : '';
1457 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1458 if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1459 return ($tag, $subfield);
1460 } else {
1461 if (C4::Context->preference('marcflavour') eq "MARC21") {
1462 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1463 } else {
1464 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1469 END { } # module clean-up code here (global destructor)
1472 __END__
1474 =head1 AUTHOR
1476 Koha Development Team <http://koha-community.org/>
1478 Paul POULAIN paul.poulain@free.fr
1480 =cut