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