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