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