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