Bug 6755 follow up
[koha.git] / C4 / AuthoritiesMarc.pm
blob0164c8daa3d3437c9ec611dbe30e69ae6fa3f48a
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; FIXME - Bug 2505
21 use C4::Context;
22 use C4::Koha;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
28 use C4::Charset;
29 use C4::Log;
31 use vars qw($VERSION @ISA @EXPORT);
33 BEGIN {
34 # set the version for version checking
35 $VERSION = 3.01;
37 require Exporter;
38 @ISA = qw(Exporter);
39 @EXPORT = qw(
40 &GetTagsLabels
41 &GetAuthType
42 &GetAuthTypeCode
43 &GetAuthMARCFromKohaField
44 &AUTHhtml2marc
46 &AddAuthority
47 &ModAuthority
48 &DelAuthority
49 &GetAuthority
50 &GetAuthorityXML
52 &CountUsage
53 &CountUsageChildren
54 &SearchAuthorities
56 &BuildSummary
57 &BuildUnimarcHierarchies
58 &BuildUnimarcHierarchy
60 &merge
61 &FindDuplicateAuthority
63 &GuessAuthTypeCode
64 &GuessAuthId
69 =head1 NAME
71 C4::AuthoritiesMarc
73 =head2 GetAuthMARCFromKohaField
75 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
77 returns tag and subfield linked to kohafield
79 Comment :
80 Suppose Kohafield is only linked to ONE subfield
82 =cut
84 sub GetAuthMARCFromKohaField {
85 #AUTHfind_marc_from_kohafield
86 my ( $kohafield,$authtypecode ) = @_;
87 my $dbh=C4::Context->dbh;
88 return 0, 0 unless $kohafield;
89 $authtypecode="" unless $authtypecode;
90 my $marcfromkohafield;
91 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
92 $sth->execute($kohafield,$authtypecode);
93 my ($tagfield,$tagsubfield) = $sth->fetchrow;
95 return ($tagfield,$tagsubfield);
98 =head2 SearchAuthorities
100 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or,
101 $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
103 returns ref to array result and count of results returned
105 =cut
107 sub SearchAuthorities {
108 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
109 # warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
110 my $dbh=C4::Context->dbh;
111 if (C4::Context->preference('NoZebra')) {
114 # build the query
116 my $query;
117 my @auths=split / /,$authtypecode ;
118 foreach my $auth (@auths){
119 $query .="AND auth_type= $auth ";
121 $query =~ s/^AND //;
122 my $dosearch;
123 for(my $i = 0 ; $i <= $#{$value} ; $i++)
125 if (@$value[$i]){
126 if (@$tags[$i] =~/mainentry|mainmainentry/) {
127 $query .= qq( AND @$tags[$i] );
128 } else {
129 $query .=" AND ";
131 if (@$operator[$i] eq 'is') {
132 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
133 }elsif (@$operator[$i] eq "="){
134 $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
135 }elsif (@$operator[$i] eq "start"){
136 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
137 } else {
138 $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
140 $dosearch=1;
141 }#if value
144 # do the query (if we had some search term
146 if ($dosearch) {
147 # warn "QUERY : $query";
148 my $result = C4::Search::NZanalyse($query,'authorityserver');
149 # warn "result : $result";
150 my %result;
151 foreach (split /;/,$result) {
152 my ($authid,$title) = split /,/,$_;
153 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
154 # and we don't want to get only 1 result for each of them !!!
155 # hint & speed improvement : we can order without reading the record
156 # so order, and read records only for the requested page !
157 $result{$title.$authid}=$authid;
159 # sort the hash and return the same structure as GetRecords (Zebra querying)
160 my @listresult = ();
161 my $numbers=0;
162 if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
163 foreach my $key (sort {$b cmp $a} (keys %result)) {
164 push @listresult, $result{$key};
165 # warn "push..."$#finalresult;
166 $numbers++;
168 } else { # sort by mainmainentry ASC
169 foreach my $key (sort (keys %result)) {
170 push @listresult, $result{$key};
171 # warn "push..."$#finalresult;
172 $numbers++;
175 # limit the $results_per_page to result size if it's more
176 $length = $numbers-$offset if $numbers < ($offset+$length);
177 # for the requested page, replace authid by the complete record
178 # speed improvement : avoid reading too much things
179 my @finalresult;
180 for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
181 # $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
182 my $separator=C4::Context->preference('authoritysep');
183 my $authrecord =GetAuthority($listresult[$counter]);
184 my $authid=$listresult[$counter];
185 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
186 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
187 my $sth = $dbh->prepare($query_auth_tag);
188 $sth->execute($authtypecode);
189 my $auth_tag_to_report = $sth->fetchrow;
190 my %newline;
191 $newline{used}=CountUsage($authid);
192 $newline{summary} = $summary;
193 $newline{authid} = $authid;
194 $newline{even} = $counter % 2;
195 push @finalresult, \%newline;
197 return (\@finalresult, $numbers);
198 } else {
199 return;
201 } else {
202 my $query;
203 my $attr;
204 # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
205 # the authtypecode. Then, search on $a of this tag_to_report
206 # also store main entry MARC tag, to extract it at end of search
207 my $mainentrytag;
208 ##first set the authtype search and may be multiple authorities
209 my $n=0;
210 my @authtypecode;
211 my @auths=split / /,$authtypecode ;
212 foreach my $auth (@auths){
213 $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
214 push @authtypecode ,$auth;
215 $n++;
217 if ($n>1){
218 while ($n>1){$query= "\@or ".$query;$n--;}
221 my $dosearch;
222 my $and=" \@and " ;
223 my $q2;
224 my $attr_cnt = 0;
225 for(my $i = 0 ; $i <= $#{$value} ; $i++)
227 if (@$value[$i]){
228 if (@$tags[$i] eq "mainmainentry") {
230 $attr =" \@attr 1=Heading-Main ";
232 }elsif (@$tags[$i] eq "mainentry") {
233 $attr =" \@attr 1=Heading ";
234 }else{
235 $attr =" \@attr 1=Any ";
237 if (@$operator[$i] eq 'is') {
238 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
239 }elsif (@$operator[$i] eq "="){
240 $attr.=" \@attr 4=107 "; #Number Exact match
241 }elsif (@$operator[$i] eq "start"){
242 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
243 } else {
244 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
246 @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value
247 $attr =$attr."\"".@$value[$i]."\"";
248 $q2 .=$attr;
249 $dosearch=1;
250 ++$attr_cnt;
251 }#if value
253 ##Add how many queries generated
254 if ($query=~/\S+/){
255 $query= $and x $attr_cnt . $query . $q2;
256 } else {
257 $query= $q2;
259 ## Adding order
260 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
261 my $orderstring= ($sortby eq "HeadingAsc"?
262 '@attr 7=1 @attr 1=Heading 0'
264 $sortby eq "HeadingDsc"?
265 '@attr 7=2 @attr 1=Heading 0'
268 $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
269 $query="\@or $orderstring $query" if $orderstring;
271 $offset=0 unless $offset;
272 my $counter = $offset;
273 $length=10 unless $length;
274 my @oAuth;
275 my $i;
276 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
277 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
278 my $oAResult;
279 $oAResult= $oAuth[0]->search($Anewq) ;
280 while (($i = ZOOM::event(\@oAuth)) != 0) {
281 my $ev = $oAuth[$i-1]->last_event();
282 last if $ev == ZOOM::Event::ZEND;
284 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
285 if ($error) {
286 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
287 goto NOLUCK;
290 my $nbresults;
291 $nbresults=$oAResult->size();
292 my $nremains=$nbresults;
293 my @result = ();
294 my @finalresult = ();
296 if ($nbresults>0){
298 ##Find authid and linkid fields
299 ##we may be searching multiple authoritytypes.
300 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
301 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
302 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
303 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
305 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
306 my $rec=$oAResult->record($counter);
307 my $marcdata=$rec->raw();
308 my $authrecord;
309 my $separator=C4::Context->preference('authoritysep');
310 $authrecord = MARC::File::USMARC::decode($marcdata);
311 my $authid=$authrecord->field('001')->data();
312 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
313 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
314 my $sth = $dbh->prepare($query_auth_tag);
315 $sth->execute($authtypecode);
316 my $auth_tag_to_report = $sth->fetchrow;
317 my $reported_tag;
318 my $mainentry = $authrecord->field($auth_tag_to_report);
319 if ($mainentry) {
320 foreach ($mainentry->subfields()) {
321 $reported_tag .='$'.$_->[0].$_->[1];
324 my %newline;
325 $newline{summary} = $summary;
326 $newline{authid} = $authid;
327 $newline{even} = $counter % 2;
328 $newline{reported_tag} = $reported_tag;
329 $counter++;
330 push @finalresult, \%newline;
331 }## while counter
333 for (my $z=0; $z<@finalresult; $z++){
334 my $count=CountUsage($finalresult[$z]{authid});
335 $finalresult[$z]{used}=$count;
336 }# all $z's
338 }## if nbresult
339 NOLUCK:
340 # $oAResult->destroy();
341 # $oAuth[0]->destroy();
343 return (\@finalresult, $nbresults);
347 =head2 CountUsage
349 $count= &CountUsage($authid)
351 counts Usage of Authid in bibliorecords.
353 =cut
355 sub CountUsage {
356 my ($authid) = @_;
357 if (C4::Context->preference('NoZebra')) {
358 # Read the index Koha-Auth-Number for this authid and count the lines
359 my $result = C4::Search::NZanalyse("an=$authid");
360 my @tab = split /;/,$result;
361 return scalar @tab;
362 } else {
363 ### ZOOM search here
364 my $query;
365 $query= "an=".$authid;
366 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
367 if ($err) {
368 warn "Error: $err from search $query";
369 $result = 0;
372 return $result;
376 =head2 CountUsageChildren
378 $count= &CountUsageChildren($authid)
380 counts Usage of narrower terms of Authid in bibliorecords.
382 =cut
384 sub CountUsageChildren {
385 my ($authid) = @_;
388 =head2 GetAuthTypeCode
390 $authtypecode= &GetAuthTypeCode($authid)
392 returns authtypecode of an authid
394 =cut
396 sub GetAuthTypeCode {
397 #AUTHfind_authtypecode
398 my ($authid) = @_;
399 my $dbh=C4::Context->dbh;
400 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
401 $sth->execute($authid);
402 my $authtypecode = $sth->fetchrow;
403 return $authtypecode;
406 =head2 GuessAuthTypeCode
408 my $authtypecode = GuessAuthTypeCode($record);
410 Get the record and tries to guess the adequate authtypecode from its content.
412 =cut
414 sub GuessAuthTypeCode {
415 my ($record) = @_;
416 return unless defined $record;
417 my $heading_fields = {
418 "MARC21"=>{
419 '100'=>{authtypecode=>'PERSO_NAME'},
420 '110'=>{authtypecode=>'CORPO_NAME'},
421 '111'=>{authtypecode=>'MEETI_NAME'},
422 '130'=>{authtypecode=>'UNIF_TITLE'},
423 '148'=>{authtypecode=>'CHRON_TERM'},
424 '150'=>{authtypecode=>'TOPIC_TERM'},
425 '151'=>{authtypecode=>'GEOGR_NAME'},
426 '155'=>{authtypecode=>'GENRE/FORM'},
427 '180'=>{authtypecode=>'GEN_SUBDIV'},
428 '181'=>{authtypecode=>'GEO_SUBDIV'},
429 '182'=>{authtypecode=>'CHRON_SUBD'},
430 '185'=>{authtypecode=>'FORM_SUBD'},
432 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
433 # 604 with embedded 700, 701, 702
434 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
435 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
436 #216 Trademark 716 [Reserved for future use]
437 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
438 #230 Title 500 4-- with embedded 500 605
439 #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
440 #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
441 #250 Topical subject 606
442 #260 Place access 620
443 #280 Form, genre or physical characteristics 608
446 # Could also be represented with :
447 #leader position 9
448 #a = personal name entry
449 #b = corporate name entry
450 #c = territorial or geographical name
451 #d = trademark
452 #e = family name
453 #f = uniform title
454 #g = collective uniform title
455 #h = name/title
456 #i = name/collective uniform title
457 #j = topical subject
458 #k = place access
459 #l = form, genre or physical characteristics
460 "UNIMARC"=>{
461 '200'=>{authtypecode=>'NP'},
462 '210'=>{authtypecode=>'CO'},
463 '215'=>{authtypecode=>'SNG'},
464 '216'=>{authtypecode=>'TM'},
465 '220'=>{authtypecode=>'FAM'},
466 '230'=>{authtypecode=>'TU'},
467 '235'=>{authtypecode=>'CO_UNI_TI'},
468 '240'=>{authtypecode=>'SAUTTIT'},
469 '245'=>{authtypecode=>'NAME_COL'},
470 '250'=>{authtypecode=>'SNC'},
471 '260'=>{authtypecode=>'PA'},
472 '280'=>{authtypecode=>'GENRE/FORM'},
475 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
476 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
478 return;
481 =head2 GuessAuthId
483 my $authtid = GuessAuthId($record);
485 Get the record and tries to guess the adequate authtypecode from its content.
487 =cut
489 sub GuessAuthId {
490 my ($record) = @_;
491 return unless ($record && $record->field('001'));
492 # my $authtypecode=GuessAuthTypeCode($record);
493 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
494 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
495 # else {return $record->field($tag)->data}
496 return $record->field('001')->data;
499 =head2 GetTagsLabels
501 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
503 returns a ref to hashref of authorities tag and subfield structure.
505 tagslabel usage :
507 $tagslabel->{$tag}->{$subfield}->{'attribute'}
509 where attribute takes values in :
513 mandatory
514 repeatable
515 authorised_value
516 authtypecode
517 value_builder
518 kohafield
519 seealso
520 hidden
521 isurl
522 link
524 =cut
526 sub GetTagsLabels {
527 my ($forlibrarian,$authtypecode)= @_;
528 my $dbh=C4::Context->dbh;
529 $authtypecode="" unless $authtypecode;
530 my $sth;
531 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
534 # check that authority exists
535 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
536 $sth->execute($authtypecode);
537 my ($total) = $sth->fetchrow;
538 $authtypecode="" unless ($total >0);
539 $sth= $dbh->prepare(
540 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
541 FROM auth_tag_structure
542 WHERE authtypecode=?
543 ORDER BY tagfield"
546 $sth->execute($authtypecode);
547 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
549 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
550 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
551 $res->{$tag}->{tab} = " "; # XXX
552 $res->{$tag}->{mandatory} = $mandatory;
553 $res->{$tag}->{repeatable} = $repeatable;
555 $sth= $dbh->prepare(
556 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
557 FROM auth_subfield_structure
558 WHERE authtypecode=?
559 ORDER BY tagfield,tagsubfield"
561 $sth->execute($authtypecode);
563 my $subfield;
564 my $authorised_value;
565 my $value_builder;
566 my $kohafield;
567 my $seealso;
568 my $hidden;
569 my $isurl;
570 my $link;
572 while (
573 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
574 $mandatory, $repeatable, $authorised_value, $authtypecode,
575 $value_builder, $kohafield, $seealso, $hidden,
576 $isurl, $link )
577 = $sth->fetchrow
580 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
581 $res->{$tag}->{$subfield}->{tab} = $tab;
582 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
583 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
584 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
585 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
586 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
587 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
588 $res->{$tag}->{$subfield}->{seealso} = $seealso;
589 $res->{$tag}->{$subfield}->{hidden} = $hidden;
590 $res->{$tag}->{$subfield}->{isurl} = $isurl;
591 $res->{$tag}->{$subfield}->{link} = $link;
593 return $res;
596 =head2 AddAuthority
598 $authid= &AddAuthority($record, $authid,$authtypecode)
600 Either Create Or Modify existing authority.
601 returns authid of the newly created authority
603 =cut
605 sub AddAuthority {
606 # pass the MARC::Record to this function, and it will create the records in the authority table
607 my ($record,$authid,$authtypecode) = @_;
608 my $dbh=C4::Context->dbh;
609 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
611 # if authid empty => true add, find a new authid number
612 my $format;
613 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
614 $format= 'UNIMARCAUTH';
616 else {
617 $format= 'MARC21';
620 #update date/time to 005 for marc and unimarc
621 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
622 my $f5=$record->field('005');
623 if (!$f5) {
624 $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
626 else {
627 $f5->update($time.".0");
630 SetUTF8Flag($record);
631 if ($format eq "MARC21") {
632 if (!$record->leader) {
633 $record->leader($leader);
635 if (!$record->field('003')) {
636 $record->insert_fields_ordered(
637 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
640 my $date=POSIX::strftime("%y%m%d",localtime);
641 if (!$record->field('008')) {
642 $record->insert_fields_ordered(
643 MARC::Field->new('008',$date."|||a|||||| | ||| d")
646 if (!$record->field('040')) {
647 $record->insert_fields_ordered(
648 MARC::Field->new('040','','',
649 'a' => C4::Context->preference('MARCOrgCode'),
650 'c' => C4::Context->preference('MARCOrgCode')
656 if ($format eq "UNIMARCAUTH") {
657 $record->leader(" nx j22 ") unless ($record->leader());
658 my $date=POSIX::strftime("%Y%m%d",localtime);
659 if (my $string=$record->subfield('100',"a")){
660 $string=~s/fre50/frey50/;
661 $record->field('100')->update('a'=>$string);
663 elsif ($record->field('100')){
664 $record->field('100')->update('a'=>$date."afrey50 ba0");
665 } else {
666 $record->append_fields(
667 MARC::Field->new('100',' ',' '
668 ,'a'=>$date."afrey50 ba0")
672 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
673 if (!$authid and $format eq "MARC21") {
674 # only need to do this fix when modifying an existing authority
675 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
677 if (my $field=$record->field($auth_type_tag)){
678 $field->update($auth_type_subfield=>$authtypecode);
680 else {
681 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
684 my $auth_exists=0;
685 my $oldRecord;
686 if (!$authid) {
687 my $sth=$dbh->prepare("select max(authid) from auth_header");
688 $sth->execute;
689 ($authid)=$sth->fetchrow;
690 $authid=$authid+1;
691 ##Insert the recordID in MARC record
692 unless ($record->field('001') && $record->field('001')->data() eq $authid){
693 $record->delete_field($record->field('001'));
694 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
696 } else {
697 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
698 # warn "auth_exists = $auth_exists";
700 if ($auth_exists>0){
701 $oldRecord=GetAuthority($authid);
702 $record->add_fields('001',$authid) unless ($record->field('001'));
703 # warn "\n\n\n enregistrement".$record->as_formatted;
704 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
705 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
706 $sth->finish;
708 else {
709 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
710 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
711 $sth->finish;
712 logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
714 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
715 return ($authid);
719 =head2 DelAuthority
721 $authid= &DelAuthority($authid)
723 Deletes $authid
725 =cut
727 sub DelAuthority {
728 my ($authid) = @_;
729 my $dbh=C4::Context->dbh;
731 logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
732 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
733 my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
734 $sth->execute($authid);
737 sub ModAuthority {
738 my ($authid,$record,$authtypecode,$merge)=@_;
739 my $dbh=C4::Context->dbh;
740 #Now rewrite the $record to table with an add
741 my $oldrecord=GetAuthority($authid);
742 $authid=AddAuthority($record,$authid,$authtypecode);
744 ### If a library thinks that updating all biblios is a long process and wishes to leave that to a cron job to use merge_authotities.p
745 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
746 ### the $merge flag is now depreceated and will be removed at code cleaning
747 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
748 &merge($authid,$oldrecord,$authid,$record);
749 } else {
750 # save the file in tmp/modified_authorities
751 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
752 unless (opendir(DIR,"$cgidir")) {
753 $cgidir = C4::Context->intranetdir."/";
754 closedir(DIR);
757 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
758 open AUTH, "> $filename";
759 print AUTH $authid;
760 close AUTH;
762 logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
763 return $authid;
766 =head2 GetAuthorityXML
768 $marcxml= &GetAuthorityXML( $authid)
770 returns xml form of record $authid
772 =cut
774 sub GetAuthorityXML {
775 # Returns MARC::XML of the authority passed in parameter.
776 my ( $authid ) = @_;
777 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
778 my $dbh=C4::Context->dbh;
779 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
780 $sth->execute($authid);
781 my ($marcxml)=$sth->fetchrow;
782 return $marcxml;
784 else {
785 # for MARC21, call GetAuthority instead of
786 # getting the XML directly since we may
787 # need to fix up the location of the authority
788 # code -- note that this is reasonably safe
789 # because GetAuthorityXML is used only by the
790 # indexing processes like zebraqueue_start.pl
791 my $record = GetAuthority($authid);
792 return $record->as_xml_record('MARC21');
796 =head2 GetAuthority
798 $record= &GetAuthority( $authid)
800 Returns MARC::Record of the authority passed in parameter.
802 =cut
804 sub GetAuthority {
805 my ($authid)=@_;
806 my $dbh=C4::Context->dbh;
807 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
808 $sth->execute($authid);
809 my ($authtypecode, $marcxml) = $sth->fetchrow;
810 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
811 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
812 return undef if ($@);
813 $record->encoding('UTF-8');
814 if (C4::Context->preference("marcflavour") eq "MARC21") {
815 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
816 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
818 return ($record);
821 =head2 GetAuthType
823 $result = &GetAuthType($authtypecode)
825 If the authority type specified by C<$authtypecode> exists,
826 returns a hashref of the type's fields. If the type
827 does not exist, returns undef.
829 =cut
831 sub GetAuthType {
832 my ($authtypecode) = @_;
833 my $dbh=C4::Context->dbh;
834 my $sth;
835 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
836 # type (FIXME but why?)
837 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
838 $sth->execute($authtypecode);
839 if (my $res = $sth->fetchrow_hashref) {
840 return $res;
843 return;
847 sub AUTHhtml2marc {
848 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
849 my $dbh=C4::Context->dbh;
850 my $prevtag = -1;
851 my $record = MARC::Record->new();
852 #---- TODO : the leader is missing
854 # my %subfieldlist=();
855 my $prevvalue; # if tag <10
856 my $field; # if tag >=10
857 for (my $i=0; $i< @$rtags; $i++) {
858 # rebuild MARC::Record
859 if (@$rtags[$i] ne $prevtag) {
860 if ($prevtag < 10) {
861 if ($prevvalue) {
862 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
864 } else {
865 if ($field) {
866 $record->add_fields($field);
869 $indicators{@$rtags[$i]}.=' ';
870 if (@$rtags[$i] <10) {
871 $prevvalue= @$rvalues[$i];
872 undef $field;
873 } else {
874 undef $prevvalue;
875 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
877 $prevtag = @$rtags[$i];
878 } else {
879 if (@$rtags[$i] <10) {
880 $prevvalue=@$rvalues[$i];
881 } else {
882 if (length(@$rvalues[$i])>0) {
883 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
886 $prevtag= @$rtags[$i];
889 # the last has not been included inside the loop... do it now !
890 $record->add_fields($field) if $field;
891 return $record;
894 =head2 FindDuplicateAuthority
896 $record= &FindDuplicateAuthority( $record, $authtypecode)
898 return $authid,Summary if duplicate is found.
900 Comments : an improvement would be to return All the records that match.
902 =cut
904 sub FindDuplicateAuthority {
906 my ($record,$authtypecode)=@_;
907 # warn "IN for ".$record->as_formatted;
908 my $dbh = C4::Context->dbh;
909 # warn "".$record->as_formatted;
910 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
911 $sth->execute($authtypecode);
912 my ($auth_tag_to_report) = $sth->fetchrow;
913 $sth->finish;
914 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
915 # build a request for SearchAuthorities
916 my $query='at='.$authtypecode.' ';
917 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
918 if ($record->field($auth_tag_to_report)) {
919 foreach ($record->field($auth_tag_to_report)->subfields()) {
920 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
923 my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
924 # there is at least 1 result => return the 1st one
925 if (!defined $error && @{$results} ) {
926 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
927 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
929 # no result, returns nothing
930 return;
933 =head2 BuildSummary
935 $text= &BuildSummary( $record, $authid, $authtypecode)
937 return HTML encoded Summary
939 Comment : authtypecode can be infered from both record and authid.
940 Moreover, authid can also be inferred from $record.
941 Would it be interesting to delete those things.
943 =cut
945 sub BuildSummary{
946 ## give this a Marc record to return summary
947 my ($record,$authid,$authtypecode)=@_;
948 my $dbh=C4::Context->dbh;
949 my $summary;
950 # handle $authtypecode is NULL or eq ""
951 if ($authtypecode) {
952 my $authref = GetAuthType($authtypecode);
953 $summary = $authref->{summary};
955 # FIXME: should use I18N.pm
956 my %language;
957 $language{'fre'}="Français";
958 $language{'eng'}="Anglais";
959 $language{'ger'}="Allemand";
960 $language{'ita'}="Italien";
961 $language{'spa'}="Espagnol";
962 my %thesaurus;
963 $thesaurus{'1'}="Peuples";
964 $thesaurus{'2'}="Anthroponymes";
965 $thesaurus{'3'}="Oeuvres";
966 $thesaurus{'4'}="Chronologie";
967 $thesaurus{'5'}="Lieux";
968 $thesaurus{'6'}="Sujets";
969 #thesaurus a remplir
970 my @fields = $record->fields();
971 my $reported_tag;
972 # if the library has a summary defined, use it. Otherwise, build a standard one
973 # FIXME - it appears that the summary field in the authority frameworks
974 # can work as a display template. However, this doesn't
975 # suit the MARC21 version, so for now the "templating"
976 # feature will be enabled only for UNIMARC for backwards
977 # compatibility.
978 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
979 my @fields = $record->fields();
980 # $reported_tag = '$9'.$result[$counter];
981 my @stringssummary;
982 foreach my $field (@fields) {
983 my $tag = $field->tag();
984 my $tagvalue = $field->as_string();
985 my $localsummary= $summary;
986 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
987 if ($tag<10) {
988 if ($tag eq '001') {
989 $reported_tag.='$3'.$field->data();
991 } else {
992 my @subf = $field->subfields;
993 for my $i (0..$#subf) {
994 my $subfieldcode = $subf[$i][0];
995 my $subfieldvalue = $subf[$i][1];
996 my $tagsubf = $tag.$subfieldcode;
997 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1000 push @stringssummary, $localsummary if ($localsummary ne $summary);
1002 my $resultstring;
1003 $resultstring = join(" -- ",@stringssummary);
1004 $resultstring =~ s/\[(.*?)\]//g;
1005 $resultstring =~ s/\n/<br>/g;
1006 $summary = $resultstring;
1007 } else {
1008 my $heading;
1009 my $altheading;
1010 my $seealso;
1011 my $broaderterms;
1012 my $narrowerterms;
1013 my $see;
1014 my $seeheading;
1015 my $notes;
1016 my @fields = $record->fields();
1017 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1018 # construct UNIMARC summary, that is quite different from MARC21 one
1019 # accepted form
1020 foreach my $field ($record->field('2..')) {
1021 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1023 # rejected form(s)
1024 foreach my $field ($record->field('3..')) {
1025 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1027 foreach my $field ($record->field('4..')) {
1028 if ($field->subfield('2')) {
1029 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1030 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1033 # see :
1034 foreach my $field ($record->field('5..')) {
1036 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1037 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1038 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1039 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1040 } elsif ($field->subfield('a')) {
1041 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1044 # // form
1045 foreach my $field ($record->field('7..')) {
1046 my $lang = substr($field->subfield('8'),3,3);
1047 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1049 $broaderterms =~s/-- \n$//;
1050 $narrowerterms =~s/-- \n$//;
1051 $seealso =~s/-- \n$//;
1052 $see =~s/-- \n$//;
1053 $summary = $heading."<br />".($notes?"$notes <br />":"");
1054 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1055 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1056 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1057 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1058 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1059 } else {
1060 # construct MARC21 summary
1061 # FIXME - looping over 1XX is questionable
1062 # since MARC21 authority should have only one 1XX
1063 foreach my $field ($record->field('1..')) {
1064 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1065 # in MARC21 -- purely local tags really ought to be
1066 # 9XX
1067 if ($record->field('100')) {
1068 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1069 } elsif ($record->field('110')) {
1070 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1071 } elsif ($record->field('111')) {
1072 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1073 } elsif ($record->field('130')) {
1074 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1075 } elsif ($record->field('148')) {
1076 $heading.= $field->as_string('abvxyz68');
1077 } elsif ($record->field('150')) {
1078 $heading.= $field->as_string('abvxyz68');
1079 #$heading.= $field->as_formatted();
1080 my $tag=$field->tag();
1081 $heading=~s /^$tag//g;
1082 $heading =~s /\_/\$/g;
1083 } elsif ($record->field('151')) {
1084 $heading.= $field->as_string('avxyz68');
1085 } elsif ($record->field('155')) {
1086 $heading.= $field->as_string('abvxyz68');
1087 } elsif ($record->field('180')) {
1088 $heading.= $field->as_string('vxyz68');
1089 } elsif ($record->field('181')) {
1090 $heading.= $field->as_string('vxyz68');
1091 } elsif ($record->field('182')) {
1092 $heading.= $field->as_string('vxyz68');
1093 } elsif ($record->field('185')) {
1094 $heading.= $field->as_string('vxyz68');
1095 } else {
1096 $heading.= $field->as_string();
1098 } #See From
1099 foreach my $field ($record->field('4..')) {
1100 $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1101 } #See Also
1102 foreach my $field ($record->field('5..')) {
1103 $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1105 $summary .= ": " if $summary;
1106 $summary.=$heading.$seeheading.$altheading;
1109 return $summary;
1112 =head2 BuildUnimarcHierarchies
1114 $text= &BuildUnimarcHierarchies( $authid, $force)
1116 return text containing trees for hierarchies
1117 for them to be stored in auth_header
1119 Example of text:
1120 122,1314,2452;1324,2342,3,2452
1122 =cut
1124 sub BuildUnimarcHierarchies{
1125 my $authid = shift @_;
1126 # warn "authid : $authid";
1127 my $force = shift @_;
1128 my @globalresult;
1129 my $dbh=C4::Context->dbh;
1130 my $hierarchies;
1131 my $data = GetHeaderAuthority($authid);
1132 if ($data->{'authtrees'} and not $force){
1133 return $data->{'authtrees'};
1134 # } elsif ($data->{'authtrees'}){
1135 # $hierarchies=$data->{'authtrees'};
1136 } else {
1137 my $record = GetAuthority($authid);
1138 my $found;
1139 return unless $record;
1140 foreach my $field ($record->field('5..')){
1141 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1142 my $subfauthid=_get_authid_subfield($field);
1143 next if ($subfauthid eq $authid);
1144 my $parentrecord = GetAuthority($subfauthid);
1145 my $localresult=$hierarchies;
1146 my $trees;
1147 $trees = BuildUnimarcHierarchies($subfauthid);
1148 my @trees;
1149 if ($trees=~/;/){
1150 @trees = split(/;/,$trees);
1151 } else {
1152 push @trees, $trees;
1154 foreach (@trees){
1155 $_.= ",$authid";
1157 @globalresult = (@globalresult,@trees);
1158 $found=1;
1160 $hierarchies=join(";",@globalresult);
1162 #Unless there is no ancestor, I am alone.
1163 $hierarchies="$authid" unless ($hierarchies);
1165 AddAuthorityTrees($authid,$hierarchies);
1166 return $hierarchies;
1169 =head2 BuildUnimarcHierarchy
1171 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1173 return a hashref in order to display hierarchy for record and final Authid $authid
1175 "loopparents"
1176 "loopchildren"
1177 "class"
1178 "loopauthid"
1179 "current_value"
1180 "value"
1182 "ifparents"
1183 "ifchildren"
1184 Those two latest ones should disappear soon.
1186 =cut
1188 sub BuildUnimarcHierarchy{
1189 my $record = shift @_;
1190 my $class = shift @_;
1191 my $authid_constructed = shift @_;
1192 return undef unless ($record);
1193 my $authid=$record->field('001')->data();
1194 my %cell;
1195 my $parents=""; my $children="";
1196 my (@loopparents,@loopchildren);
1197 foreach my $field ($record->field('5..')){
1198 my $subfauthid=_get_authid_subfield($field);
1199 if ($subfauthid && $field->subfield('5') && $field->subfield('a')){
1200 if ($field->subfield('5') eq 'h'){
1201 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1203 elsif ($field->subfield('5') eq 'g'){
1204 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1206 # brothers could get in there with an else
1209 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1210 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1211 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1212 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1213 $cell{"class"}=$class;
1214 $cell{"loopauthid"}=$authid;
1215 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1216 $cell{"value"}=$record->subfield('2..',"a");
1217 return \%cell;
1220 sub _get_authid_subfield{
1221 my ($field)=@_;
1222 return $field->subfield('9')||$field->subfield('3');
1224 =head2 GetHeaderAuthority
1226 $ref= &GetHeaderAuthority( $authid)
1228 return a hashref in order auth_header table data
1230 =cut
1232 sub GetHeaderAuthority{
1233 my $authid = shift @_;
1234 my $sql= "SELECT * from auth_header WHERE authid = ?";
1235 my $dbh=C4::Context->dbh;
1236 my $rq= $dbh->prepare($sql);
1237 $rq->execute($authid);
1238 my $data= $rq->fetchrow_hashref;
1239 return $data;
1242 =head2 AddAuthorityTrees
1244 $ref= &AddAuthorityTrees( $authid, $trees)
1246 return success or failure
1248 =cut
1250 sub AddAuthorityTrees{
1251 my $authid = shift @_;
1252 my $trees = shift @_;
1253 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1254 my $dbh=C4::Context->dbh;
1255 my $rq= $dbh->prepare($sql);
1256 return $rq->execute($trees,$authid);
1259 =head2 merge
1261 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1263 Could add some feature : Migrating from a typecode to an other for instance.
1264 Then we should add some new parameter : bibliotargettag, authtargettag
1266 =cut
1268 sub merge {
1269 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1270 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1271 my $dbh=C4::Context->dbh;
1272 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1273 my $authtypecodeto = GetAuthTypeCode($mergeto);
1274 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1275 # return if authority does not exist
1276 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1277 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1278 # search the tag to report
1279 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1280 $sth->execute($authtypecodefrom);
1281 my ($auth_tag_to_report_from) = $sth->fetchrow;
1282 $sth->execute($authtypecodeto);
1283 my ($auth_tag_to_report_to) = $sth->fetchrow;
1285 my @record_to;
1286 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1287 my @record_from;
1288 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1290 my @reccache;
1291 # search all biblio tags using this authority.
1292 #Getting marcbiblios impacted by the change.
1293 if (C4::Context->preference('NoZebra')) {
1294 #nozebra way
1295 my $dbh=C4::Context->dbh;
1296 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1297 $rq->execute;
1298 while (my $biblionumbers=$rq->fetchrow){
1299 my @biblionumbers=split /;/,$biblionumbers;
1300 foreach (@biblionumbers) {
1301 if ($_=~/(\d+),.*/) {
1302 my $marc=GetMarcBiblio($1);
1303 push @reccache,$marc;
1307 } else {
1308 #zebra connection
1309 my $oConnection=C4::Context->Zconn("biblioserver",0);
1310 my $oldSyntax = $oConnection->option("preferredRecordSyntax");
1311 $oConnection->option("preferredRecordSyntax"=>"XML");
1312 my $query;
1313 $query= "an=".$mergefrom;
1314 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1315 my $count = 0;
1316 if ($oResult) {
1317 $count=$oResult->size();
1319 my $z=0;
1320 while ( $z<$count ) {
1321 my $rec;
1322 $rec=$oResult->record($z);
1323 my $marcdata = $rec->raw();
1324 push @reccache, $marcdata;
1325 $z++;
1327 $oResult->destroy();
1328 $oConnection->option("preferredRecordSyntax"=>$oldSyntax);
1330 #warn scalar(@reccache)." biblios to update";
1331 # Get All candidate Tags for the change
1332 # (This will reduce the search scope in marc records).
1333 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1334 $sth->execute($authtypecodefrom);
1335 my @tags_using_authtype;
1336 while (my ($tagfield) = $sth->fetchrow) {
1337 push @tags_using_authtype,$tagfield ;
1339 my $tag_to=0;
1340 if ($authtypecodeto ne $authtypecodefrom){
1341 # If many tags, take the first
1342 $sth->execute($authtypecodeto);
1343 $tag_to=$sth->fetchrow;
1344 #warn $tag_to;
1346 # BulkEdit marc records
1347 # May be used as a template for a bulkedit field
1348 foreach my $marcrecord(@reccache){
1349 my $update;
1350 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1351 foreach my $tagfield (@tags_using_authtype){
1352 # warn "tagfield : $tagfield ";
1353 foreach my $field ($marcrecord->field($tagfield)){
1354 my $auth_number=$field->subfield("9");
1355 my $tag=$field->tag();
1356 if ($auth_number==$mergefrom) {
1357 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1358 my $exclude='9';
1359 foreach my $subfield (@record_to) {
1360 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1361 $exclude.= $subfield->[0];
1363 $exclude='['.$exclude.']';
1364 # add subfields in $field not included in @record_to
1365 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1366 foreach my $subfield (@restore) {
1367 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1369 $marcrecord->delete_field($field);
1370 $marcrecord->insert_grouped_field($field_to);
1371 $update=1;
1373 }#for each tag
1374 }#foreach tagfield
1375 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1376 my $biblionumber;
1377 if ($bibliotag<10){
1378 $biblionumber=$marcrecord->field($bibliotag)->data;
1380 else {
1381 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1383 unless ($biblionumber){
1384 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1385 next;
1387 if ($update==1){
1388 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1389 $counteditedbiblio++;
1390 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1392 }#foreach $marc
1393 return $counteditedbiblio;
1394 # now, find every other authority linked with this authority
1395 # now, find every other authority linked with this authority
1396 # my $oConnection=C4::Context->Zconn("authorityserver");
1397 # my $query;
1398 # # att 9210 Auth-Internal-authtype
1399 # # att 9220 Auth-Internal-LN
1400 # # ccl.properties to add for authorities
1401 # $query= "= ".$mergefrom;
1402 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1403 # my $count=$oResult->size() if ($oResult);
1404 # my @reccache;
1405 # my $z=0;
1406 # while ( $z<$count ) {
1407 # my $rec;
1408 # $rec=$oResult->record($z);
1409 # my $marcdata = $rec->raw();
1410 # push @reccache, $marcdata;
1411 # $z++;
1413 # $oResult->destroy();
1414 # foreach my $marc(@reccache){
1415 # my $update;
1416 # my $marcrecord;
1417 # $marcrecord = MARC::File::USMARC::decode($marc);
1418 # foreach my $tagfield (@tags_using_authtype){
1419 # $tagfield=substr($tagfield,0,3);
1420 # my @tags = $marcrecord->field($tagfield);
1421 # foreach my $tag (@tags){
1422 # my $tagsubs=$tag->subfield("9");
1423 # #warn "$tagfield:$tagsubs:$mergefrom";
1424 # if ($tagsubs== $mergefrom) {
1425 # $tag->update("9" =>$mergeto);
1426 # foreach my $subfield (@record_to) {
1427 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1428 # $tag->update($subfield->[0] =>$subfield->[1]);
1429 # }#for $subfield
1431 # $marcrecord->delete_field($tag);
1432 # $marcrecord->add_fields($tag);
1433 # $update=1;
1434 # }#for each tag
1435 # }#foreach tagfield
1436 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1437 # if ($update==1){
1438 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1441 # }#foreach $marc
1442 }#sub
1444 =head2 get_auth_type_location
1446 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1448 Get the tag and subfield used to store the heading type
1449 for indexing purposes. The C<$auth_type> parameter is
1450 optional; if it is not supplied, assume ''.
1452 This routine searches the MARC authority framework
1453 for the tag and subfield whose kohafield is
1454 C<auth_header.authtypecode>; if no such field is
1455 defined in the framework, default to the hardcoded value
1456 specific to the MARC format.
1458 =cut
1460 sub get_auth_type_location {
1461 my $auth_type_code = @_ ? shift : '';
1463 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1464 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1465 return ($tag, $subfield);
1466 } else {
1467 if (C4::Context->preference('marcflavour') eq "MARC21") {
1468 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1469 } else {
1470 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1475 END { } # module clean-up code here (global destructor)
1478 __END__
1480 =head1 AUTHOR
1482 Koha Development Team <http://koha-community.org/>
1484 Paul POULAIN paul.poulain@free.fr
1486 =cut