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