ba71a8df4f433bd651d24ef76076ccbb3b818dc0
[koha.git] / C4 / AuthoritiesMarc.pm
1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
3 #
4 # This file is part of Koha.
5 #
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.
10 #
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.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19 use strict;
20 use C4::Context;
21 use C4::Koha;
22 use MARC::Record;
23 use C4::Biblio;
24 use C4::Search;
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
27 use C4::Charset;
28 use C4::Debug;
29
30 use vars qw($VERSION @ISA @EXPORT);
31
32 BEGIN {
33         # set the version for version checking
34         $VERSION = 3.01;
35
36         require Exporter;
37         @ISA = qw(Exporter);
38         @EXPORT = qw(
39             &GetTagsLabels
40             &GetAuthType
41             &GetAuthTypeCode
42         &GetAuthMARCFromKohaField 
43         &AUTHhtml2marc
44
45         &AddAuthority
46         &ModAuthority
47         &DelAuthority
48         &GetAuthority
49         &GetAuthorityXML
50     
51         &CountUsage
52         &CountUsageChildren
53         &SearchAuthorities
54     
55         &BuildSummary
56         &BuildUnimarcHierarchies
57         &BuildUnimarcHierarchy
58     
59         &merge
60         &FindDuplicateAuthority
61         );
62 }
63
64 =head2 GetAuthMARCFromKohaField 
65
66 =over 4
67
68 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
69 returns tag and subfield linked to kohafield
70
71 Comment :
72 Suppose Kohafield is only linked to ONE subfield
73
74 =back
75
76 =cut
77
78 sub GetAuthMARCFromKohaField {
79 #AUTHfind_marc_from_kohafield
80   my ( $kohafield,$authtypecode ) = @_;
81   my $dbh=C4::Context->dbh;
82   return 0, 0 unless $kohafield;
83   $authtypecode="" unless $authtypecode;
84   my $marcfromkohafield;
85   my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
86   $sth->execute($kohafield,$authtypecode);
87   my ($tagfield,$tagsubfield) = $sth->fetchrow;
88     
89   return  ($tagfield,$tagsubfield);
90 }
91
92 =head2 SearchAuthorities 
93
94 =over 4
95
96 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
97 returns ref to array result and count of results returned
98
99 =back
100
101 =cut
102
103 sub SearchAuthorities {
104     my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
105 #     warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
106     my $dbh=C4::Context->dbh;
107     if (C4::Context->preference('NoZebra')) {
108     
109         #
110         # build the query
111         #
112         my $query;
113         my @auths=split / /,$authtypecode ;
114         foreach my  $auth (@auths){
115             $query .="AND auth_type= $auth ";
116         }
117         $query =~ s/^AND //;
118         my $dosearch;
119         for(my $i = 0 ; $i <= $#{$value} ; $i++)
120         {
121             if (@$value[$i]){
122                 if (@$tags[$i] =~/mainentry|mainmainentry/) {
123                     $query .= qq( AND @$tags[$i] );
124                 } else {
125                     $query .=" AND ";
126                 }
127                 if (@$operator[$i] eq 'is') {
128                     $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
129                 }elsif (@$operator[$i] eq "="){
130                     $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
131                 }elsif (@$operator[$i] eq "start"){
132                     $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
133                 } else {
134                     $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
135                 }
136                 $dosearch=1;
137             }#if value
138         }
139         #
140         # do the query (if we had some search term
141         #
142         if ($dosearch) {
143 #             warn "QUERY : $query";
144             my $result = C4::Search::NZanalyse($query,'authorityserver');
145 #             warn "result : $result";
146             my %result;
147             foreach (split /;/,$result) {
148                 my ($authid,$title) = split /,/,$_;
149                 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
150                 # and we don't want to get only 1 result for each of them !!!
151                 # hint & speed improvement : we can order without reading the record
152                 # so order, and read records only for the requested page !
153                 $result{$title.$authid}=$authid;
154             }
155             # sort the hash and return the same structure as GetRecords (Zebra querying)
156             my @listresult = ();
157             my $numbers=0;
158             if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
159                 foreach my $key (sort {$b cmp $a} (keys %result)) {
160                     push @listresult, $result{$key};
161 #                     warn "push..."$#finalresult;
162                     $numbers++;
163                 }
164             } else { # sort by mainmainentry ASC
165                 foreach my $key (sort (keys %result)) {
166                     push @listresult, $result{$key};
167 #                     warn "push..."$#finalresult;
168                     $numbers++;
169                 }
170             }
171             # limit the $results_per_page to result size if it's more
172             $length = $numbers-$offset if $numbers < ($offset+$length);
173             # for the requested page, replace authid by the complete record
174             # speed improvement : avoid reading too much things
175             my @finalresult;      
176             for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
177 #                 $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
178                 my $separator=C4::Context->preference('authoritysep');
179                 my $authrecord =GetAuthority($listresult[$counter]);
180                 my $authid=$listresult[$counter]; 
181                 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
182                 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
183                 my $sth = $dbh->prepare($query_auth_tag);
184                 $sth->execute($authtypecode);
185                 my $auth_tag_to_report = $sth->fetchrow;
186                 my %newline;
187                 $newline{used}=CountUsage($authid);
188                 $newline{summary} = $summary;
189                 $newline{authid} = $authid;
190                 $newline{even} = $counter % 2;
191                 push @finalresult, \%newline;
192             }
193             return (\@finalresult, $numbers);
194         } else {
195             return;
196         }
197     } else {
198         my $query;
199         my $attr;
200             # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
201             # the authtypecode. Then, search on $a of this tag_to_report
202             # also store main entry MARC tag, to extract it at end of search
203         my $mainentrytag;
204         ##first set the authtype search and may be multiple authorities
205         my $n=0;
206         my @authtypecode;
207         my @auths=split / /,$authtypecode ;
208                 my @queries;
209         foreach my  $auth (@auths){
210             push @queries, " \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
211             push @authtypecode ,$auth;
212             $n++;
213         }
214         if ($n>1){
215             while ($n>1){$query= "\@or ".$query;$n--;}
216         }
217         
218         my $dosearch;
219         my $and=" \@and " ;
220         for(my $i = 0 ; $i <= $#{$value} ; $i++)
221         {
222             if (@$value[$i]){
223             ##If mainentry search $a tag
224                 if (@$tags[$i] eq "mainmainentry") {
225
226                 $attr =" \@attr 1=Heading-Main "; 
227 #                $attr =" \@attr 1=Heading ";
228
229                 }elsif (@$tags[$i] eq "mainentry") {
230                 $attr =" \@attr 1=Heading ";
231                 }else{
232                 $attr =" \@attr 1=Any ";
233                 }
234                 if (@$operator[$i] eq 'is') {
235                     $attr.=" \@attr 4=1  \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
236                 }elsif (@$operator[$i] eq "="){
237                     $attr.=" \@attr 4=107 ";           #Number Exact match
238                 }elsif (@$operator[$i] eq "start"){
239                     $attr.=" \@attr 3=2 \@attr 4=1 \@attr 5=1 ";#Firstinfield Phrase, Right truncated
240                 } else {
241                     $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
242                 }
243                 $attr =$attr."\"".@$value[$i]."\"";
244                 push @queries, "$attr";
245             $dosearch=1;
246             }#if value
247         }
248         ##Add how many queries generated
249                 $query='';
250                 foreach my $query_part (@queries){
251                         $query=($query?$and.$query_part.$query:$query_part);
252                 }
253         ## Adding order
254         #$query=' @or  @attr 7=2 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
255         my $orderstring= ($sortby eq "HeadingAsc"?
256                            '@attr 7=1 @attr 1=Heading 0'
257                          :
258                            $sortby eq "HeadingDsc"?      
259                             '@attr 7=2 @attr 1=Heading 0'
260                            :''
261                         );            
262         $query=($dosearch?"\@or $orderstring $query":"\@or ".($query?"$and $query":"")." \@attr 1=_ALLRECORDS \@attr 2=103 '' $orderstring ");
263         $debug && warn $query;
264         
265         $offset=0 unless $offset;
266         my $counter = $offset;
267         $length=10 unless $length;
268         my @oAuth;
269         my $i;
270         $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
271         my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
272         my $oAResult;
273         $oAResult= $oAuth[0]->search($Anewq) ; 
274         while (($i = ZOOM::event(\@oAuth)) != 0) {
275             my $ev = $oAuth[$i-1]->last_event();
276             last if $ev == ZOOM::Event::ZEND;
277         }
278         my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
279         if ($error) {
280             warn  "oAuth error: $errmsg ($error) $addinfo $diagset\n";
281             goto NOLUCK;
282         }
283         
284         my $nbresults;
285         $nbresults=$oAResult->size();
286         my $nremains=$nbresults;    
287         my @result = ();
288         my @finalresult = ();
289         
290         if ($nbresults>0){
291         
292         ##Find authid and linkid fields
293         ##we may be searching multiple authoritytypes.
294         ## FIXME this assumes that all authid and linkid fields are the same for all authority types
295         # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
296         # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
297             while (($counter < $nbresults) && ($counter < ($offset + $length))) {
298             
299             ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
300             my $rec=$oAResult->record($counter);
301             my $marcdata=$rec->raw();
302             my $authrecord;
303             my $separator=C4::Context->preference('authoritysep');
304             $authrecord = MARC::File::USMARC::decode($marcdata);
305             my $authid=$authrecord->field('001')->data(); 
306             my $summary=BuildSummary($authrecord,$authid,$authtypecode);
307             my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
308             my $sth = $dbh->prepare($query_auth_tag);
309             $sth->execute($authtypecode);
310             my $auth_tag_to_report = $sth->fetchrow;
311             my $reported_tag;
312             my $mainentry = $authrecord->field($auth_tag_to_report);
313             if ($mainentry) {
314                 foreach ($mainentry->subfields()) {
315                     $reported_tag .='$'.$_->[0].$_->[1];
316                 }
317             }
318             my %newline;
319             $newline{summary} = $summary;
320             $newline{authid} = $authid;
321             $newline{even} = $counter % 2;
322             $newline{reported_tag} = $reported_tag;
323             $counter++;
324             push @finalresult, \%newline;
325             }## while counter
326         ###
327         for (my $z=0; $z<@finalresult; $z++){
328                 my  $count=CountUsage($finalresult[$z]{authid});
329                 $finalresult[$z]{used}=$count;
330         }# all $z's
331         
332         }## if nbresult
333         NOLUCK:
334         # $oAResult->destroy();
335         # $oAuth[0]->destroy();
336         
337         return (\@finalresult, $nbresults);
338     }
339 }
340
341 =head2 CountUsage 
342
343 =over 4
344
345 $count= &CountUsage($authid)
346 counts Usage of Authid in bibliorecords. 
347
348 =back
349
350 =cut
351
352 sub CountUsage {
353     my ($authid) = @_;
354     if (C4::Context->preference('NoZebra')) {
355         # Read the index Koha-Auth-Number for this authid and count the lines
356         my $result = C4::Search::NZanalyse("an=$authid");
357         my @tab = split /;/,$result;
358         return scalar @tab;
359     } else {
360         ### ZOOM search here
361         my $oConnection=C4::Context->Zconn("biblioserver",1);
362         my $query;
363         $query= "an=".$authid;
364         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
365         my $result;
366         while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
367             my $ev = $oConnection->last_event();
368             if ($ev == ZOOM::Event::ZEND) {
369                 $result = $oResult->size();
370             }
371         }
372         return ($result);
373     }
374 }
375
376 =head2 CountUsageChildren 
377
378 =over 4
379
380 $count= &CountUsageChildren($authid)
381 counts Usage of narrower terms of Authid in bibliorecords.
382
383 =back
384
385 =cut
386
387 sub CountUsageChildren {
388   my ($authid) = @_;
389 }
390
391 =head2 GetAuthTypeCode
392
393 =over 4
394
395 $authtypecode= &GetAuthTypeCode($authid)
396 returns authtypecode of an authid
397
398 =back
399
400 =cut
401
402 sub GetAuthTypeCode {
403 #AUTHfind_authtypecode
404   my ($authid) = @_;
405   my $dbh=C4::Context->dbh;
406   my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
407   $sth->execute($authid);
408   my $authtypecode = $sth->fetchrow;
409   return $authtypecode;
410 }
411  
412 =head2 GetTagsLabels
413
414 =over 4
415
416 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
417 returns a ref to hashref of authorities tag and subfield structure.
418
419 tagslabel usage : 
420 $tagslabel->{$tag}->{$subfield}->{'attribute'}
421 where attribute takes values in :
422   lib
423   tab
424   mandatory
425   repeatable
426   authorised_value
427   authtypecode
428   value_builder
429   kohafield
430   seealso
431   hidden
432   isurl
433   link
434
435 =back
436
437 =cut
438
439 sub GetTagsLabels {
440   my ($forlibrarian,$authtypecode)= @_;
441   my $dbh=C4::Context->dbh;
442   $authtypecode="" unless $authtypecode;
443   my $sth;
444   my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
445
446
447   # check that authority exists
448   $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
449   $sth->execute($authtypecode);
450   my ($total) = $sth->fetchrow;
451   $authtypecode="" unless ($total >0);
452   $sth= $dbh->prepare(
453 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable 
454  FROM auth_tag_structure 
455  WHERE authtypecode=? 
456  ORDER BY tagfield"
457     );
458
459   $sth->execute($authtypecode);
460   my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
461
462   while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
463         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
464         $res->{$tag}->{tab}        = " ";            # XXX
465         $res->{$tag}->{mandatory}  = $mandatory;
466         $res->{$tag}->{repeatable} = $repeatable;
467   }
468   $sth=      $dbh->prepare(
469 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl 
470 FROM auth_subfield_structure 
471 WHERE authtypecode=? 
472 ORDER BY tagfield,tagsubfield"
473     );
474     $sth->execute($authtypecode);
475
476     my $subfield;
477     my $authorised_value;
478     my $value_builder;
479     my $kohafield;
480     my $seealso;
481     my $hidden;
482     my $isurl;
483     my $link;
484
485     while (
486         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
487         $mandatory,     $repeatable, $authorised_value, $authtypecode,
488         $value_builder, $kohafield,  $seealso,          $hidden,
489         $isurl,            $link )
490         = $sth->fetchrow
491       )
492     {
493         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
494         $res->{$tag}->{$subfield}->{tab}              = $tab;
495         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
496         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
497         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
498         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
499         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
500         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
501         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
502         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
503         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
504         $res->{$tag}->{$subfield}->{link}            = $link;
505     }
506     return $res;
507 }
508
509 =head2 AddAuthority
510
511 =over 4
512
513 $authid= &AddAuthority($record, $authid,$authtypecode)
514 returns authid of the newly created authority
515
516 Either Create Or Modify existing authority.
517
518 =back
519
520 =cut
521
522 sub AddAuthority {
523 # pass the MARC::Record to this function, and it will create the records in the authority table
524   my ($record,$authid,$authtypecode) = @_;
525   my $dbh=C4::Context->dbh;
526         my $leader='    nz   a22     o  4500';#Leader for incomplete MARC21 record
527
528 # if authid empty => true add, find a new authid number
529   my $format = uc(C4::Context->preference('marcflavour')) eq 'UNIMARC'
530     ? 'UNIMARCAUTH' : 'MARC21'
531   ; 
532
533         if ($format eq "MARC21") {
534                 if (!$record->leader) {
535                         $record->leader($leader);
536                 }
537                 if (!$record->field('003')) {
538                         $record->insert_fields_ordered(
539                                 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
540                         );
541                 }
542                 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
543                 if (!$record->field('005')) {
544                         $record->insert_fields_ordered(
545                                 MARC::Field->new('005',$time.".0")
546                         );
547                 }
548                 my $date=POSIX::strftime("%y%m%d",localtime);
549                 if (!$record->field('008')) {
550                         $record->insert_fields_ordered(
551                                 MARC::Field->new('008',$date."|||a||||||           | |||     d")
552                         );
553                 }
554                 if (!$record->field('040')) {
555                  $record->insert_fields_ordered(
556         MARC::Field->new('040','','',
557                                 'a' => C4::Context->preference('MARCOrgCode'),
558                                 'c' => C4::Context->preference('MARCOrgCode')
559                                 ) 
560                         );
561     }
562         }
563
564   if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
565         $record->leader("     nx  j22             ");
566         my $date=POSIX::strftime("%Y%m%d",localtime);    
567         if ($record->field('100')){
568           $record->field('100')->update('a'=>$date."afrey50      ba0");
569         } else {      
570           $record->append_fields(
571             MARC::Field->new('100',' ',' '
572               ,'a'=>$date."afrey50      ba0")
573           );
574         }      
575   }
576   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
577   if (!$authid and $format eq "MARC21") {
578     # only need to do this fix when modifying an existing authority
579     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
580   } 
581   if (my $field=$record->field($auth_type_tag)){
582     $field->update($auth_type_subfield=>$authtypecode);
583   }
584   else {
585     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
586   }
587
588   my $auth_exists=0;
589   my $oldRecord;
590   if (!$authid) {
591     my $sth=$dbh->prepare("select max(authid) from auth_header");
592     $sth->execute;
593     ($authid)=$sth->fetchrow;
594     ( $authid ||= 0 )++; # $authid is undef for the first authority
595     ## Insert the recordID in MARC record
596     if   ( my $field = $record->field('001') ) { $field->data($authid) }
597     else { $record->insert_fields_ordered(MARC::Field->new('001',$authid)) }
598   } else {
599     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
600 #     warn "auth_exists = $auth_exists";
601   }
602   if ($auth_exists>0){
603       $oldRecord=GetAuthority($authid);
604       $record->add_fields('001',$authid) unless ($record->field('001'));
605 #       warn "\n\n\n enregistrement".$record->as_formatted;
606       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
607       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
608       $sth->finish;
609   }
610   else {
611     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
612     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
613     $sth->finish;
614   }
615   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
616   return ($authid);
617 }
618
619
620 =head2 DelAuthority
621
622 =over 4
623
624 $authid= &DelAuthority($authid)
625 Deletes $authid
626
627 =back
628
629 =cut
630
631
632 sub DelAuthority {
633     my ($authid) = @_;
634     my $dbh=C4::Context->dbh;
635
636     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
637     $dbh->do("delete from auth_header where authid=$authid") ;
638
639 }
640
641 sub ModAuthority {
642   my ($authid,$record,$authtypecode,$merge)=@_;
643   my $dbh=C4::Context->dbh;
644   #Now rewrite the $record to table with an add
645   my $oldrecord=GetAuthority($authid);
646   $authid=AddAuthority($record,$authid,$authtypecode);
647
648 ### 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
649 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
650 ### the $merge flag is now depreceated and will be removed at code cleaning
651   if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
652       &merge($authid,$oldrecord,$authid,$record);
653   } else {
654   # save the file in tmp/modified_authorities
655       my $cgidir = C4::Context->intranetdir ."/cgi-bin";
656       unless (opendir(DIR,"$cgidir")) {
657               $cgidir = C4::Context->intranetdir."/";
658               closedir(DIR);
659       }
660   
661       my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
662       open AUTH, "> $filename";
663       print AUTH $authid;
664       close AUTH;
665   }
666   return $authid;
667 }
668
669 =head2 GetAuthorityXML 
670
671 =over 4
672
673 $marcxml= &GetAuthorityXML( $authid)
674 returns xml form of record $authid
675
676 =back
677
678 =cut
679
680 sub GetAuthorityXML {
681   # Returns MARC::XML of the authority passed in parameter.
682   my ( $authid ) = @_;
683   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
684       my $dbh=C4::Context->dbh;
685       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
686       $sth->execute($authid);
687       my ($marcxml)=$sth->fetchrow;
688       return $marcxml;
689   }
690   else { 
691       # for MARC21, call GetAuthority instead of
692       # getting the XML directly since we may
693       # need to fix up the location of the authority
694       # code -- note that this is reasonably safe
695       # because GetAuthorityXML is used only by the 
696       # indexing processes like zebraqueue_start.pl
697       my $record = GetAuthority($authid);
698       return $record->as_xml_record('MARC21');
699   }
700 }
701
702 =head2 GetAuthority 
703
704 =over 4
705
706 $record= &GetAuthority( $authid)
707 Returns MARC::Record of the authority passed in parameter.
708
709 =back
710
711 =cut
712
713 sub GetAuthority {
714     my ($authid)=@_;
715     my $dbh=C4::Context->dbh;
716     my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
717     $sth->execute($authid);
718     my ($authtypecode, $marcxml) = $sth->fetchrow;
719     my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
720         (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
721     return undef if ($@);
722     $record->encoding('UTF-8');
723     if (C4::Context->preference("marcflavour") eq "MARC21") {
724       my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
725       C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
726     }
727     return ($record);
728 }
729
730 =head2 GetAuthType 
731
732 =over 4
733
734 $result = &GetAuthType($authtypecode)
735
736 =back
737
738 If the authority type specified by C<$authtypecode> exists,
739 returns a hashref of the type's fields.  If the type
740 does not exist, returns undef.
741
742 =cut
743
744 sub GetAuthType {
745     my ($authtypecode) = @_;
746     my $dbh=C4::Context->dbh;
747     my $sth;
748     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
749                                 # type (FIXME but why?)
750         $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
751         $sth->execute($authtypecode);
752         if (my $res = $sth->fetchrow_hashref) {
753             return $res; 
754         }
755     }
756     return;
757 }
758
759
760 sub AUTHhtml2marc {
761     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
762     my $dbh=C4::Context->dbh;
763     my $prevtag = -1;
764     my $record = MARC::Record->new();
765 #---- TODO : the leader is missing
766
767 #     my %subfieldlist=();
768     my $prevvalue; # if tag <10
769     my $field; # if tag >=10
770     for (my $i=0; $i< @$rtags; $i++) {
771         # rebuild MARC::Record
772         if (@$rtags[$i] ne $prevtag) {
773             if ($prevtag < 10) {
774                 if ($prevvalue) {
775                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
776                 }
777             } else {
778                 if ($field) {
779                     $record->add_fields($field);
780                 }
781             }
782             $indicators{@$rtags[$i]}.='  ';
783             if (@$rtags[$i] <10) {
784                 $prevvalue= @$rvalues[$i];
785                 undef $field;
786             } else {
787                 undef $prevvalue;
788                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
789             }
790             $prevtag = @$rtags[$i];
791         } else {
792             if (@$rtags[$i] <10) {
793                 $prevvalue=@$rvalues[$i];
794             } else {
795                 if (length(@$rvalues[$i])>0) {
796                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
797                 }
798             }
799             $prevtag= @$rtags[$i];
800         }
801     }
802     # the last has not been included inside the loop... do it now !
803     $record->add_fields($field) if $field;
804     return $record;
805 }
806
807 =head2 FindDuplicateAuthority
808
809 =over 4
810
811 $record= &FindDuplicateAuthority( $record, $authtypecode)
812 return $authid,Summary if duplicate is found.
813
814 Comments : an improvement would be to return All the records that match.
815
816 =back
817
818 =cut
819
820 sub FindDuplicateAuthority {
821
822     my ($record,$authtypecode)=@_;
823 #    warn "IN for ".$record->as_formatted;
824     my $dbh = C4::Context->dbh;
825 #    warn "".$record->as_formatted;
826     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
827     $sth->execute($authtypecode);
828     my ($auth_tag_to_report) = $sth->fetchrow;
829     $sth->finish;
830 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
831     # build a request for SearchAuthorities
832     my $query='at='.$authtypecode.' ';
833     my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
834     if ($record->field($auth_tag_to_report)) {
835       foreach ($record->field($auth_tag_to_report)->subfields()) {
836         $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
837       }
838     }
839     my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
840     # there is at least 1 result => return the 1st one
841     if (@$results>0) {
842       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
843       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
844     }
845     # no result, returns nothing
846     return;
847 }
848
849 =head2 BuildSummary
850
851 =over 4
852
853 $text= &BuildSummary( $record, $authid, $authtypecode)
854 return HTML encoded Summary
855
856 Comment : authtypecode can be infered from both record and authid.
857 Moreover, authid can also be inferred from $record.
858 Would it be interesting to delete those things.
859
860 =back
861
862 =cut
863
864 sub BuildSummary{
865 ## give this a Marc record to return summary
866   my ($record,$authid,$authtypecode)=@_;
867   my $dbh=C4::Context->dbh;
868   my $summary;
869   # handle $authtypecode is NULL or eq ""
870   if ($authtypecode) {
871         my $authref = GetAuthType($authtypecode);
872         $summary = $authref->{summary};
873   }
874   # FIXME: should use I18N.pm
875   my %language;
876   $language{'fre'}="Français";
877   $language{'eng'}="Anglais";
878   $language{'ger'}="Allemand";
879   $language{'ita'}="Italien";
880   $language{'spa'}="Espagnol";
881   my %thesaurus;
882   $thesaurus{'1'}="Peuples";
883   $thesaurus{'2'}="Anthroponymes";
884   $thesaurus{'3'}="Oeuvres";
885   $thesaurus{'4'}="Chronologie";
886   $thesaurus{'5'}="Lieux";
887   $thesaurus{'6'}="Sujets";
888   #thesaurus a remplir
889   my @fields = $record->fields();
890   my $reported_tag;
891   # if the library has a summary defined, use it. Otherwise, build a standard one
892   # FIXME - it appears that the summary field in the authority frameworks
893   #         can work as a display template.  However, this doesn't
894   #         suit the MARC21 version, so for now the "templating"
895   #         feature will be enabled only for UNIMARC for backwards
896   #         compatibility.
897   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
898     my @fields = $record->fields();
899     #             $reported_tag = '$9'.$result[$counter];
900     foreach my $field (@fields) {
901       my $tag = $field->tag();
902       my $tagvalue = $field->as_string();
903       $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
904       if ($tag<10) {
905         if ($tag eq '001') {
906           $reported_tag.='$3'.$field->data();
907         }
908       } else {
909         my @subf = $field->subfields;
910         for my $i (0..$#subf) {
911           my $subfieldcode = $subf[$i][0];
912           my $subfieldvalue = $subf[$i][1];
913           my $tagsubf = $tag.$subfieldcode;
914           $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
915         }
916       }
917     }
918     $summary =~ s/\[(.*?)]//g;
919     $summary =~ s/\n/<br>/g;
920   } else {
921     my $heading; 
922     my $altheading;
923     my $seealso;
924     my $broaderterms;
925     my $narrowerterms;
926     my $see;
927     my $seeheading;
928         my $notes;
929     my @fields = $record->fields();
930     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
931     # construct UNIMARC summary, that is quite different from MARC21 one
932       # accepted form
933       foreach my $field ($record->field('2..')) {
934         $heading.= $field->subfield('a');
935       }
936       # rejected form(s)
937       foreach my $field ($record->field('3..')) {
938         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
939       }
940       foreach my $field ($record->field('4..')) {
941         if ($field->subfield('2')) {
942             my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
943             $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
944         }
945       }
946       # see :
947       foreach my $field ($record->field('5..')) {
948         my $authid=_get_authid_subfield($field);    
949         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
950           $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$authid.'">'.$field->subfield('a')."</a></span> -- \n";
951         } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
952           $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$authid.'">'.$field->subfield('a')."</a></span> -- \n";
953         } elsif ($field->subfield('a')) {
954           $seealso.= '<span class="RT"><a href="detail.pl?authid='.$authid.'">'.$field->subfield('a')."</a></span> -- \n";
955         }
956       }
957       # // form
958       foreach my $field ($record->field('7..')) {
959         my $lang = substr($field->subfield('8'),3,3);
960         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
961       }
962             $broaderterms =~s/-- \n$//;
963             $narrowerterms =~s/-- \n$//;
964             $seealso =~s/-- \n$//;
965             $see =~s/-- \n$//;
966       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
967       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
968       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
969       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
970       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
971       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
972       } else {
973       # construct MARC21 summary
974           # FIXME - looping over 1XX is questionable
975           # since MARC21 authority should have only one 1XX
976           foreach my $field ($record->field('1..')) {
977               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
978                                               # in MARC21 -- purely local tags really ought to be
979                                               # 9XX
980               if ($record->field('100')) {
981                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
982               } elsif ($record->field('110')) {
983                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
984               } elsif ($record->field('111')) {
985                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
986               } elsif ($record->field('130')) {
987                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
988               } elsif ($record->field('148')) {
989                                       $heading.= $field->as_string('abvxyz68');
990               } elsif ($record->field('150')) {
991           #    $heading.= $field->as_string('abvxyz68');
992           $heading.= $field->as_formatted();
993               my $tag=$field->tag();
994               $heading=~s /^$tag//g;
995               $heading =~s /\_/\$/g;
996               } elsif ($record->field('151')) {
997                                       $heading.= $field->as_string('avxyz68');
998               } elsif ($record->field('155')) {
999                                       $heading.= $field->as_string('abvxyz68');
1000               } elsif ($record->field('180')) {
1001                                       $heading.= $field->as_string('vxyz68');
1002               } elsif ($record->field('181')) {
1003                                       $heading.= $field->as_string('vxyz68');
1004               } elsif ($record->field('182')) {
1005                                       $heading.= $field->as_string('vxyz68');
1006               } elsif ($record->field('185')) {
1007                                       $heading.= $field->as_string('vxyz68');
1008               } else {
1009                   $heading.= $field->as_string();
1010               }
1011           } #See From
1012           foreach my $field ($record->field('4..')) {
1013               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1014           } #See Also
1015           foreach my $field ($record->field('5..')) {
1016               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1017           }
1018           $summary .= ": " if $summary;
1019           $summary.=$heading.$seeheading.$altheading;
1020       }
1021   }
1022   return $summary;
1023 }
1024
1025 sub _get_authid_subfield{
1026         my ($field)=@_;
1027         return $field->subfield('9')||$field->subfield('3');
1028 }
1029 =head2 BuildUnimarcHierarchies
1030
1031 =over 4
1032
1033 $text= &BuildUnimarcHierarchies( $authid, $force)
1034 return text containing trees for hierarchies
1035 for them to be stored in auth_header
1036
1037 Example of text:
1038 122,1314,2452;1324,2342,3,2452
1039
1040 =back
1041
1042 =cut
1043
1044 sub BuildUnimarcHierarchies{
1045   my $authid = shift @_;
1046 #   warn "authid : $authid";
1047   my $force = shift @_;
1048   my @globalresult;
1049   my $dbh=C4::Context->dbh;
1050   my $hierarchies;
1051   my $data = GetHeaderAuthority($authid);
1052   if ($data->{'authtrees'} and not $force){
1053     return $data->{'authtrees'};
1054 #  } elsif ($data->{'authtrees'}){
1055 #    $hierarchies=$data->{'authtrees'};
1056   } else {
1057     my $record = GetAuthority($authid);
1058     my $found;
1059     foreach my $field ($record->field('5..')){
1060       if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1061                 my $subfauthid=_get_authid_subfield($field);
1062         my $parentrecord = GetAuthority($subfauthid);
1063         my $localresult=$hierarchies;
1064         my $trees;
1065         $trees = BuildUnimarcHierarchies($subfauthid);
1066         my @trees;
1067         if ($trees=~/;/){
1068            @trees = split(/;/,$trees);
1069         } else {
1070            push @trees, $trees;
1071         }
1072         foreach (@trees){
1073           $_.= ",$authid";
1074         }
1075         @globalresult = (@globalresult,@trees);
1076         $found=1;
1077       }
1078       $hierarchies=join(";",@globalresult);
1079     }
1080     #Unless there is no ancestor, I am alone.
1081     $hierarchies="$authid" unless ($hierarchies);
1082   } 
1083   AddAuthorityTrees($authid,$hierarchies);
1084   return $hierarchies;
1085 }
1086
1087 =head2 BuildUnimarcHierarchy
1088
1089 =over 4
1090
1091 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1092 return a hashref in order to display hierarchy for record and final Authid $authid
1093
1094 "loopparents"
1095 "loopchildren"
1096 "class"
1097 "loopauthid"
1098 "current_value"
1099 "value"
1100
1101 "ifparents"  
1102 "ifchildren" 
1103 Those two latest ones should disappear soon.
1104
1105 =back
1106
1107 =cut
1108
1109 sub BuildUnimarcHierarchy{
1110   my $record = shift @_;
1111   my $class = shift @_;
1112   my $authid_constructed = shift @_;
1113   return unless $record;
1114   my $authid=$record->field('001')->data();
1115   my %cell;
1116   my $parents=""; my $children="";
1117   my (@loopparents,@loopchildren);
1118   foreach my $field ($record->field('5..')){
1119         my $subfauthid=_get_authid_subfield($field);
1120     if ($field->subfield('5') && $field->subfield('a')){
1121       if ($field->subfield('5') eq 'h'){
1122         push @loopchildren, { "childauthid"=>$subfauthid,"childvalue"=>$field->subfield('a')};
1123       }elsif ($field->subfield('5') eq 'g'){
1124         push @loopparents, { "parentauthid"=>$subfauthid,"parentvalue"=>$field->subfield('a')};
1125       }
1126           # brothers could get in there with an else
1127     }
1128   }
1129   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1130   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1131   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1132   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1133   $cell{"class"}=$class;
1134   $cell{"loopauthid"}=$authid;
1135   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1136   $cell{"value"}=$record->subfield('2..',"a");
1137   return \%cell;
1138 }
1139
1140 =head2 GetHeaderAuthority
1141
1142 =over 4
1143
1144 $ref= &GetHeaderAuthority( $authid)
1145 return a hashref in order auth_header table data
1146
1147 =back
1148
1149 =cut
1150
1151 sub GetHeaderAuthority{
1152   my $authid = shift @_;
1153   my $sql= "SELECT * from auth_header WHERE authid = ?";
1154   my $dbh=C4::Context->dbh;
1155   my $rq= $dbh->prepare($sql);
1156   $rq->execute($authid);
1157   my $data= $rq->fetchrow_hashref;
1158   return $data;
1159 }
1160
1161 =head2 AddAuthorityTrees
1162
1163 =over 4
1164
1165 $ref= &AddAuthorityTrees( $authid, $trees)
1166 return success or failure
1167
1168 =back
1169
1170 =cut
1171
1172 sub AddAuthorityTrees{
1173   my $authid = shift @_;
1174   my $trees = shift @_;
1175   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1176   my $dbh=C4::Context->dbh;
1177   my $rq= $dbh->prepare($sql);
1178   return $rq->execute($trees,$authid);
1179 }
1180
1181 =head2 merge
1182
1183 =over 4
1184
1185 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1186
1187
1188 Could add some feature : Migrating from a typecode to an other for instance.
1189 Then we should add some new parameter : bibliotargettag, authtargettag
1190
1191 =back
1192
1193 =cut
1194
1195 sub merge {
1196     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1197     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1198     my $dbh=C4::Context->dbh;
1199     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1200     my $authtypecodeto = GetAuthTypeCode($mergeto);
1201 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1202     # return if authority does not exist
1203     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1204     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1205     # search the tag to report
1206     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1207     $sth->execute($authtypecodefrom);
1208     my ($auth_tag_to_report_from) = $sth->fetchrow;
1209     $sth->execute($authtypecodeto);
1210     my ($auth_tag_to_report_to) = $sth->fetchrow;
1211     
1212     my @record_to;
1213     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1214     my @record_from;
1215     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1216     
1217     my @reccache;
1218     # search all biblio tags using this authority.
1219     #Getting marcbiblios impacted by the change.
1220     if (C4::Context->preference('NoZebra')) {
1221         #nozebra way    
1222         my $dbh=C4::Context->dbh;
1223         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1224         $rq->execute;
1225         while (my $biblionumbers=$rq->fetchrow){
1226             my @biblionumbers=split /;/,$biblionumbers;
1227             foreach (@biblionumbers) {
1228                 if ($_=~/(\d+),.*/) {
1229                     my $marc=GetMarcBiblio($1);
1230                     push @reccache,$marc;
1231                 }
1232             }
1233         }
1234     } else {
1235         #zebra connection  
1236         my $oConnection=C4::Context->Zconn("biblioserver",0);
1237         $oConnection->option("preferredRecordSyntax"=>"XML");
1238         my $query;
1239         $query= "an=".$mergefrom;
1240         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1241         my $count = 0;
1242         if  ($oResult) {
1243             $count=$oResult->size();
1244         }
1245         my $z=0;
1246         while ( $z<$count ) {
1247             my $rec;
1248             $rec=$oResult->record($z);
1249             my $marcdata = $rec->raw();
1250             push @reccache, $marcdata;
1251             $z++;
1252         }
1253         $oConnection->destroy();    
1254     }
1255     #warn scalar(@reccache)." biblios to update";
1256     # Get All candidate Tags for the change 
1257     # (This will reduce the search scope in marc records).
1258     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1259     $sth->execute($authtypecodefrom);
1260     my @tags_using_authtype;
1261     while (my ($tagfield) = $sth->fetchrow) {
1262         push @tags_using_authtype,$tagfield ;
1263     }
1264     my $tag_to=0;  
1265     if ($authtypecodeto ne $authtypecodefrom){  
1266         # If many tags, take the first
1267         $sth->execute($authtypecodeto);    
1268         $tag_to=$sth->fetchrow;
1269         #warn $tag_to;    
1270     }  
1271     # BulkEdit marc records
1272     # May be used as a template for a bulkedit field  
1273     foreach my $marcrecord(@reccache){
1274         my $update;           
1275         $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1276         foreach my $tagfield (@tags_using_authtype){
1277 #             warn "tagfield : $tagfield ";
1278             foreach my $field ($marcrecord->field($tagfield)){
1279                 my $auth_number=$field->subfield("9");
1280                 my $tag=$field->tag();          
1281                 if ($auth_number==$mergefrom) {
1282                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1283                 foreach my $subfield (@record_to) {
1284                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1285                 }
1286                 $marcrecord->delete_field($field);
1287                 $marcrecord->insert_grouped_field($field_to);            
1288                 $update=1;
1289                 }
1290             }#for each tag
1291         }#foreach tagfield
1292         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1293         my $biblionumber;
1294         if ($bibliotag<10){
1295             $biblionumber=$marcrecord->field($bibliotag)->data;
1296         }
1297         else {
1298             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1299         }
1300         unless ($biblionumber){
1301             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1302             next;
1303         }
1304         if ($update==1){
1305             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1306             $counteditedbiblio++;
1307             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1308         }    
1309     }#foreach $marc
1310     return $counteditedbiblio;  
1311   # now, find every other authority linked with this authority
1312   # now, find every other authority linked with this authority
1313 #   my $oConnection=C4::Context->Zconn("authorityserver");
1314 #   my $query;
1315 # # att 9210               Auth-Internal-authtype
1316 # # att 9220               Auth-Internal-LN
1317 # # ccl.properties to add for authorities
1318 #   $query= "= ".$mergefrom;
1319 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1320 #   my $count=$oResult->size() if  ($oResult);
1321 #   my @reccache;
1322 #   my $z=0;
1323 #   while ( $z<$count ) {
1324 #   my $rec;
1325 #           $rec=$oResult->record($z);
1326 #       my $marcdata = $rec->raw();
1327 #   push @reccache, $marcdata;
1328 #   $z++;
1329 #   }
1330 #   $oResult->destroy();
1331 #   foreach my $marc(@reccache){
1332 #     my $update;
1333 #     my $marcrecord;
1334 #     $marcrecord = MARC::File::USMARC::decode($marc);
1335 #     foreach my $tagfield (@tags_using_authtype){
1336 #       $tagfield=substr($tagfield,0,3);
1337 #       my @tags = $marcrecord->field($tagfield);
1338 #       foreach my $tag (@tags){
1339 #         my $tagsubs=$tag->subfield("9");
1340 #     #warn "$tagfield:$tagsubs:$mergefrom";
1341 #         if ($tagsubs== $mergefrom) {
1342 #           $tag->update("9" =>$mergeto);
1343 #           foreach my $subfield (@record_to) {
1344 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1345 #             $tag->update($subfield->[0] =>$subfield->[1]);
1346 #           }#for $subfield
1347 #         }
1348 #         $marcrecord->delete_field($tag);
1349 #         $marcrecord->add_fields($tag);
1350 #         $update=1;
1351 #       }#for each tag
1352 #     }#foreach tagfield
1353 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1354 #     if ($update==1){
1355 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1356 #     }
1357
1358 #   }#foreach $marc
1359 }#sub
1360
1361 =head2 get_auth_type_location
1362
1363 =over 4
1364
1365 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1366
1367 =back
1368
1369 Get the tag and subfield used to store the heading type
1370 for indexing purposes.  The C<$auth_type> parameter is
1371 optional; if it is not supplied, assume ''.
1372
1373 This routine searches the MARC authority framework
1374 for the tag and subfield whose kohafield is 
1375 C<auth_header.authtypecode>; if no such field is
1376 defined in the framework, default to the hardcoded value
1377 specific to the MARC format.
1378
1379 =cut
1380
1381 sub get_auth_type_location {
1382     my $auth_type_code = @_ ? shift : '';
1383
1384     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1385     if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1386         return ($tag, $subfield);
1387     } else {
1388         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1389             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1390         } else {
1391             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1392         }
1393     }
1394 }
1395
1396 END { }       # module clean-up code here (global destructor)
1397
1398 1;
1399 __END__
1400
1401 =head1 AUTHOR
1402
1403 Koha Developement team <info@koha.org>
1404
1405 Paul POULAIN paul.poulain@free.fr
1406
1407 =cut
1408