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