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