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