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