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