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