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