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