Update README.Debian for koha-common with post-install setup.
[koha.git] / C4 / AuthoritiesMarc.pm
blob5de02c4d43d7f16eba3e8e953dc7adc8e3286dbd
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;
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
43 &AUTHhtml2marc
45 &AddAuthority
46 &ModAuthority
47 &DelAuthority
48 &GetAuthority
49 &GetAuthorityXML
51 &CountUsage
52 &CountUsageChildren
53 &SearchAuthorities
55 &BuildSummary
56 &BuildUnimarcHierarchies
57 &BuildUnimarcHierarchy
59 &merge
60 &FindDuplicateAuthority
62 &GuessAuthTypeCode
63 &GuessAuthId
67 =head2 GetAuthMARCFromKohaField
69 =over 4
71 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
72 returns tag and subfield linked to kohafield
74 Comment :
75 Suppose Kohafield is only linked to ONE subfield
77 =back
79 =cut
81 sub GetAuthMARCFromKohaField {
82 #AUTHfind_marc_from_kohafield
83 my ( $kohafield,$authtypecode ) = @_;
84 my $dbh=C4::Context->dbh;
85 return 0, 0 unless $kohafield;
86 $authtypecode="" unless $authtypecode;
87 my $marcfromkohafield;
88 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
89 $sth->execute($kohafield,$authtypecode);
90 my ($tagfield,$tagsubfield) = $sth->fetchrow;
92 return ($tagfield,$tagsubfield);
95 =head2 SearchAuthorities
97 =over 4
99 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
100 returns ref to array result and count of results returned
102 =back
104 =cut
106 sub SearchAuthorities {
107 my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
108 # warn "CALL : $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 for(my $i = 0 ; $i <= $#{$value} ; $i++)
225 if (@$value[$i]){
226 ##If mainentry search $a tag
227 if (@$tags[$i] eq "mainmainentry") {
229 # FIXME: 'Heading-Main' index not yet defined in zebra
230 # $attr =" \@attr 1=Heading-Main ";
231 $attr =" \@attr 1=Heading ";
233 }elsif (@$tags[$i] eq "mainentry") {
234 $attr =" \@attr 1=Heading ";
235 }else{
236 $attr =" \@attr 1=Any ";
238 if (@$operator[$i] eq 'is') {
239 $attr.=" \@attr 4=1 \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
240 }elsif (@$operator[$i] eq "="){
241 $attr.=" \@attr 4=107 "; #Number Exact match
242 }elsif (@$operator[$i] eq "start"){
243 $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
244 } else {
245 $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
247 $attr =$attr."\"".@$value[$i]."\"";
248 $q2 .=$attr;
249 $dosearch=1;
250 }#if value
252 ##Add how many queries generated
253 if ($query=~/\S+/){
254 $query= $and.$query.$q2
255 } else {
256 $query=$q2;
258 ## Adding order
259 #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
260 my $orderstring= ($sortby eq "HeadingAsc"?
261 '@attr 7=1 @attr 1=Heading 0'
263 $sortby eq "HeadingDsc"?
264 '@attr 7=2 @attr 1=Heading 0'
267 $query=($query?"\@or $orderstring $query":"\@or \@attr 1=_ALLRECORDS \@attr 2=103 '' $orderstring ");
269 $offset=0 unless $offset;
270 my $counter = $offset;
271 $length=10 unless $length;
272 my @oAuth;
273 my $i;
274 $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
275 my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
276 my $oAResult;
277 $oAResult= $oAuth[0]->search($Anewq) ;
278 while (($i = ZOOM::event(\@oAuth)) != 0) {
279 my $ev = $oAuth[$i-1]->last_event();
280 last if $ev == ZOOM::Event::ZEND;
282 my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
283 if ($error) {
284 warn "oAuth error: $errmsg ($error) $addinfo $diagset\n";
285 goto NOLUCK;
288 my $nbresults;
289 $nbresults=$oAResult->size();
290 my $nremains=$nbresults;
291 my @result = ();
292 my @finalresult = ();
294 if ($nbresults>0){
296 ##Find authid and linkid fields
297 ##we may be searching multiple authoritytypes.
298 ## FIXME this assumes that all authid and linkid fields are the same for all authority types
299 # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
300 # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
301 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
303 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
304 my $rec=$oAResult->record($counter);
305 my $marcdata=$rec->raw();
306 my $authrecord;
307 my $separator=C4::Context->preference('authoritysep');
308 $authrecord = MARC::File::USMARC::decode($marcdata);
309 my $authid=$authrecord->field('001')->data();
310 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
311 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
312 my $sth = $dbh->prepare($query_auth_tag);
313 $sth->execute($authtypecode);
314 my $auth_tag_to_report = $sth->fetchrow;
315 my $reported_tag;
316 my $mainentry = $authrecord->field($auth_tag_to_report);
317 if ($mainentry) {
318 foreach ($mainentry->subfields()) {
319 $reported_tag .='$'.$_->[0].$_->[1];
322 my %newline;
323 $newline{summary} = $summary;
324 $newline{authid} = $authid;
325 $newline{even} = $counter % 2;
326 $newline{reported_tag} = $reported_tag;
327 $counter++;
328 push @finalresult, \%newline;
329 }## while counter
331 for (my $z=0; $z<@finalresult; $z++){
332 my $count=CountUsage($finalresult[$z]{authid});
333 $finalresult[$z]{used}=$count;
334 }# all $z's
336 }## if nbresult
337 NOLUCK:
338 # $oAResult->destroy();
339 # $oAuth[0]->destroy();
341 return (\@finalresult, $nbresults);
345 =head2 CountUsage
347 =over 4
349 $count= &CountUsage($authid)
350 counts Usage of Authid in bibliorecords.
352 =back
354 =cut
356 sub CountUsage {
357 my ($authid) = @_;
358 if (C4::Context->preference('NoZebra')) {
359 # Read the index Koha-Auth-Number for this authid and count the lines
360 my $result = C4::Search::NZanalyse("an=$authid");
361 my @tab = split /;/,$result;
362 return scalar @tab;
363 } else {
364 ### ZOOM search here
365 my $query;
366 $query= "an=".$authid;
367 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
368 return ($result);
372 =head2 CountUsageChildren
374 =over 4
376 $count= &CountUsageChildren($authid)
377 counts Usage of narrower terms of Authid in bibliorecords.
379 =back
381 =cut
383 sub CountUsageChildren {
384 my ($authid) = @_;
387 =head2 GetAuthTypeCode
389 =over 4
391 $authtypecode= &GetAuthTypeCode($authid)
392 returns authtypecode of an authid
394 =back
396 =cut
398 sub GetAuthTypeCode {
399 #AUTHfind_authtypecode
400 my ($authid) = @_;
401 my $dbh=C4::Context->dbh;
402 my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
403 $sth->execute($authid);
404 my $authtypecode = $sth->fetchrow;
405 return $authtypecode;
408 =head2 GuessAuthTypeCode
410 =over 4
412 my $authtypecode = GuessAuthTypeCode($record);
414 =back
416 Get the record and tries to guess the adequate authtypecode from its content.
418 =cut
420 sub GuessAuthTypeCode {
421 my ($record) = @_;
422 return unless defined $record;
423 my $heading_fields = {
424 "MARC21"=>{
425 '100'=>{authtypecode=>'PERSO_NAME'},
426 '110'=>{authtypecode=>'CORPO_NAME'},
427 '111'=>{authtypecode=>'MEETI_NAME'},
428 '130'=>{authtypecode=>'UNIF_TITLE'},
429 '148'=>{authtypecode=>'CHRON_TERM'},
430 '150'=>{authtypecode=>'TOPIC_TERM'},
431 '151'=>{authtypecode=>'GEOGR_NAME'},
432 '155'=>{authtypecode=>'GENRE/FORM'},
433 '180'=>{authtypecode=>'GEN_SUBDIV'},
434 '181'=>{authtypecode=>'GEO_SUBDIV'},
435 '182'=>{authtypecode=>'CHRON_SUBD'},
436 '185'=>{authtypecode=>'FORM_SUBD'},
438 #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600
439 # 604 with embedded 700, 701, 702
440 #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
441 #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
442 #216 Trademark 716 [Reserved for future use]
443 #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
444 #230 Title 500 4-- with embedded 500 605
445 #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
446 #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
447 #250 Topical subject 606
448 #260 Place access 620
449 #280 Form, genre or physical characteristics 608
452 # Could also be represented with :
453 #leader position 9
454 #a = personal name entry
455 #b = corporate name entry
456 #c = territorial or geographical name
457 #d = trademark
458 #e = family name
459 #f = uniform title
460 #g = collective uniform title
461 #h = name/title
462 #i = name/collective uniform title
463 #j = topical subject
464 #k = place access
465 #l = form, genre or physical characteristics
466 "UNIMARC"=>{
467 '200'=>{authtypecode=>'NP'},
468 '210'=>{authtypecode=>'CO'},
469 '215'=>{authtypecode=>'SNG'},
470 '216'=>{authtypecode=>'TM'},
471 '220'=>{authtypecode=>'FAM'},
472 '230'=>{authtypecode=>'TU'},
473 '235'=>{authtypecode=>'CO_UNI_TI'},
474 '240'=>{authtypecode=>'SAUTTIT'},
475 '245'=>{authtypecode=>'NAME_COL'},
476 '250'=>{authtypecode=>'SNC'},
477 '260'=>{authtypecode=>'PA'},
478 '280'=>{authtypecode=>'GENRE/FORM'},
481 foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
482 return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
484 return;
487 =head2 GuessAuthId
489 =over 4
491 my $authtid = GuessAuthId($record);
493 =back
495 Get the record and tries to guess the adequate authtypecode from its content.
497 =cut
499 sub GuessAuthId {
500 my ($record) = @_;
501 return unless ($record && $record->field('001'));
502 # my $authtypecode=GuessAuthTypeCode($record);
503 # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
504 # if ($tag > 010) {return $record->subfield($tag,$subfield)}
505 # else {return $record->field($tag)->data}
506 return $record->field('001')->data;
509 =head2 GetTagsLabels
511 =over 4
513 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
514 returns a ref to hashref of authorities tag and subfield structure.
516 tagslabel usage :
517 $tagslabel->{$tag}->{$subfield}->{'attribute'}
518 where attribute takes values in :
521 mandatory
522 repeatable
523 authorised_value
524 authtypecode
525 value_builder
526 kohafield
527 seealso
528 hidden
529 isurl
530 link
532 =back
534 =cut
536 sub GetTagsLabels {
537 my ($forlibrarian,$authtypecode)= @_;
538 my $dbh=C4::Context->dbh;
539 $authtypecode="" unless $authtypecode;
540 my $sth;
541 my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
544 # check that authority exists
545 $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
546 $sth->execute($authtypecode);
547 my ($total) = $sth->fetchrow;
548 $authtypecode="" unless ($total >0);
549 $sth= $dbh->prepare(
550 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable
551 FROM auth_tag_structure
552 WHERE authtypecode=?
553 ORDER BY tagfield"
556 $sth->execute($authtypecode);
557 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
559 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
560 $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
561 $res->{$tag}->{tab} = " "; # XXX
562 $res->{$tag}->{mandatory} = $mandatory;
563 $res->{$tag}->{repeatable} = $repeatable;
565 $sth= $dbh->prepare(
566 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl
567 FROM auth_subfield_structure
568 WHERE authtypecode=?
569 ORDER BY tagfield,tagsubfield"
571 $sth->execute($authtypecode);
573 my $subfield;
574 my $authorised_value;
575 my $value_builder;
576 my $kohafield;
577 my $seealso;
578 my $hidden;
579 my $isurl;
580 my $link;
582 while (
583 ( $tag, $subfield, $liblibrarian, , $libopac, $tab,
584 $mandatory, $repeatable, $authorised_value, $authtypecode,
585 $value_builder, $kohafield, $seealso, $hidden,
586 $isurl, $link )
587 = $sth->fetchrow
590 $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
591 $res->{$tag}->{$subfield}->{tab} = $tab;
592 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
593 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
594 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
595 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
596 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
597 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
598 $res->{$tag}->{$subfield}->{seealso} = $seealso;
599 $res->{$tag}->{$subfield}->{hidden} = $hidden;
600 $res->{$tag}->{$subfield}->{isurl} = $isurl;
601 $res->{$tag}->{$subfield}->{link} = $link;
603 return $res;
606 =head2 AddAuthority
608 =over 4
610 $authid= &AddAuthority($record, $authid,$authtypecode)
611 returns authid of the newly created authority
613 Either Create Or Modify existing authority.
615 =back
617 =cut
619 sub AddAuthority {
620 # pass the MARC::Record to this function, and it will create the records in the authority table
621 my ($record,$authid,$authtypecode) = @_;
622 my $dbh=C4::Context->dbh;
623 my $leader=' nz a22 o 4500';#Leader for incomplete MARC21 record
625 # if authid empty => true add, find a new authid number
626 my $format;
627 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
628 $format= 'UNIMARCAUTH';
630 else {
631 $format= 'MARC21';
634 if ($format eq "MARC21") {
635 if (!$record->leader) {
636 $record->leader($leader);
638 if (!$record->field('003')) {
639 $record->insert_fields_ordered(
640 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
643 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
644 if (!$record->field('005')) {
645 $record->insert_fields_ordered(
646 MARC::Field->new('005',$time.".0")
649 my $date=POSIX::strftime("%y%m%d",localtime);
650 if (!$record->field('008')) {
651 $record->insert_fields_ordered(
652 MARC::Field->new('008',$date."|||a|||||| | ||| d")
655 if (!$record->field('040')) {
656 $record->insert_fields_ordered(
657 MARC::Field->new('040','','',
658 'a' => C4::Context->preference('MARCOrgCode'),
659 'c' => C4::Context->preference('MARCOrgCode')
665 if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
666 $record->leader(" nx j22 ");
667 my $date=POSIX::strftime("%Y%m%d",localtime);
668 if ($record->field('100')){
669 $record->field('100')->update('a'=>$date."afrey50 ba0");
670 } else {
671 $record->append_fields(
672 MARC::Field->new('100',' ',' '
673 ,'a'=>$date."afrey50 ba0")
677 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
678 if (!$authid and $format eq "MARC21") {
679 # only need to do this fix when modifying an existing authority
680 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
682 if (my $field=$record->field($auth_type_tag)){
683 $field->update($auth_type_subfield=>$authtypecode);
685 else {
686 $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode);
689 my $auth_exists=0;
690 my $oldRecord;
691 if (!$authid) {
692 my $sth=$dbh->prepare("select max(authid) from auth_header");
693 $sth->execute;
694 ($authid)=$sth->fetchrow;
695 $authid=$authid+1;
696 ##Insert the recordID in MARC record
697 unless ($record->field('001') && $record->field('001')->data() eq $authid){
698 $record->delete_field($record->field('001'));
699 $record->insert_fields_ordered(MARC::Field->new('001',$authid));
701 } else {
702 $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
703 # warn "auth_exists = $auth_exists";
705 if ($auth_exists>0){
706 $oldRecord=GetAuthority($authid);
707 $record->add_fields('001',$authid) unless ($record->field('001'));
708 # warn "\n\n\n enregistrement".$record->as_formatted;
709 my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
710 $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
711 $sth->finish;
713 else {
714 my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
715 $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
716 $sth->finish;
718 ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
719 return ($authid);
723 =head2 DelAuthority
725 =over 4
727 $authid= &DelAuthority($authid)
728 Deletes $authid
730 =back
732 =cut
735 sub DelAuthority {
736 my ($authid) = @_;
737 my $dbh=C4::Context->dbh;
739 ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
740 $dbh->do("delete from auth_header where authid=$authid") ;
744 sub ModAuthority {
745 my ($authid,$record,$authtypecode,$merge)=@_;
746 my $dbh=C4::Context->dbh;
747 #Now rewrite the $record to table with an add
748 my $oldrecord=GetAuthority($authid);
749 $authid=AddAuthority($record,$authid,$authtypecode);
751 ### 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
752 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
753 ### the $merge flag is now depreceated and will be removed at code cleaning
754 if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
755 &merge($authid,$oldrecord,$authid,$record);
756 } else {
757 # save the file in tmp/modified_authorities
758 my $cgidir = C4::Context->intranetdir ."/cgi-bin";
759 unless (opendir(DIR,"$cgidir")) {
760 $cgidir = C4::Context->intranetdir."/";
761 closedir(DIR);
764 my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
765 open AUTH, "> $filename";
766 print AUTH $authid;
767 close AUTH;
769 return $authid;
772 =head2 GetAuthorityXML
774 =over 4
776 $marcxml= &GetAuthorityXML( $authid)
777 returns xml form of record $authid
779 =back
781 =cut
783 sub GetAuthorityXML {
784 # Returns MARC::XML of the authority passed in parameter.
785 my ( $authid ) = @_;
786 if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
787 my $dbh=C4::Context->dbh;
788 my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " );
789 $sth->execute($authid);
790 my ($marcxml)=$sth->fetchrow;
791 return $marcxml;
793 else {
794 # for MARC21, call GetAuthority instead of
795 # getting the XML directly since we may
796 # need to fix up the location of the authority
797 # code -- note that this is reasonably safe
798 # because GetAuthorityXML is used only by the
799 # indexing processes like zebraqueue_start.pl
800 my $record = GetAuthority($authid);
801 return $record->as_xml_record('MARC21');
805 =head2 GetAuthority
807 =over 4
809 $record= &GetAuthority( $authid)
810 Returns MARC::Record of the authority passed in parameter.
812 =back
814 =cut
816 sub GetAuthority {
817 my ($authid)=@_;
818 my $dbh=C4::Context->dbh;
819 my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
820 $sth->execute($authid);
821 my ($authtypecode, $marcxml) = $sth->fetchrow;
822 my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
823 (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
824 return undef if ($@);
825 $record->encoding('UTF-8');
826 if (C4::Context->preference("marcflavour") eq "MARC21") {
827 my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
828 C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
830 return ($record);
833 =head2 GetAuthType
835 =over 4
837 $result = &GetAuthType($authtypecode)
839 =back
841 If the authority type specified by C<$authtypecode> exists,
842 returns a hashref of the type's fields. If the type
843 does not exist, returns undef.
845 =cut
847 sub GetAuthType {
848 my ($authtypecode) = @_;
849 my $dbh=C4::Context->dbh;
850 my $sth;
851 if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority
852 # type (FIXME but why?)
853 $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
854 $sth->execute($authtypecode);
855 if (my $res = $sth->fetchrow_hashref) {
856 return $res;
859 return;
863 sub AUTHhtml2marc {
864 my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
865 my $dbh=C4::Context->dbh;
866 my $prevtag = -1;
867 my $record = MARC::Record->new();
868 #---- TODO : the leader is missing
870 # my %subfieldlist=();
871 my $prevvalue; # if tag <10
872 my $field; # if tag >=10
873 for (my $i=0; $i< @$rtags; $i++) {
874 # rebuild MARC::Record
875 if (@$rtags[$i] ne $prevtag) {
876 if ($prevtag < 10) {
877 if ($prevvalue) {
878 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
880 } else {
881 if ($field) {
882 $record->add_fields($field);
885 $indicators{@$rtags[$i]}.=' ';
886 if (@$rtags[$i] <10) {
887 $prevvalue= @$rvalues[$i];
888 undef $field;
889 } else {
890 undef $prevvalue;
891 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
893 $prevtag = @$rtags[$i];
894 } else {
895 if (@$rtags[$i] <10) {
896 $prevvalue=@$rvalues[$i];
897 } else {
898 if (length(@$rvalues[$i])>0) {
899 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
902 $prevtag= @$rtags[$i];
905 # the last has not been included inside the loop... do it now !
906 $record->add_fields($field) if $field;
907 return $record;
910 =head2 FindDuplicateAuthority
912 =over 4
914 $record= &FindDuplicateAuthority( $record, $authtypecode)
915 return $authid,Summary if duplicate is found.
917 Comments : an improvement would be to return All the records that match.
919 =back
921 =cut
923 sub FindDuplicateAuthority {
925 my ($record,$authtypecode)=@_;
926 # warn "IN for ".$record->as_formatted;
927 my $dbh = C4::Context->dbh;
928 # warn "".$record->as_formatted;
929 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
930 $sth->execute($authtypecode);
931 my ($auth_tag_to_report) = $sth->fetchrow;
932 $sth->finish;
933 # warn "record :".$record->as_formatted." auth_tag_to_report :$auth_tag_to_report";
934 # build a request for SearchAuthorities
935 my $query='at='.$authtypecode.' ';
936 my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
937 if ($record->field($auth_tag_to_report)) {
938 foreach ($record->field($auth_tag_to_report)->subfields()) {
939 $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
942 my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
943 # there is at least 1 result => return the 1st one
944 if (@$results>0) {
945 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
946 return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
948 # no result, returns nothing
949 return;
952 =head2 BuildSummary
954 =over 4
956 $text= &BuildSummary( $record, $authid, $authtypecode)
957 return HTML encoded Summary
959 Comment : authtypecode can be infered from both record and authid.
960 Moreover, authid can also be inferred from $record.
961 Would it be interesting to delete those things.
963 =back
965 =cut
967 sub BuildSummary{
968 ## give this a Marc record to return summary
969 my ($record,$authid,$authtypecode)=@_;
970 my $dbh=C4::Context->dbh;
971 my $summary;
972 # handle $authtypecode is NULL or eq ""
973 if ($authtypecode) {
974 my $authref = GetAuthType($authtypecode);
975 $summary = $authref->{summary};
977 # FIXME: should use I18N.pm
978 my %language;
979 $language{'fre'}="Français";
980 $language{'eng'}="Anglais";
981 $language{'ger'}="Allemand";
982 $language{'ita'}="Italien";
983 $language{'spa'}="Espagnol";
984 my %thesaurus;
985 $thesaurus{'1'}="Peuples";
986 $thesaurus{'2'}="Anthroponymes";
987 $thesaurus{'3'}="Oeuvres";
988 $thesaurus{'4'}="Chronologie";
989 $thesaurus{'5'}="Lieux";
990 $thesaurus{'6'}="Sujets";
991 #thesaurus a remplir
992 my @fields = $record->fields();
993 my $reported_tag;
994 # if the library has a summary defined, use it. Otherwise, build a standard one
995 # FIXME - it appears that the summary field in the authority frameworks
996 # can work as a display template. However, this doesn't
997 # suit the MARC21 version, so for now the "templating"
998 # feature will be enabled only for UNIMARC for backwards
999 # compatibility.
1000 if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
1001 my @fields = $record->fields();
1002 # $reported_tag = '$9'.$result[$counter];
1003 my @stringssummary;
1004 foreach my $field (@fields) {
1005 my $tag = $field->tag();
1006 my $tagvalue = $field->as_string();
1007 my $localsummary= $summary;
1008 $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
1009 if ($tag<10) {
1010 if ($tag eq '001') {
1011 $reported_tag.='$3'.$field->data();
1013 } else {
1014 my @subf = $field->subfields;
1015 for my $i (0..$#subf) {
1016 my $subfieldcode = $subf[$i][0];
1017 my $subfieldvalue = $subf[$i][1];
1018 my $tagsubf = $tag.$subfieldcode;
1019 $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1022 push @stringssummary, $localsummary if ($localsummary ne $summary);
1024 my $resultstring;
1025 $resultstring = join(" -- ",@stringssummary);
1026 $resultstring =~ s/\[(.*?)\]//g;
1027 $resultstring =~ s/\n/<br>/g;
1028 $summary = $resultstring;
1029 } else {
1030 my $heading;
1031 my $altheading;
1032 my $seealso;
1033 my $broaderterms;
1034 my $narrowerterms;
1035 my $see;
1036 my $seeheading;
1037 my $notes;
1038 my @fields = $record->fields();
1039 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1040 # construct UNIMARC summary, that is quite different from MARC21 one
1041 # accepted form
1042 foreach my $field ($record->field('2..')) {
1043 $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1045 # rejected form(s)
1046 foreach my $field ($record->field('3..')) {
1047 $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1049 foreach my $field ($record->field('4..')) {
1050 if ($field->subfield('2')) {
1051 my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1052 $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1055 # see :
1056 foreach my $field ($record->field('5..')) {
1058 if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1059 $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1060 } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1061 $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1062 } elsif ($field->subfield('a')) {
1063 $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1066 # // form
1067 foreach my $field ($record->field('7..')) {
1068 my $lang = substr($field->subfield('8'),3,3);
1069 $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";
1071 $broaderterms =~s/-- \n$//;
1072 $narrowerterms =~s/-- \n$//;
1073 $seealso =~s/-- \n$//;
1074 $see =~s/-- \n$//;
1075 $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1076 $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1077 $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1078 $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1079 $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1080 $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1081 } else {
1082 # construct MARC21 summary
1083 # FIXME - looping over 1XX is questionable
1084 # since MARC21 authority should have only one 1XX
1085 foreach my $field ($record->field('1..')) {
1086 next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1087 # in MARC21 -- purely local tags really ought to be
1088 # 9XX
1089 if ($record->field('100')) {
1090 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1091 } elsif ($record->field('110')) {
1092 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1093 } elsif ($record->field('111')) {
1094 $heading.= $field->as_string('acdefghklnpqstvxyz68');
1095 } elsif ($record->field('130')) {
1096 $heading.= $field->as_string('adfghklmnoprstvxyz68');
1097 } elsif ($record->field('148')) {
1098 $heading.= $field->as_string('abvxyz68');
1099 } elsif ($record->field('150')) {
1100 # $heading.= $field->as_string('abvxyz68');
1101 $heading.= $field->as_formatted();
1102 my $tag=$field->tag();
1103 $heading=~s /^$tag//g;
1104 $heading =~s /\_/\$/g;
1105 } elsif ($record->field('151')) {
1106 $heading.= $field->as_string('avxyz68');
1107 } elsif ($record->field('155')) {
1108 $heading.= $field->as_string('abvxyz68');
1109 } elsif ($record->field('180')) {
1110 $heading.= $field->as_string('vxyz68');
1111 } elsif ($record->field('181')) {
1112 $heading.= $field->as_string('vxyz68');
1113 } elsif ($record->field('182')) {
1114 $heading.= $field->as_string('vxyz68');
1115 } elsif ($record->field('185')) {
1116 $heading.= $field->as_string('vxyz68');
1117 } else {
1118 $heading.= $field->as_string();
1120 } #See From
1121 foreach my $field ($record->field('4..')) {
1122 $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1123 } #See Also
1124 foreach my $field ($record->field('5..')) {
1125 $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1127 $summary .= ": " if $summary;
1128 $summary.=$heading.$seeheading.$altheading;
1131 return $summary;
1134 =head2 BuildUnimarcHierarchies
1136 =over 4
1138 $text= &BuildUnimarcHierarchies( $authid, $force)
1139 return text containing trees for hierarchies
1140 for them to be stored in auth_header
1142 Example of text:
1143 122,1314,2452;1324,2342,3,2452
1145 =back
1147 =cut
1149 sub BuildUnimarcHierarchies{
1150 my $authid = shift @_;
1151 # warn "authid : $authid";
1152 my $force = shift @_;
1153 my @globalresult;
1154 my $dbh=C4::Context->dbh;
1155 my $hierarchies;
1156 my $data = GetHeaderAuthority($authid);
1157 if ($data->{'authtrees'} and not $force){
1158 return $data->{'authtrees'};
1159 } elsif ($data->{'authtrees'}){
1160 $hierarchies=$data->{'authtrees'};
1161 } else {
1162 my $record = GetAuthority($authid);
1163 my $found;
1164 if ($record){
1165 foreach my $field ($record->field('550')){
1166 if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1167 my $parentrecord = GetAuthority($field->subfield('3'));
1168 my $localresult=$hierarchies;
1169 my $trees;
1170 $trees = BuildUnimarcHierarchies($field->subfield('3'));
1171 my @trees;
1172 if ($trees=~/;/){
1173 @trees = split(/;/,$trees);
1174 } else {
1175 push @trees, $trees;
1177 foreach (@trees){
1178 $_.= ",$authid";
1180 @globalresult = (@globalresult,@trees);
1181 $found=1;
1183 $hierarchies=join(";",@globalresult);
1186 #Unless there is no ancestor, I am alone.
1187 $hierarchies="$authid" unless ($hierarchies);
1189 AddAuthorityTrees($authid,$hierarchies);
1190 return $hierarchies;
1193 =head2 BuildUnimarcHierarchy
1195 =over 4
1197 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1198 return a hashref in order to display hierarchy for record and final Authid $authid
1200 "loopparents"
1201 "loopchildren"
1202 "class"
1203 "loopauthid"
1204 "current_value"
1205 "value"
1207 "ifparents"
1208 "ifchildren"
1209 Those two latest ones should disappear soon.
1211 =back
1213 =cut
1215 sub BuildUnimarcHierarchy{
1216 my $record = shift @_;
1217 my $class = shift @_;
1218 my $authid_constructed = shift @_;
1219 return undef unless ($record);
1220 my $authid=$record->subfield('2..','3');
1221 my %cell;
1222 my $parents=""; my $children="";
1223 my (@loopparents,@loopchildren);
1224 foreach my $field ($record->field('550')){
1225 if ($field->subfield('5') && $field->subfield('a')){
1226 if ($field->subfield('5') eq 'h'){
1227 push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1228 }elsif ($field->subfield('5') eq 'g'){
1229 push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1231 # brothers could get in there with an else
1234 $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1235 $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1236 $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1237 $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1238 $cell{"class"}=$class;
1239 $cell{"loopauthid"}=$authid;
1240 $cell{"current_value"} =1 if $authid eq $authid_constructed;
1241 $cell{"value"}=$record->subfield('2..',"a");
1242 return \%cell;
1245 =head2 GetHeaderAuthority
1247 =over 4
1249 $ref= &GetHeaderAuthority( $authid)
1250 return a hashref in order auth_header table data
1252 =back
1254 =cut
1256 sub GetHeaderAuthority{
1257 my $authid = shift @_;
1258 my $sql= "SELECT * from auth_header WHERE authid = ?";
1259 my $dbh=C4::Context->dbh;
1260 my $rq= $dbh->prepare($sql);
1261 $rq->execute($authid);
1262 my $data= $rq->fetchrow_hashref;
1263 return $data;
1266 =head2 AddAuthorityTrees
1268 =over 4
1270 $ref= &AddAuthorityTrees( $authid, $trees)
1271 return success or failure
1273 =back
1275 =cut
1277 sub AddAuthorityTrees{
1278 my $authid = shift @_;
1279 my $trees = shift @_;
1280 my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1281 my $dbh=C4::Context->dbh;
1282 my $rq= $dbh->prepare($sql);
1283 return $rq->execute($trees,$authid);
1286 =head2 merge
1288 =over 4
1290 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1293 Could add some feature : Migrating from a typecode to an other for instance.
1294 Then we should add some new parameter : bibliotargettag, authtargettag
1296 =back
1298 =cut
1300 sub merge {
1301 my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1302 my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);
1303 my $dbh=C4::Context->dbh;
1304 my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1305 my $authtypecodeto = GetAuthTypeCode($mergeto);
1306 # warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1307 # return if authority does not exist
1308 return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1309 return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1310 # search the tag to report
1311 my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1312 $sth->execute($authtypecodefrom);
1313 my ($auth_tag_to_report_from) = $sth->fetchrow;
1314 $sth->execute($authtypecodeto);
1315 my ($auth_tag_to_report_to) = $sth->fetchrow;
1317 my @record_to;
1318 @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1319 my @record_from;
1320 @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1322 my @reccache;
1323 # search all biblio tags using this authority.
1324 #Getting marcbiblios impacted by the change.
1325 if (C4::Context->preference('NoZebra')) {
1326 #nozebra way
1327 my $dbh=C4::Context->dbh;
1328 my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1329 $rq->execute;
1330 while (my $biblionumbers=$rq->fetchrow){
1331 my @biblionumbers=split /;/,$biblionumbers;
1332 foreach (@biblionumbers) {
1333 if ($_=~/(\d+),.*/) {
1334 my $marc=GetMarcBiblio($1);
1335 push @reccache,$marc;
1339 } else {
1340 #zebra connection
1341 my $oConnection=C4::Context->Zconn("biblioserver",0);
1342 $oConnection->option("preferredRecordSyntax"=>"XML");
1343 my $query;
1344 $query= "an=".$mergefrom;
1345 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1346 my $count = 0;
1347 if ($oResult) {
1348 $count=$oResult->size();
1350 my $z=0;
1351 while ( $z<$count ) {
1352 my $rec;
1353 $rec=$oResult->record($z);
1354 my $marcdata = $rec->raw();
1355 push @reccache, $marcdata;
1356 $z++;
1358 $oConnection->destroy();
1360 #warn scalar(@reccache)." biblios to update";
1361 # Get All candidate Tags for the change
1362 # (This will reduce the search scope in marc records).
1363 $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1364 $sth->execute($authtypecodefrom);
1365 my @tags_using_authtype;
1366 while (my ($tagfield) = $sth->fetchrow) {
1367 push @tags_using_authtype,$tagfield ;
1369 my $tag_to=0;
1370 if ($authtypecodeto ne $authtypecodefrom){
1371 # If many tags, take the first
1372 $sth->execute($authtypecodeto);
1373 $tag_to=$sth->fetchrow;
1374 #warn $tag_to;
1376 # BulkEdit marc records
1377 # May be used as a template for a bulkedit field
1378 foreach my $marcrecord(@reccache){
1379 my $update;
1380 $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1381 foreach my $tagfield (@tags_using_authtype){
1382 # warn "tagfield : $tagfield ";
1383 foreach my $field ($marcrecord->field($tagfield)){
1384 my $auth_number=$field->subfield("9");
1385 my $tag=$field->tag();
1386 if ($auth_number==$mergefrom) {
1387 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1388 foreach my $subfield (@record_to) {
1389 $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1391 $marcrecord->delete_field($field);
1392 $marcrecord->insert_grouped_field($field_to);
1393 $update=1;
1395 }#for each tag
1396 }#foreach tagfield
1397 my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1398 my $biblionumber;
1399 if ($bibliotag<10){
1400 $biblionumber=$marcrecord->field($bibliotag)->data;
1402 else {
1403 $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1405 unless ($biblionumber){
1406 warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1407 next;
1409 if ($update==1){
1410 &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1411 $counteditedbiblio++;
1412 warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1414 }#foreach $marc
1415 return $counteditedbiblio;
1416 # now, find every other authority linked with this authority
1417 # now, find every other authority linked with this authority
1418 # my $oConnection=C4::Context->Zconn("authorityserver");
1419 # my $query;
1420 # # att 9210 Auth-Internal-authtype
1421 # # att 9220 Auth-Internal-LN
1422 # # ccl.properties to add for authorities
1423 # $query= "= ".$mergefrom;
1424 # my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1425 # my $count=$oResult->size() if ($oResult);
1426 # my @reccache;
1427 # my $z=0;
1428 # while ( $z<$count ) {
1429 # my $rec;
1430 # $rec=$oResult->record($z);
1431 # my $marcdata = $rec->raw();
1432 # push @reccache, $marcdata;
1433 # $z++;
1435 # $oResult->destroy();
1436 # foreach my $marc(@reccache){
1437 # my $update;
1438 # my $marcrecord;
1439 # $marcrecord = MARC::File::USMARC::decode($marc);
1440 # foreach my $tagfield (@tags_using_authtype){
1441 # $tagfield=substr($tagfield,0,3);
1442 # my @tags = $marcrecord->field($tagfield);
1443 # foreach my $tag (@tags){
1444 # my $tagsubs=$tag->subfield("9");
1445 # #warn "$tagfield:$tagsubs:$mergefrom";
1446 # if ($tagsubs== $mergefrom) {
1447 # $tag->update("9" =>$mergeto);
1448 # foreach my $subfield (@record_to) {
1449 # # warn "$subfield,$subfield->[0],$subfield->[1]";
1450 # $tag->update($subfield->[0] =>$subfield->[1]);
1451 # }#for $subfield
1453 # $marcrecord->delete_field($tag);
1454 # $marcrecord->add_fields($tag);
1455 # $update=1;
1456 # }#for each tag
1457 # }#foreach tagfield
1458 # my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1459 # if ($update==1){
1460 # &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1463 # }#foreach $marc
1464 }#sub
1466 =head2 get_auth_type_location
1468 =over 4
1470 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1472 =back
1474 Get the tag and subfield used to store the heading type
1475 for indexing purposes. The C<$auth_type> parameter is
1476 optional; if it is not supplied, assume ''.
1478 This routine searches the MARC authority framework
1479 for the tag and subfield whose kohafield is
1480 C<auth_header.authtypecode>; if no such field is
1481 defined in the framework, default to the hardcoded value
1482 specific to the MARC format.
1484 =cut
1486 sub get_auth_type_location {
1487 my $auth_type_code = @_ ? shift : '';
1489 my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1490 if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1491 return ($tag, $subfield);
1492 } else {
1493 if (C4::Context->preference('marcflavour') eq "MARC21") {
1494 return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1495 } else {
1496 return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1501 END { } # module clean-up code here (global destructor)
1504 __END__
1506 =head1 AUTHOR
1508 Koha Development Team <info@koha.org>
1510 Paul POULAIN paul.poulain@free.fr
1512 =cut