Merge remote branch 'kc/new/enh/bug_3659' 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         if ($format eq "MARC21") {
628                 if (!$record->leader) {
629                         $record->leader($leader);
630                 }
631                 if (!$record->field('003')) {
632                         $record->insert_fields_ordered(
633                                 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
634                         );
635                 }
636                 my $date=POSIX::strftime("%y%m%d",localtime);
637                 if (!$record->field('008')) {
638                         $record->insert_fields_ordered(
639                                 MARC::Field->new('008',$date."|||a||||||           | |||     d")
640                         );
641                 }
642                 if (!$record->field('040')) {
643                  $record->insert_fields_ordered(
644         MARC::Field->new('040','','',
645                                 'a' => C4::Context->preference('MARCOrgCode'),
646                                 'c' => C4::Context->preference('MARCOrgCode')
647                                 ) 
648                         );
649     }
650         }
651
652   if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
653         $record->leader("     nx  j22             ");
654         my $date=POSIX::strftime("%Y%m%d",localtime);    
655         if ($record->field('100')){
656           $record->field('100')->update('a'=>$date."afrey50      ba0");
657         } else {      
658           $record->append_fields(
659             MARC::Field->new('100',' ',' '
660               ,'a'=>$date."afrey50      ba0")
661           );
662         }      
663   }
664   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
665   if (!$authid and $format eq "MARC21") {
666     # only need to do this fix when modifying an existing authority
667     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
668   } 
669   if (my $field=$record->field($auth_type_tag)){
670     $field->update($auth_type_subfield=>$authtypecode);
671   }
672   else {
673     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
674   }
675
676   my $auth_exists=0;
677   my $oldRecord;
678   if (!$authid) {
679     my $sth=$dbh->prepare("select max(authid) from auth_header");
680     $sth->execute;
681     ($authid)=$sth->fetchrow;
682     $authid=$authid+1;
683   ##Insert the recordID in MARC record 
684     unless ($record->field('001') && $record->field('001')->data() eq $authid){
685         $record->delete_field($record->field('001'));
686         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
687     }
688   } else {
689     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
690 #     warn "auth_exists = $auth_exists";
691   }
692   if ($auth_exists>0){
693       $oldRecord=GetAuthority($authid);
694       $record->add_fields('001',$authid) unless ($record->field('001'));
695 #       warn "\n\n\n enregistrement".$record->as_formatted;
696       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
697       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
698       $sth->finish;
699   }
700   else {
701     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
702     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
703     $sth->finish;
704     logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
705   }
706   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
707   return ($authid);
708 }
709
710
711 =head2 DelAuthority
712
713   $authid= &DelAuthority($authid)
714
715 Deletes $authid
716
717 =cut
718
719 sub DelAuthority {
720     my ($authid) = @_;
721     my $dbh=C4::Context->dbh;
722
723     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
724     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
725     my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
726     $sth->execute($authid);
727 }
728
729 sub ModAuthority {
730   my ($authid,$record,$authtypecode,$merge)=@_;
731   my $dbh=C4::Context->dbh;
732   #Now rewrite the $record to table with an add
733   my $oldrecord=GetAuthority($authid);
734   $authid=AddAuthority($record,$authid,$authtypecode);
735
736 ### 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
737 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
738 ### the $merge flag is now depreceated and will be removed at code cleaning
739   if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
740       &merge($authid,$oldrecord,$authid,$record);
741   } else {
742   # save the file in tmp/modified_authorities
743       my $cgidir = C4::Context->intranetdir ."/cgi-bin";
744       unless (opendir(DIR,"$cgidir")) {
745               $cgidir = C4::Context->intranetdir."/";
746               closedir(DIR);
747       }
748   
749       my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
750       open AUTH, "> $filename";
751       print AUTH $authid;
752       close AUTH;
753   }
754   logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
755   return $authid;
756 }
757
758 =head2 GetAuthorityXML 
759
760   $marcxml= &GetAuthorityXML( $authid)
761
762 returns xml form of record $authid
763
764 =cut
765
766 sub GetAuthorityXML {
767   # Returns MARC::XML of the authority passed in parameter.
768   my ( $authid ) = @_;
769   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
770       my $dbh=C4::Context->dbh;
771       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
772       $sth->execute($authid);
773       my ($marcxml)=$sth->fetchrow;
774       return $marcxml;
775   }
776   else { 
777       # for MARC21, call GetAuthority instead of
778       # getting the XML directly since we may
779       # need to fix up the location of the authority
780       # code -- note that this is reasonably safe
781       # because GetAuthorityXML is used only by the 
782       # indexing processes like zebraqueue_start.pl
783       my $record = GetAuthority($authid);
784       return $record->as_xml_record('MARC21');
785   }
786 }
787
788 =head2 GetAuthority 
789
790   $record= &GetAuthority( $authid)
791
792 Returns MARC::Record of the authority passed in parameter.
793
794 =cut
795
796 sub GetAuthority {
797     my ($authid)=@_;
798     my $dbh=C4::Context->dbh;
799     my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
800     $sth->execute($authid);
801     my ($authtypecode, $marcxml) = $sth->fetchrow;
802     my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
803         (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
804     return undef if ($@);
805     $record->encoding('UTF-8');
806     if (C4::Context->preference("marcflavour") eq "MARC21") {
807       my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
808       C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
809     }
810     return ($record);
811 }
812
813 =head2 GetAuthType 
814
815   $result = &GetAuthType($authtypecode)
816
817 If the authority type specified by C<$authtypecode> exists,
818 returns a hashref of the type's fields.  If the type
819 does not exist, returns undef.
820
821 =cut
822
823 sub GetAuthType {
824     my ($authtypecode) = @_;
825     my $dbh=C4::Context->dbh;
826     my $sth;
827     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
828                                 # type (FIXME but why?)
829         $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
830         $sth->execute($authtypecode);
831         if (my $res = $sth->fetchrow_hashref) {
832             return $res; 
833         }
834     }
835     return;
836 }
837
838
839 sub AUTHhtml2marc {
840     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
841     my $dbh=C4::Context->dbh;
842     my $prevtag = -1;
843     my $record = MARC::Record->new();
844 #---- TODO : the leader is missing
845
846 #     my %subfieldlist=();
847     my $prevvalue; # if tag <10
848     my $field; # if tag >=10
849     for (my $i=0; $i< @$rtags; $i++) {
850         # rebuild MARC::Record
851         if (@$rtags[$i] ne $prevtag) {
852             if ($prevtag < 10) {
853                 if ($prevvalue) {
854                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
855                 }
856             } else {
857                 if ($field) {
858                     $record->add_fields($field);
859                 }
860             }
861             $indicators{@$rtags[$i]}.='  ';
862             if (@$rtags[$i] <10) {
863                 $prevvalue= @$rvalues[$i];
864                 undef $field;
865             } else {
866                 undef $prevvalue;
867                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
868             }
869             $prevtag = @$rtags[$i];
870         } else {
871             if (@$rtags[$i] <10) {
872                 $prevvalue=@$rvalues[$i];
873             } else {
874                 if (length(@$rvalues[$i])>0) {
875                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
876                 }
877             }
878             $prevtag= @$rtags[$i];
879         }
880     }
881     # the last has not been included inside the loop... do it now !
882     $record->add_fields($field) if $field;
883     return $record;
884 }
885
886 =head2 FindDuplicateAuthority
887
888   $record= &FindDuplicateAuthority( $record, $authtypecode)
889
890 return $authid,Summary if duplicate is found.
891
892 Comments : an improvement would be to return All the records that match.
893
894 =cut
895
896 sub FindDuplicateAuthority {
897
898     my ($record,$authtypecode)=@_;
899 #    warn "IN for ".$record->as_formatted;
900     my $dbh = C4::Context->dbh;
901 #    warn "".$record->as_formatted;
902     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
903     $sth->execute($authtypecode);
904     my ($auth_tag_to_report) = $sth->fetchrow;
905     $sth->finish;
906 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
907     # build a request for SearchAuthorities
908     my $query='at='.$authtypecode.' ';
909     my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
910     if ($record->field($auth_tag_to_report)) {
911       foreach ($record->field($auth_tag_to_report)->subfields()) {
912         $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
913       }
914     }
915     my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
916     # there is at least 1 result => return the 1st one
917     if (@$results>0) {
918       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
919       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
920     }
921     # no result, returns nothing
922     return;
923 }
924
925 =head2 BuildSummary
926
927   $text= &BuildSummary( $record, $authid, $authtypecode)
928
929 return HTML encoded Summary
930
931 Comment : authtypecode can be infered from both record and authid.
932 Moreover, authid can also be inferred from $record.
933 Would it be interesting to delete those things.
934
935 =cut
936
937 sub BuildSummary{
938 ## give this a Marc record to return summary
939   my ($record,$authid,$authtypecode)=@_;
940   my $dbh=C4::Context->dbh;
941   my $summary;
942   # handle $authtypecode is NULL or eq ""
943   if ($authtypecode) {
944         my $authref = GetAuthType($authtypecode);
945         $summary = $authref->{summary};
946   }
947   # FIXME: should use I18N.pm
948   my %language;
949   $language{'fre'}="Français";
950   $language{'eng'}="Anglais";
951   $language{'ger'}="Allemand";
952   $language{'ita'}="Italien";
953   $language{'spa'}="Espagnol";
954   my %thesaurus;
955   $thesaurus{'1'}="Peuples";
956   $thesaurus{'2'}="Anthroponymes";
957   $thesaurus{'3'}="Oeuvres";
958   $thesaurus{'4'}="Chronologie";
959   $thesaurus{'5'}="Lieux";
960   $thesaurus{'6'}="Sujets";
961   #thesaurus a remplir
962   my @fields = $record->fields();
963   my $reported_tag;
964   # if the library has a summary defined, use it. Otherwise, build a standard one
965   # FIXME - it appears that the summary field in the authority frameworks
966   #         can work as a display template.  However, this doesn't
967   #         suit the MARC21 version, so for now the "templating"
968   #         feature will be enabled only for UNIMARC for backwards
969   #         compatibility.
970   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
971     my @fields = $record->fields();
972     #             $reported_tag = '$9'.$result[$counter];
973         my @stringssummary;
974     foreach my $field (@fields) {
975       my $tag = $field->tag();
976       my $tagvalue = $field->as_string();
977       my $localsummary= $summary;
978           $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
979       if ($tag<10) {
980         if ($tag eq '001') {
981           $reported_tag.='$3'.$field->data();
982         }
983       } else {
984         my @subf = $field->subfields;
985         for my $i (0..$#subf) {
986           my $subfieldcode = $subf[$i][0];
987           my $subfieldvalue = $subf[$i][1];
988           my $tagsubf = $tag.$subfieldcode;
989           $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
990         }
991       }
992           push @stringssummary, $localsummary if ($localsummary ne $summary);
993     }
994         my $resultstring;
995         $resultstring = join(" -- ",@stringssummary);
996     $resultstring =~ s/\[(.*?)\]//g;
997     $resultstring =~ s/\n/<br>/g;
998         $summary      =  $resultstring;
999   } else {
1000     my $heading; 
1001     my $altheading;
1002     my $seealso;
1003     my $broaderterms;
1004     my $narrowerterms;
1005     my $see;
1006     my $seeheading;
1007         my $notes;
1008     my @fields = $record->fields();
1009     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1010     # construct UNIMARC summary, that is quite different from MARC21 one
1011       # accepted form
1012       foreach my $field ($record->field('2..')) {
1013         $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1014       }
1015       # rejected form(s)
1016       foreach my $field ($record->field('3..')) {
1017         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1018       }
1019       foreach my $field ($record->field('4..')) {
1020         if ($field->subfield('2')) {
1021             my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1022             $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1023         }
1024       }
1025       # see :
1026       foreach my $field ($record->field('5..')) {
1027             
1028         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1029           $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1030         } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1031           $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1032         } elsif ($field->subfield('a')) {
1033           $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1034         }
1035       }
1036       # // form
1037       foreach my $field ($record->field('7..')) {
1038         my $lang = substr($field->subfield('8'),3,3);
1039         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
1040       }
1041             $broaderterms =~s/-- \n$//;
1042             $narrowerterms =~s/-- \n$//;
1043             $seealso =~s/-- \n$//;
1044             $see =~s/-- \n$//;
1045       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1046       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1047       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1048       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1049       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1050       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1051       } else {
1052       # construct MARC21 summary
1053           # FIXME - looping over 1XX is questionable
1054           # since MARC21 authority should have only one 1XX
1055           foreach my $field ($record->field('1..')) {
1056               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1057                                               # in MARC21 -- purely local tags really ought to be
1058                                               # 9XX
1059               if ($record->field('100')) {
1060                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1061               } elsif ($record->field('110')) {
1062                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1063               } elsif ($record->field('111')) {
1064                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
1065               } elsif ($record->field('130')) {
1066                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
1067               } elsif ($record->field('148')) {
1068                                       $heading.= $field->as_string('abvxyz68');
1069               } elsif ($record->field('150')) {
1070           #    $heading.= $field->as_string('abvxyz68');
1071           $heading.= $field->as_formatted();
1072               my $tag=$field->tag();
1073               $heading=~s /^$tag//g;
1074               $heading =~s /\_/\$/g;
1075               } elsif ($record->field('151')) {
1076                                       $heading.= $field->as_string('avxyz68');
1077               } elsif ($record->field('155')) {
1078                                       $heading.= $field->as_string('abvxyz68');
1079               } elsif ($record->field('180')) {
1080                                       $heading.= $field->as_string('vxyz68');
1081               } elsif ($record->field('181')) {
1082                                       $heading.= $field->as_string('vxyz68');
1083               } elsif ($record->field('182')) {
1084                                       $heading.= $field->as_string('vxyz68');
1085               } elsif ($record->field('185')) {
1086                                       $heading.= $field->as_string('vxyz68');
1087               } else {
1088                   $heading.= $field->as_string();
1089               }
1090           } #See From
1091           foreach my $field ($record->field('4..')) {
1092               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1093           } #See Also
1094           foreach my $field ($record->field('5..')) {
1095               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1096           }
1097           $summary .= ": " if $summary;
1098           $summary.=$heading.$seeheading.$altheading;
1099       }
1100   }
1101   return $summary;
1102 }
1103
1104 =head2 BuildUnimarcHierarchies
1105
1106   $text= &BuildUnimarcHierarchies( $authid, $force)
1107
1108 return text containing trees for hierarchies
1109 for them to be stored in auth_header
1110
1111 Example of text:
1112 122,1314,2452;1324,2342,3,2452
1113
1114 =cut
1115
1116 sub BuildUnimarcHierarchies{
1117   my $authid = shift @_;
1118 #   warn "authid : $authid";
1119   my $force = shift @_;
1120   my @globalresult;
1121   my $dbh=C4::Context->dbh;
1122   my $hierarchies;
1123   my $data = GetHeaderAuthority($authid);
1124   if ($data->{'authtrees'} and not $force){
1125     return $data->{'authtrees'};
1126   } elsif ($data->{'authtrees'}){
1127     $hierarchies=$data->{'authtrees'};
1128   } else {
1129     my $record = GetAuthority($authid);
1130     my $found;
1131         if ($record){
1132                 foreach my $field ($record->field('550')){
1133                   if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1134                         my $parentrecord = GetAuthority($field->subfield('3'));
1135                         my $localresult=$hierarchies;
1136                         my $trees;
1137                         $trees = BuildUnimarcHierarchies($field->subfield('3'));
1138                         my @trees;
1139                         if ($trees=~/;/){
1140                            @trees = split(/;/,$trees);
1141                         } else {
1142                            push @trees, $trees;
1143                         }
1144                         foreach (@trees){
1145                           $_.= ",$authid";
1146                         }
1147                         @globalresult = (@globalresult,@trees);
1148                         $found=1;
1149                   }
1150                   $hierarchies=join(";",@globalresult);
1151                 }
1152         }
1153     #Unless there is no ancestor, I am alone.
1154     $hierarchies="$authid" unless ($hierarchies);
1155   }
1156   AddAuthorityTrees($authid,$hierarchies);
1157   return $hierarchies;
1158 }
1159
1160 =head2 BuildUnimarcHierarchy
1161
1162   $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1163
1164 return a hashref in order to display hierarchy for record and final Authid $authid
1165
1166 "loopparents"
1167 "loopchildren"
1168 "class"
1169 "loopauthid"
1170 "current_value"
1171 "value"
1172
1173 "ifparents"  
1174 "ifchildren" 
1175 Those two latest ones should disappear soon.
1176
1177 =cut
1178
1179 sub BuildUnimarcHierarchy{
1180   my $record = shift @_;
1181   my $class = shift @_;
1182   my $authid_constructed = shift @_;
1183   return undef unless ($record);
1184   my $authid=$record->subfield('2..','3');
1185   my %cell;
1186   my $parents=""; my $children="";
1187   my (@loopparents,@loopchildren);
1188   foreach my $field ($record->field('550')){
1189     if ($field->subfield('5') && $field->subfield('a')){
1190       if ($field->subfield('5') eq 'h'){
1191         push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1192       }elsif ($field->subfield('5') eq 'g'){
1193         push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1194       }
1195           # brothers could get in there with an else
1196     }
1197   }
1198   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1199   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1200   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1201   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1202   $cell{"class"}=$class;
1203   $cell{"loopauthid"}=$authid;
1204   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1205   $cell{"value"}=$record->subfield('2..',"a");
1206   return \%cell;
1207 }
1208
1209 =head2 GetHeaderAuthority
1210
1211   $ref= &GetHeaderAuthority( $authid)
1212
1213 return a hashref in order auth_header table data
1214
1215 =cut
1216
1217 sub GetHeaderAuthority{
1218   my $authid = shift @_;
1219   my $sql= "SELECT * from auth_header WHERE authid = ?";
1220   my $dbh=C4::Context->dbh;
1221   my $rq= $dbh->prepare($sql);
1222   $rq->execute($authid);
1223   my $data= $rq->fetchrow_hashref;
1224   return $data;
1225 }
1226
1227 =head2 AddAuthorityTrees
1228
1229   $ref= &AddAuthorityTrees( $authid, $trees)
1230
1231 return success or failure
1232
1233 =cut
1234
1235 sub AddAuthorityTrees{
1236   my $authid = shift @_;
1237   my $trees = shift @_;
1238   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1239   my $dbh=C4::Context->dbh;
1240   my $rq= $dbh->prepare($sql);
1241   return $rq->execute($trees,$authid);
1242 }
1243
1244 =head2 merge
1245
1246   $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1247
1248 Could add some feature : Migrating from a typecode to an other for instance.
1249 Then we should add some new parameter : bibliotargettag, authtargettag
1250
1251 =cut
1252
1253 sub merge {
1254     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1255     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1256     my $dbh=C4::Context->dbh;
1257     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1258     my $authtypecodeto = GetAuthTypeCode($mergeto);
1259 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1260     # return if authority does not exist
1261     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1262     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1263     # search the tag to report
1264     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1265     $sth->execute($authtypecodefrom);
1266     my ($auth_tag_to_report_from) = $sth->fetchrow;
1267     $sth->execute($authtypecodeto);
1268     my ($auth_tag_to_report_to) = $sth->fetchrow;
1269     
1270     my @record_to;
1271     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1272     my @record_from;
1273     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1274     
1275     my @reccache;
1276     # search all biblio tags using this authority.
1277     #Getting marcbiblios impacted by the change.
1278     if (C4::Context->preference('NoZebra')) {
1279         #nozebra way    
1280         my $dbh=C4::Context->dbh;
1281         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1282         $rq->execute;
1283         while (my $biblionumbers=$rq->fetchrow){
1284             my @biblionumbers=split /;/,$biblionumbers;
1285             foreach (@biblionumbers) {
1286                 if ($_=~/(\d+),.*/) {
1287                     my $marc=GetMarcBiblio($1);
1288                     push @reccache,$marc;
1289                 }
1290             }
1291         }
1292     } else {
1293         #zebra connection  
1294         my $oConnection=C4::Context->Zconn("biblioserver",0);
1295         $oConnection->option("preferredRecordSyntax"=>"XML");
1296         my $query;
1297         $query= "an=".$mergefrom;
1298         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1299         my $count = 0;
1300         if  ($oResult) {
1301             $count=$oResult->size();
1302         }
1303         my $z=0;
1304         while ( $z<$count ) {
1305             my $rec;
1306             $rec=$oResult->record($z);
1307             my $marcdata = $rec->raw();
1308             push @reccache, $marcdata;
1309             $z++;
1310         }
1311         $oConnection->destroy();    
1312     }
1313     #warn scalar(@reccache)." biblios to update";
1314     # Get All candidate Tags for the change 
1315     # (This will reduce the search scope in marc records).
1316     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1317     $sth->execute($authtypecodefrom);
1318     my @tags_using_authtype;
1319     while (my ($tagfield) = $sth->fetchrow) {
1320         push @tags_using_authtype,$tagfield ;
1321     }
1322     my $tag_to=0;  
1323     if ($authtypecodeto ne $authtypecodefrom){  
1324         # If many tags, take the first
1325         $sth->execute($authtypecodeto);    
1326         $tag_to=$sth->fetchrow;
1327         #warn $tag_to;    
1328     }  
1329     # BulkEdit marc records
1330     # May be used as a template for a bulkedit field  
1331     foreach my $marcrecord(@reccache){
1332         my $update;           
1333         $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1334         foreach my $tagfield (@tags_using_authtype){
1335 #             warn "tagfield : $tagfield ";
1336             foreach my $field ($marcrecord->field($tagfield)){
1337                 my $auth_number=$field->subfield("9");
1338                 my $tag=$field->tag();          
1339                 if ($auth_number==$mergefrom) {
1340                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1341                 my $exclude='9';
1342                 foreach my $subfield (@record_to) {
1343                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1344                     $exclude.= $subfield->[0];
1345                 }
1346                 $exclude='['.$exclude.']';
1347 #               add subfields in $field not included in @record_to
1348                 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1349                 foreach my $subfield (@restore) {
1350                    $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1351                 }
1352                 $marcrecord->delete_field($field);
1353                 $marcrecord->insert_grouped_field($field_to);            
1354                 $update=1;
1355                 }
1356             }#for each tag
1357         }#foreach tagfield
1358         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1359         my $biblionumber;
1360         if ($bibliotag<10){
1361             $biblionumber=$marcrecord->field($bibliotag)->data;
1362         }
1363         else {
1364             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1365         }
1366         unless ($biblionumber){
1367             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1368             next;
1369         }
1370         if ($update==1){
1371             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1372             $counteditedbiblio++;
1373             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1374         }    
1375     }#foreach $marc
1376     return $counteditedbiblio;  
1377   # now, find every other authority linked with this authority
1378   # now, find every other authority linked with this authority
1379 #   my $oConnection=C4::Context->Zconn("authorityserver");
1380 #   my $query;
1381 # # att 9210               Auth-Internal-authtype
1382 # # att 9220               Auth-Internal-LN
1383 # # ccl.properties to add for authorities
1384 #   $query= "= ".$mergefrom;
1385 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1386 #   my $count=$oResult->size() if  ($oResult);
1387 #   my @reccache;
1388 #   my $z=0;
1389 #   while ( $z<$count ) {
1390 #   my $rec;
1391 #           $rec=$oResult->record($z);
1392 #       my $marcdata = $rec->raw();
1393 #   push @reccache, $marcdata;
1394 #   $z++;
1395 #   }
1396 #   $oResult->destroy();
1397 #   foreach my $marc(@reccache){
1398 #     my $update;
1399 #     my $marcrecord;
1400 #     $marcrecord = MARC::File::USMARC::decode($marc);
1401 #     foreach my $tagfield (@tags_using_authtype){
1402 #       $tagfield=substr($tagfield,0,3);
1403 #       my @tags = $marcrecord->field($tagfield);
1404 #       foreach my $tag (@tags){
1405 #         my $tagsubs=$tag->subfield("9");
1406 #     #warn "$tagfield:$tagsubs:$mergefrom";
1407 #         if ($tagsubs== $mergefrom) {
1408 #           $tag->update("9" =>$mergeto);
1409 #           foreach my $subfield (@record_to) {
1410 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1411 #             $tag->update($subfield->[0] =>$subfield->[1]);
1412 #           }#for $subfield
1413 #         }
1414 #         $marcrecord->delete_field($tag);
1415 #         $marcrecord->add_fields($tag);
1416 #         $update=1;
1417 #       }#for each tag
1418 #     }#foreach tagfield
1419 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1420 #     if ($update==1){
1421 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1422 #     }
1423
1424 #   }#foreach $marc
1425 }#sub
1426
1427 =head2 get_auth_type_location
1428
1429   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1430
1431 Get the tag and subfield used to store the heading type
1432 for indexing purposes.  The C<$auth_type> parameter is
1433 optional; if it is not supplied, assume ''.
1434
1435 This routine searches the MARC authority framework
1436 for the tag and subfield whose kohafield is 
1437 C<auth_header.authtypecode>; if no such field is
1438 defined in the framework, default to the hardcoded value
1439 specific to the MARC format.
1440
1441 =cut
1442
1443 sub get_auth_type_location {
1444     my $auth_type_code = @_ ? shift : '';
1445
1446     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1447     if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1448         return ($tag, $subfield);
1449     } else {
1450         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1451             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1452         } else {
1453             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1454         }
1455     }
1456 }
1457
1458 END { }       # module clean-up code here (global destructor)
1459
1460 1;
1461 __END__
1462
1463 =head1 AUTHOR
1464
1465 Koha Development Team <http://koha-community.org/>
1466
1467 Paul POULAIN paul.poulain@free.fr
1468
1469 =cut
1470