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