AuthoritiesMarc.pm Improvements
[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                 my $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= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
530   $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
531
532         if ($format eq "MARC21") {
533                 if (!$record->leader) {
534                         $record->leader($leader);
535                 }
536                 if (!$record->field('003')) {
537                         $record->insert_fields_ordered(
538                                 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
539                         );
540                 }
541                 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
542                 if (!$record->field('005')) {
543                         $record->insert_fields_ordered(
544                                 MARC::Field->new('005',$time.".0")
545                         );
546                 }
547                 my $date=POSIX::strftime("%y%m%d",localtime);
548                 if (!$record->field('008')) {
549                         $record->insert_fields_ordered(
550                                 MARC::Field->new('008',$date."|||a||||||           | |||     d")
551                         );
552                 }
553                 if (!$record->field('040')) {
554                  $record->insert_fields_ordered(
555         MARC::Field->new('040','','',
556                                 'a' => C4::Context->preference('MARCOrgCode'),
557                                 'c' => C4::Context->preference('MARCOrgCode')
558                                 ) 
559                         );
560     }
561         }
562
563   if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
564         $record->leader("     nx  j22             ");
565         my $date=POSIX::strftime("%Y%m%d",localtime);    
566         if ($record->field('100')){
567           $record->field('100')->update('a'=>$date."afrey50      ba0");
568         } else {      
569           $record->append_fields(
570             MARC::Field->new('100',' ',' '
571               ,'a'=>$date."afrey50      ba0")
572           );
573         }      
574   }
575   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
576   if (!$authid and $format eq "MARC21") {
577     # only need to do this fix when modifying an existing authority
578     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
579   } 
580   if (my $field=$record->field($auth_type_tag)){
581     $field->update($auth_type_subfield=>$authtypecode);
582   }
583   else {
584     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
585   }
586
587   my $auth_exists=0;
588   my $oldRecord;
589   if (!$authid) {
590     my $sth=$dbh->prepare("select max(authid) from auth_header");
591     $sth->execute;
592     ($authid)=$sth->fetchrow;
593     $authid=$authid+1;
594   ##Insert the recordID in MARC record 
595     unless ($record->field('001') && $record->field('001')->data() eq $authid){
596         $record->delete_field($record->field('001'));
597         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
598     }
599   } else {
600     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
601 #     warn "auth_exists = $auth_exists";
602   }
603   if ($auth_exists>0){
604       $oldRecord=GetAuthority($authid);
605       $record->add_fields('001',$authid) unless ($record->field('001'));
606 #       warn "\n\n\n enregistrement".$record->as_formatted;
607       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
608       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
609       $sth->finish;
610   }
611   else {
612     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
613     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
614     $sth->finish;
615   }
616   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
617   return ($authid);
618 }
619
620
621 =head2 DelAuthority
622
623 =over 4
624
625 $authid= &DelAuthority($authid)
626 Deletes $authid
627
628 =back
629
630 =cut
631
632
633 sub DelAuthority {
634     my ($authid) = @_;
635     my $dbh=C4::Context->dbh;
636
637     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
638     $dbh->do("delete from auth_header where authid=$authid") ;
639
640 }
641
642 sub ModAuthority {
643   my ($authid,$record,$authtypecode,$merge)=@_;
644   my $dbh=C4::Context->dbh;
645   #Now rewrite the $record to table with an add
646   my $oldrecord=GetAuthority($authid);
647   $authid=AddAuthority($record,$authid,$authtypecode);
648
649 ### 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
650 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
651 ### the $merge flag is now depreceated and will be removed at code cleaning
652   if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
653       &merge($authid,$oldrecord,$authid,$record);
654   } else {
655   # save the file in tmp/modified_authorities
656       my $cgidir = C4::Context->intranetdir ."/cgi-bin";
657       unless (opendir(DIR,"$cgidir")) {
658               $cgidir = C4::Context->intranetdir."/";
659               closedir(DIR);
660       }
661   
662       my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
663       open AUTH, "> $filename";
664       print AUTH $authid;
665       close AUTH;
666   }
667   return $authid;
668 }
669
670 =head2 GetAuthorityXML 
671
672 =over 4
673
674 $marcxml= &GetAuthorityXML( $authid)
675 returns xml form of record $authid
676
677 =back
678
679 =cut
680
681 sub GetAuthorityXML {
682   # Returns MARC::XML of the authority passed in parameter.
683   my ( $authid ) = @_;
684   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
685       my $dbh=C4::Context->dbh;
686       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
687       $sth->execute($authid);
688       my ($marcxml)=$sth->fetchrow;
689       return $marcxml;
690   }
691   else { 
692       # for MARC21, call GetAuthority instead of
693       # getting the XML directly since we may
694       # need to fix up the location of the authority
695       # code -- note that this is reasonably safe
696       # because GetAuthorityXML is used only by the 
697       # indexing processes like zebraqueue_start.pl
698       my $record = GetAuthority($authid);
699       return $record->as_xml_record('MARC21');
700   }
701 }
702
703 =head2 GetAuthority 
704
705 =over 4
706
707 $record= &GetAuthority( $authid)
708 Returns MARC::Record of the authority passed in parameter.
709
710 =back
711
712 =cut
713
714 sub GetAuthority {
715     my ($authid)=@_;
716     my $dbh=C4::Context->dbh;
717     my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
718     $sth->execute($authid);
719     my ($authtypecode, $marcxml) = $sth->fetchrow;
720     my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
721         (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
722     return undef if ($@);
723     $record->encoding('UTF-8');
724     if (C4::Context->preference("marcflavour") eq "MARC21") {
725       my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
726       C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
727     }
728     return ($record);
729 }
730
731 =head2 GetAuthType 
732
733 =over 4
734
735 $result = &GetAuthType($authtypecode)
736
737 =back
738
739 If the authority type specified by C<$authtypecode> exists,
740 returns a hashref of the type's fields.  If the type
741 does not exist, returns undef.
742
743 =cut
744
745 sub GetAuthType {
746     my ($authtypecode) = @_;
747     my $dbh=C4::Context->dbh;
748     my $sth;
749     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
750                                 # type (FIXME but why?)
751         $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
752         $sth->execute($authtypecode);
753         if (my $res = $sth->fetchrow_hashref) {
754             return $res; 
755         }
756     }
757     return;
758 }
759
760
761 sub AUTHhtml2marc {
762     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
763     my $dbh=C4::Context->dbh;
764     my $prevtag = -1;
765     my $record = MARC::Record->new();
766 #---- TODO : the leader is missing
767
768 #     my %subfieldlist=();
769     my $prevvalue; # if tag <10
770     my $field; # if tag >=10
771     for (my $i=0; $i< @$rtags; $i++) {
772         # rebuild MARC::Record
773         if (@$rtags[$i] ne $prevtag) {
774             if ($prevtag < 10) {
775                 if ($prevvalue) {
776                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
777                 }
778             } else {
779                 if ($field) {
780                     $record->add_fields($field);
781                 }
782             }
783             $indicators{@$rtags[$i]}.='  ';
784             if (@$rtags[$i] <10) {
785                 $prevvalue= @$rvalues[$i];
786                 undef $field;
787             } else {
788                 undef $prevvalue;
789                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
790             }
791             $prevtag = @$rtags[$i];
792         } else {
793             if (@$rtags[$i] <10) {
794                 $prevvalue=@$rvalues[$i];
795             } else {
796                 if (length(@$rvalues[$i])>0) {
797                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
798                 }
799             }
800             $prevtag= @$rtags[$i];
801         }
802     }
803     # the last has not been included inside the loop... do it now !
804     $record->add_fields($field) if $field;
805     return $record;
806 }
807
808 =head2 FindDuplicateAuthority
809
810 =over 4
811
812 $record= &FindDuplicateAuthority( $record, $authtypecode)
813 return $authid,Summary if duplicate is found.
814
815 Comments : an improvement would be to return All the records that match.
816
817 =back
818
819 =cut
820
821 sub FindDuplicateAuthority {
822
823     my ($record,$authtypecode)=@_;
824 #    warn "IN for ".$record->as_formatted;
825     my $dbh = C4::Context->dbh;
826 #    warn "".$record->as_formatted;
827     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
828     $sth->execute($authtypecode);
829     my ($auth_tag_to_report) = $sth->fetchrow;
830     $sth->finish;
831 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
832     # build a request for SearchAuthorities
833     my $query='at='.$authtypecode.' ';
834     my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
835     if ($record->field($auth_tag_to_report)) {
836       foreach ($record->field($auth_tag_to_report)->subfields()) {
837         $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
838       }
839     }
840     my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
841     # there is at least 1 result => return the 1st one
842     if (@$results>0) {
843       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
844       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
845     }
846     # no result, returns nothing
847     return;
848 }
849
850 =head2 BuildSummary
851
852 =over 4
853
854 $text= &BuildSummary( $record, $authid, $authtypecode)
855 return HTML encoded Summary
856
857 Comment : authtypecode can be infered from both record and authid.
858 Moreover, authid can also be inferred from $record.
859 Would it be interesting to delete those things.
860
861 =back
862
863 =cut
864
865 sub BuildSummary{
866 ## give this a Marc record to return summary
867   my ($record,$authid,$authtypecode)=@_;
868   my $dbh=C4::Context->dbh;
869   my $summary;
870   # handle $authtypecode is NULL or eq ""
871   if ($authtypecode) {
872         my $authref = GetAuthType($authtypecode);
873         $summary = $authref->{summary};
874   }
875   # FIXME: should use I18N.pm
876   my %language;
877   $language{'fre'}="Français";
878   $language{'eng'}="Anglais";
879   $language{'ger'}="Allemand";
880   $language{'ita'}="Italien";
881   $language{'spa'}="Espagnol";
882   my %thesaurus;
883   $thesaurus{'1'}="Peuples";
884   $thesaurus{'2'}="Anthroponymes";
885   $thesaurus{'3'}="Oeuvres";
886   $thesaurus{'4'}="Chronologie";
887   $thesaurus{'5'}="Lieux";
888   $thesaurus{'6'}="Sujets";
889   #thesaurus a remplir
890   my @fields = $record->fields();
891   my $reported_tag;
892   # if the library has a summary defined, use it. Otherwise, build a standard one
893   # FIXME - it appears that the summary field in the authority frameworks
894   #         can work as a display template.  However, this doesn't
895   #         suit the MARC21 version, so for now the "templating"
896   #         feature will be enabled only for UNIMARC for backwards
897   #         compatibility.
898   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
899     my @fields = $record->fields();
900     #             $reported_tag = '$9'.$result[$counter];
901     foreach my $field (@fields) {
902       my $tag = $field->tag();
903       my $tagvalue = $field->as_string();
904       $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
905       if ($tag<10) {
906         if ($tag eq '001') {
907           $reported_tag.='$3'.$field->data();
908         }
909       } else {
910         my @subf = $field->subfields;
911         for my $i (0..$#subf) {
912           my $subfieldcode = $subf[$i][0];
913           my $subfieldvalue = $subf[$i][1];
914           my $tagsubf = $tag.$subfieldcode;
915           $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
916         }
917       }
918     }
919     $summary =~ s/\[(.*?)]//g;
920     $summary =~ s/\n/<br>/g;
921   } else {
922     my $heading; 
923     my $authid; 
924     my $altheading;
925     my $seealso;
926     my $broaderterms;
927     my $narrowerterms;
928     my $see;
929     my $seeheading;
930         my $notes;
931     my @fields = $record->fields();
932     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
933     # construct UNIMARC summary, that is quite different from MARC21 one
934       # accepted form
935       foreach my $field ($record->field('2..')) {
936         $heading.= $field->subfield('a');
937                 $authid=$field->subfield('3');
938       }
939       # rejected form(s)
940       foreach my $field ($record->field('3..')) {
941         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
942       }
943       foreach my $field ($record->field('4..')) {
944         if ($field->subfield('2')) {
945             my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
946             $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
947         }
948       }
949       # see :
950       foreach my $field ($record->field('5..')) {
951             
952         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
953           $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
954         } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
955           $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
956         } elsif ($field->subfield('a')) {
957           $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
958         }
959       }
960       # // form
961       foreach my $field ($record->field('7..')) {
962         my $lang = substr($field->subfield('8'),3,3);
963         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
964       }
965             $broaderterms =~s/-- \n$//;
966             $narrowerterms =~s/-- \n$//;
967             $seealso =~s/-- \n$//;
968             $see =~s/-- \n$//;
969       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
970       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
971       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
972       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
973       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
974       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
975       } else {
976       # construct MARC21 summary
977           # FIXME - looping over 1XX is questionable
978           # since MARC21 authority should have only one 1XX
979           foreach my $field ($record->field('1..')) {
980               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
981                                               # in MARC21 -- purely local tags really ought to be
982                                               # 9XX
983               if ($record->field('100')) {
984                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
985               } elsif ($record->field('110')) {
986                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
987               } elsif ($record->field('111')) {
988                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
989               } elsif ($record->field('130')) {
990                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
991               } elsif ($record->field('148')) {
992                                       $heading.= $field->as_string('abvxyz68');
993               } elsif ($record->field('150')) {
994           #    $heading.= $field->as_string('abvxyz68');
995           $heading.= $field->as_formatted();
996               my $tag=$field->tag();
997               $heading=~s /^$tag//g;
998               $heading =~s /\_/\$/g;
999               } elsif ($record->field('151')) {
1000                                       $heading.= $field->as_string('avxyz68');
1001               } elsif ($record->field('155')) {
1002                                       $heading.= $field->as_string('abvxyz68');
1003               } elsif ($record->field('180')) {
1004                                       $heading.= $field->as_string('vxyz68');
1005               } elsif ($record->field('181')) {
1006                                       $heading.= $field->as_string('vxyz68');
1007               } elsif ($record->field('182')) {
1008                                       $heading.= $field->as_string('vxyz68');
1009               } elsif ($record->field('185')) {
1010                                       $heading.= $field->as_string('vxyz68');
1011               } else {
1012                   $heading.= $field->as_string();
1013               }
1014           } #See From
1015           foreach my $field ($record->field('4..')) {
1016               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1017           } #See Also
1018           foreach my $field ($record->field('5..')) {
1019               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1020           }
1021           $summary .= ": " if $summary;
1022           $summary.=$heading.$seeheading.$altheading;
1023       }
1024   }
1025   return $summary;
1026 }
1027
1028 =head2 BuildUnimarcHierarchies
1029
1030 =over 4
1031
1032 $text= &BuildUnimarcHierarchies( $authid, $force)
1033 return text containing trees for hierarchies
1034 for them to be stored in auth_header
1035
1036 Example of text:
1037 122,1314,2452;1324,2342,3,2452
1038
1039 =back
1040
1041 =cut
1042
1043 sub BuildUnimarcHierarchies{
1044   my $authid = shift @_;
1045 #   warn "authid : $authid";
1046   my $force = shift @_;
1047   my @globalresult;
1048   my $dbh=C4::Context->dbh;
1049   my $hierarchies;
1050   my $data = GetHeaderAuthority($authid);
1051   if ($data->{'authtrees'} and not $force){
1052     return $data->{'authtrees'};
1053   } elsif ($data->{'authtrees'}){
1054     $hierarchies=$data->{'authtrees'};
1055   } else {
1056     my $record = GetAuthority($authid);
1057     my $found;
1058     foreach my $field ($record->field('550')){
1059       if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1060         my $parentrecord = GetAuthority($field->subfield('3'));
1061         my $localresult=$hierarchies;
1062         my $trees;
1063         $trees = BuildUnimarcHierarchies($field->subfield('3'));
1064         my @trees;
1065         if ($trees=~/;/){
1066            @trees = split(/;/,$trees);
1067         } else {
1068            push @trees, $trees;
1069         }
1070         foreach (@trees){
1071           $_.= ",$authid";
1072         }
1073         @globalresult = (@globalresult,@trees);
1074         $found=1;
1075       }
1076       $hierarchies=join(";",@globalresult);
1077     }
1078     #Unless there is no ancestor, I am alone.
1079     $hierarchies="$authid" unless ($hierarchies);
1080   }
1081   AddAuthorityTrees($authid,$hierarchies);
1082   return $hierarchies;
1083 }
1084
1085 =head2 BuildUnimarcHierarchy
1086
1087 =over 4
1088
1089 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1090 return a hashref in order to display hierarchy for record and final Authid $authid
1091
1092 "loopparents"
1093 "loopchildren"
1094 "class"
1095 "loopauthid"
1096 "current_value"
1097 "value"
1098
1099 "ifparents"  
1100 "ifchildren" 
1101 Those two latest ones should disappear soon.
1102
1103 =back
1104
1105 =cut
1106
1107 sub BuildUnimarcHierarchy{
1108   my $record = shift @_;
1109   my $class = shift @_;
1110   my $authid_constructed = shift @_;
1111   my $authid=$record->subfield('2..','3');
1112   my %cell;
1113   my $parents=""; my $children="";
1114   my (@loopparents,@loopchildren);
1115   foreach my $field ($record->field('550')){
1116     if ($field->subfield('5') && $field->subfield('a')){
1117       if ($field->subfield('5') eq 'h'){
1118         push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1119       }elsif ($field->subfield('5') eq 'g'){
1120         push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1121       }
1122           # brothers could get in there with an else
1123     }
1124   }
1125   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1126   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1127   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1128   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1129   $cell{"class"}=$class;
1130   $cell{"loopauthid"}=$authid;
1131   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1132   $cell{"value"}=$record->subfield('2..',"a");
1133   return \%cell;
1134 }
1135
1136 =head2 GetHeaderAuthority
1137
1138 =over 4
1139
1140 $ref= &GetHeaderAuthority( $authid)
1141 return a hashref in order auth_header table data
1142
1143 =back
1144
1145 =cut
1146
1147 sub GetHeaderAuthority{
1148   my $authid = shift @_;
1149   my $sql= "SELECT * from auth_header WHERE authid = ?";
1150   my $dbh=C4::Context->dbh;
1151   my $rq= $dbh->prepare($sql);
1152   $rq->execute($authid);
1153   my $data= $rq->fetchrow_hashref;
1154   return $data;
1155 }
1156
1157 =head2 AddAuthorityTrees
1158
1159 =over 4
1160
1161 $ref= &AddAuthorityTrees( $authid, $trees)
1162 return success or failure
1163
1164 =back
1165
1166 =cut
1167
1168 sub AddAuthorityTrees{
1169   my $authid = shift @_;
1170   my $trees = shift @_;
1171   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1172   my $dbh=C4::Context->dbh;
1173   my $rq= $dbh->prepare($sql);
1174   return $rq->execute($trees,$authid);
1175 }
1176
1177 =head2 merge
1178
1179 =over 4
1180
1181 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1182
1183
1184 Could add some feature : Migrating from a typecode to an other for instance.
1185 Then we should add some new parameter : bibliotargettag, authtargettag
1186
1187 =back
1188
1189 =cut
1190
1191 sub merge {
1192     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1193     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1194     my $dbh=C4::Context->dbh;
1195     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1196     my $authtypecodeto = GetAuthTypeCode($mergeto);
1197 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1198     # return if authority does not exist
1199     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1200     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1201     # search the tag to report
1202     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1203     $sth->execute($authtypecodefrom);
1204     my ($auth_tag_to_report_from) = $sth->fetchrow;
1205     $sth->execute($authtypecodeto);
1206     my ($auth_tag_to_report_to) = $sth->fetchrow;
1207     
1208     my @record_to;
1209     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1210     my @record_from;
1211     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1212     
1213     my @reccache;
1214     # search all biblio tags using this authority.
1215     #Getting marcbiblios impacted by the change.
1216     if (C4::Context->preference('NoZebra')) {
1217         #nozebra way    
1218         my $dbh=C4::Context->dbh;
1219         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1220         $rq->execute;
1221         while (my $biblionumbers=$rq->fetchrow){
1222             my @biblionumbers=split /;/,$biblionumbers;
1223             foreach (@biblionumbers) {
1224                 if ($_=~/(\d+),.*/) {
1225                     my $marc=GetMarcBiblio($1);
1226                     push @reccache,$marc;
1227                 }
1228             }
1229         }
1230     } else {
1231         #zebra connection  
1232         my $oConnection=C4::Context->Zconn("biblioserver",0);
1233         $oConnection->option("preferredRecordSyntax"=>"XML");
1234         my $query;
1235         $query= "an=".$mergefrom;
1236         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1237         my $count = 0;
1238         if  ($oResult) {
1239             $count=$oResult->size();
1240         }
1241         my $z=0;
1242         while ( $z<$count ) {
1243             my $rec;
1244             $rec=$oResult->record($z);
1245             my $marcdata = $rec->raw();
1246             push @reccache, $marcdata;
1247             $z++;
1248         }
1249         $oConnection->destroy();    
1250     }
1251     #warn scalar(@reccache)." biblios to update";
1252     # Get All candidate Tags for the change 
1253     # (This will reduce the search scope in marc records).
1254     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1255     $sth->execute($authtypecodefrom);
1256     my @tags_using_authtype;
1257     while (my ($tagfield) = $sth->fetchrow) {
1258         push @tags_using_authtype,$tagfield ;
1259     }
1260     my $tag_to=0;  
1261     if ($authtypecodeto ne $authtypecodefrom){  
1262         # If many tags, take the first
1263         $sth->execute($authtypecodeto);    
1264         $tag_to=$sth->fetchrow;
1265         #warn $tag_to;    
1266     }  
1267     # BulkEdit marc records
1268     # May be used as a template for a bulkedit field  
1269     foreach my $marcrecord(@reccache){
1270         my $update;           
1271         $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1272         foreach my $tagfield (@tags_using_authtype){
1273 #             warn "tagfield : $tagfield ";
1274             foreach my $field ($marcrecord->field($tagfield)){
1275                 my $auth_number=$field->subfield("9");
1276                 my $tag=$field->tag();          
1277                 if ($auth_number==$mergefrom) {
1278                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1279                 foreach my $subfield (@record_to) {
1280                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1281                 }
1282                 $marcrecord->delete_field($field);
1283                 $marcrecord->insert_grouped_field($field_to);            
1284                 $update=1;
1285                 }
1286             }#for each tag
1287         }#foreach tagfield
1288         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1289         my $biblionumber;
1290         if ($bibliotag<10){
1291             $biblionumber=$marcrecord->field($bibliotag)->data;
1292         }
1293         else {
1294             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1295         }
1296         unless ($biblionumber){
1297             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1298             next;
1299         }
1300         if ($update==1){
1301             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1302             $counteditedbiblio++;
1303             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1304         }    
1305     }#foreach $marc
1306     return $counteditedbiblio;  
1307   # now, find every other authority linked with this authority
1308   # now, find every other authority linked with this authority
1309 #   my $oConnection=C4::Context->Zconn("authorityserver");
1310 #   my $query;
1311 # # att 9210               Auth-Internal-authtype
1312 # # att 9220               Auth-Internal-LN
1313 # # ccl.properties to add for authorities
1314 #   $query= "= ".$mergefrom;
1315 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1316 #   my $count=$oResult->size() if  ($oResult);
1317 #   my @reccache;
1318 #   my $z=0;
1319 #   while ( $z<$count ) {
1320 #   my $rec;
1321 #           $rec=$oResult->record($z);
1322 #       my $marcdata = $rec->raw();
1323 #   push @reccache, $marcdata;
1324 #   $z++;
1325 #   }
1326 #   $oResult->destroy();
1327 #   foreach my $marc(@reccache){
1328 #     my $update;
1329 #     my $marcrecord;
1330 #     $marcrecord = MARC::File::USMARC::decode($marc);
1331 #     foreach my $tagfield (@tags_using_authtype){
1332 #       $tagfield=substr($tagfield,0,3);
1333 #       my @tags = $marcrecord->field($tagfield);
1334 #       foreach my $tag (@tags){
1335 #         my $tagsubs=$tag->subfield("9");
1336 #     #warn "$tagfield:$tagsubs:$mergefrom";
1337 #         if ($tagsubs== $mergefrom) {
1338 #           $tag->update("9" =>$mergeto);
1339 #           foreach my $subfield (@record_to) {
1340 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1341 #             $tag->update($subfield->[0] =>$subfield->[1]);
1342 #           }#for $subfield
1343 #         }
1344 #         $marcrecord->delete_field($tag);
1345 #         $marcrecord->add_fields($tag);
1346 #         $update=1;
1347 #       }#for each tag
1348 #     }#foreach tagfield
1349 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1350 #     if ($update==1){
1351 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1352 #     }
1353
1354 #   }#foreach $marc
1355 }#sub
1356
1357 =head2 get_auth_type_location
1358
1359 =over 4
1360
1361 my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1362
1363 =back
1364
1365 Get the tag and subfield used to store the heading type
1366 for indexing purposes.  The C<$auth_type> parameter is
1367 optional; if it is not supplied, assume ''.
1368
1369 This routine searches the MARC authority framework
1370 for the tag and subfield whose kohafield is 
1371 C<auth_header.authtypecode>; if no such field is
1372 defined in the framework, default to the hardcoded value
1373 specific to the MARC format.
1374
1375 =cut
1376
1377 sub get_auth_type_location {
1378     my $auth_type_code = @_ ? shift : '';
1379
1380     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1381     if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1382         return ($tag, $subfield);
1383     } else {
1384         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1385             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1386         } else {
1387             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1388         }
1389     }
1390 }
1391
1392 END { }       # module clean-up code here (global destructor)
1393
1394 1;
1395 __END__
1396
1397 =head1 AUTHOR
1398
1399 Koha Developement team <info@koha.org>
1400
1401 Paul POULAIN paul.poulain@free.fr
1402
1403 =cut
1404