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