34151fc32111ae034914642bbc08913c11a114d1
[koha-equinox.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;
21 use C4::Context;
22 use MARC::Record;
23 use C4::Biblio;
24 use C4::Search;
25 use C4::AuthoritiesMarc::MARC21;
26 use C4::AuthoritiesMarc::UNIMARC;
27 use C4::Charset;
28 use C4::Log;
29 use Koha::Authority;
30
31 use vars qw($VERSION @ISA @EXPORT);
32
33 BEGIN {
34         # set the version for version checking
35     $VERSION = 3.07.00.049;
36
37         require Exporter;
38         @ISA = qw(Exporter);
39         @EXPORT = qw(
40             &GetTagsLabels
41             &GetAuthType
42             &GetAuthTypeCode
43         &GetAuthMARCFromKohaField 
44
45         &AddAuthority
46         &ModAuthority
47         &DelAuthority
48         &GetAuthority
49         &GetAuthorityXML
50
51         &CountUsage
52         &CountUsageChildren
53         &SearchAuthorities
54     
55         &BuildSummary
56         &BuildAuthHierarchies
57         &BuildAuthHierarchy
58         &GenerateHierarchy
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,
102      $sortby[, $skipmetadata])
103
104 returns ref to array result and count of results returned
105
106 =cut
107
108 sub SearchAuthorities {
109     my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
110     # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
111     my $dbh=C4::Context->dbh;
112     my $query;
113     my $qpquery = '';
114     my $QParser;
115     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
116     my $attr = '';
117         # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
118         # the authtypecode. Then, search on $a of this tag_to_report
119         # also store main entry MARC tag, to extract it at end of search
120     my $mainentrytag;
121     ##first set the authtype search and may be multiple authorities
122     if ($authtypecode) {
123         my $n=0;
124         my @authtypecode;
125         my @auths=split / /,$authtypecode ;
126         foreach my  $auth (@auths){
127             $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
128                 push @authtypecode ,$auth;
129             $n++;
130         }
131         if ($n>1){
132             while ($n>1){$query= "\@or ".$query;$n--;}
133         }
134         if ($QParser) {
135             $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
136         }
137     }
138
139     my $dosearch;
140     my $and=" \@and " ;
141     my $q2;
142     my $attr_cnt = 0;
143     for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
144         if ( @$value[$i] ) {
145             if ( @$tags[$i] ) {
146                 if ( @$tags[$i] eq "mainmainentry" ) {
147                     $attr = " \@attr 1=Heading-Main ";
148                 }
149                 elsif ( @$tags[$i] eq "mainentry" ) {
150                     $attr = " \@attr 1=Heading ";
151                 }
152                 elsif ( @$tags[$i] eq "match" ) {
153                     $attr = " \@attr 1=Match ";
154                 }
155                 elsif ( @$tags[$i] eq "match-heading" ) {
156                     $attr = " \@attr 1=Match-heading ";
157                 }
158                 elsif ( @$tags[$i] eq "see-from" ) {
159                     $attr = " \@attr 1=Match-heading-see-from ";
160                 }
161                 elsif ( @$tags[$i] eq "thesaurus" ) {
162                     $attr = " \@attr 1=Subject-heading-thesaurus ";
163                 }
164                 else {    # Assume any if no index was specified
165                     $attr = " \@attr 1=Any ";
166                 }
167             }         #if @$tags[$i]
168             else {    # Assume any if no index was specified
169                 $attr = " \@attr 1=Any ";
170             }
171
172             my $operator = @$operator[$i];
173             if ( $operator and $operator eq 'is' ) {
174                 $attr .= " \@attr 4=1  \@attr 5=100 "
175                   ;    ##Phrase, No truncation,all of subfield field must match
176             }
177             elsif ( $operator and $operator eq "=" ) {
178                 $attr .= " \@attr 4=107 ";    #Number Exact match
179             }
180             elsif ( $operator and $operator eq "start" ) {
181                 $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 "
182                   ;    #Firstinfield Phrase, Right truncated
183             }
184             elsif ( $operator and $operator eq "exact" ) {
185                 $attr .= " \@attr 4=1  \@attr 5=100 \@attr 6=3 "
186                   ;    ##Phrase, No truncation,all of subfield field must match
187             }
188             else {
189                 $attr .= " \@attr 5=1 \@attr 4=6 "
190                   ;    ## Word list, right truncated, anywhere
191                 if ( $sortby eq 'Relevance' ) {
192                     $attr .= "\@attr 2=102 ";
193                 }
194             }
195             @$value[$i] =~
196               s/"/\\"/g;    # Escape the double-quotes in the search value
197             $attr = $attr . "\"" . @$value[$i] . "\"";
198             $q2 .= $attr;
199             $dosearch = 1;
200             ++$attr_cnt;
201             if ($QParser) {
202                 $qpquery .= " $tags->[$i]:\"$value->[$i]\"";
203             }
204         }    #if value
205     }
206     ##Add how many queries generated
207     if (defined $query && $query=~/\S+/){
208       $query= $and x $attr_cnt . $query . (defined $q2 ? $q2 : '');
209     } else {
210       $query= $q2;
211     }
212     ## Adding order
213     #$query=' @or  @attr 7=2 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
214     my $orderstring;
215     if ($sortby eq 'HeadingAsc') {
216         $orderstring = '@attr 7=1 @attr 1=Heading 0';
217     } elsif ($sortby eq 'HeadingDsc') {
218         $orderstring = '@attr 7=2 @attr 1=Heading 0';
219     } elsif ($sortby eq 'AuthidAsc') {
220         $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0';
221     } elsif ($sortby eq 'AuthidDsc') {
222         $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0';
223     }
224     if ($QParser) {
225         $qpquery .= ' all:all' unless $value->[0];
226
227         if ( $value->[0] =~ m/^qp=(.*)$/ ) {
228             $qpquery = $1;
229         }
230
231         $qpquery .= " #$sortby" unless $sortby eq '';
232
233         $QParser->parse( $qpquery );
234         $query = $QParser->target_syntax('authorityserver');
235     } else {
236         $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''");
237         $query="\@or $orderstring $query" if $orderstring;
238     }
239
240     $offset=0 unless $offset;
241     my $counter = $offset;
242     $length=10 unless $length;
243     my @oAuth;
244     my $i;
245     $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
246     my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
247     my $oAResult;
248     $oAResult= $oAuth[0]->search($Anewq) ;
249     while (($i = ZOOM::event(\@oAuth)) != 0) {
250         my $ev = $oAuth[$i-1]->last_event();
251         last if $ev == ZOOM::Event::ZEND;
252     }
253     my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
254     if ($error) {
255         warn  "oAuth error: $errmsg ($error) $addinfo $diagset\n";
256         goto NOLUCK;
257     }
258
259     my $nbresults;
260     $nbresults=$oAResult->size();
261     my $nremains=$nbresults;
262     my @result = ();
263     my @finalresult = ();
264
265     if ($nbresults>0){
266
267     ##Find authid and linkid fields
268     ##we may be searching multiple authoritytypes.
269     ## FIXME this assumes that all authid and linkid fields are the same for all authority types
270     # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
271     # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
272         while (($counter < $nbresults) && ($counter < ($offset + $length))) {
273         
274         ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
275         my $rec=$oAResult->record($counter);
276         my $separator=C4::Context->preference('AuthoritySeparator');
277         my $authrecord = C4::Search::new_record_from_zebra(
278             'authorityserver',
279             $rec->raw()
280         );
281
282         if ( !defined $authrecord or !defined $authrecord->field('001') ) {
283             $counter++;
284             next;
285         }
286
287         SetUTF8Flag( $authrecord );
288
289         my $authid=$authrecord->field('001')->data();
290         my %newline;
291         $newline{authid} = $authid;
292         if ( !$skipmetadata ) {
293             my $query_auth_tag =
294 "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
295             my $sth = $dbh->prepare($query_auth_tag);
296             $sth->execute($authtypecode);
297             my $auth_tag_to_report = $sth->fetchrow;
298             my $reported_tag;
299             my $mainentry = $authrecord->field($auth_tag_to_report);
300             if ($mainentry) {
301                 foreach ( $mainentry->subfields() ) {
302                     $reported_tag .= '$' . $_->[0] . $_->[1];
303                 }
304             }
305             my $thisauthtypecode = GetAuthTypeCode($authid);
306             my $thisauthtype = GetAuthType($thisauthtypecode);
307             unless (defined $thisauthtype) {
308                 $thisauthtypecode = $authtypecode;
309                 $thisauthtype = GetAuthType($authtypecode);
310             }
311             my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode );
312
313             $newline{authtype}     = defined($thisauthtype) ?
314                                         $thisauthtype->{'authtypetext'} : '';
315             $newline{summary}      = $summary;
316             $newline{even}         = $counter % 2;
317             $newline{reported_tag} = $reported_tag;
318         }
319         $counter++;
320         push @finalresult, \%newline;
321         }## while counter
322         ###
323         if (! $skipmetadata) {
324             for (my $z=0; $z<@finalresult; $z++){
325                 my  $count=CountUsage($finalresult[$z]{authid});
326                 $finalresult[$z]{used}=$count;
327             }# all $z's
328         }
329
330     }## if nbresult
331     NOLUCK:
332     $oAResult->destroy();
333     # $oAuth[0]->destroy();
334
335     return (\@finalresult, $nbresults);
336 }
337
338 =head2 CountUsage 
339
340   $count= &CountUsage($authid)
341
342 counts Usage of Authid in bibliorecords. 
343
344 =cut
345
346 sub CountUsage {
347     my ($authid) = @_;
348         ### ZOOM search here
349         my $query;
350         $query= "an:".$authid;
351                 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
352         if ($err) {
353             warn "Error: $err from search $query";
354             $result = 0;
355         }
356
357         return $result;
358 }
359
360 =head2 CountUsageChildren 
361
362   $count= &CountUsageChildren($authid)
363
364 counts Usage of narrower terms of Authid in bibliorecords.
365
366 =cut
367
368 sub CountUsageChildren {
369   my ($authid) = @_;
370 }
371
372 =head2 GetAuthTypeCode
373
374   $authtypecode= &GetAuthTypeCode($authid)
375
376 returns authtypecode of an authid
377
378 =cut
379
380 sub GetAuthTypeCode {
381 #AUTHfind_authtypecode
382   my ($authid) = @_;
383   my $dbh=C4::Context->dbh;
384   my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
385   $sth->execute($authid);
386   my $authtypecode = $sth->fetchrow;
387   return $authtypecode;
388 }
389  
390 =head2 GuessAuthTypeCode
391
392   my $authtypecode = GuessAuthTypeCode($record);
393
394 Get the record and tries to guess the adequate authtypecode from its content.
395
396 =cut
397
398 sub GuessAuthTypeCode {
399     my ($record, $heading_fields) = @_;
400     return unless defined $record;
401     $heading_fields //= {
402     "MARC21"=>{
403         '100'=>{authtypecode=>'PERSO_NAME'},
404         '110'=>{authtypecode=>'CORPO_NAME'},
405         '111'=>{authtypecode=>'MEETI_NAME'},
406         '130'=>{authtypecode=>'UNIF_TITLE'},
407         '148'=>{authtypecode=>'CHRON_TERM'},
408         '150'=>{authtypecode=>'TOPIC_TERM'},
409         '151'=>{authtypecode=>'GEOGR_NAME'},
410         '155'=>{authtypecode=>'GENRE/FORM'},
411         '180'=>{authtypecode=>'GEN_SUBDIV'},
412         '181'=>{authtypecode=>'GEO_SUBDIV'},
413         '182'=>{authtypecode=>'CHRON_SUBD'},
414         '185'=>{authtypecode=>'FORM_SUBD'},
415     },
416 #200 Personal name      700, 701, 702 4-- with embedded 700, 701, 702 600
417 #                    604 with embedded 700, 701, 702
418 #210 Corporate or meeting name  710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712
419 #215 Territorial or geographic name     710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712
420 #216 Trademark  716 [Reserved for future use]
421 #220 Family name        720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722
422 #230 Title      500 4-- with embedded 500 605
423 #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
424 #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
425 #250 Topical subject    606
426 #260 Place access       620
427 #280 Form, genre or physical characteristics    608
428 #
429 #
430 # Could also be represented with :
431 #leader position 9
432 #a = personal name entry
433 #b = corporate name entry
434 #c = territorial or geographical name
435 #d = trademark
436 #e = family name
437 #f = uniform title
438 #g = collective uniform title
439 #h = name/title
440 #i = name/collective uniform title
441 #j = topical subject
442 #k = place access
443 #l = form, genre or physical characteristics
444     "UNIMARC"=>{
445         '200'=>{authtypecode=>'NP'},
446         '210'=>{authtypecode=>'CO'},
447         '215'=>{authtypecode=>'SNG'},
448         '216'=>{authtypecode=>'TM'},
449         '220'=>{authtypecode=>'FAM'},
450         '230'=>{authtypecode=>'TU'},
451         '235'=>{authtypecode=>'CO_UNI_TI'},
452         '240'=>{authtypecode=>'SAUTTIT'},
453         '245'=>{authtypecode=>'NAME_COL'},
454         '250'=>{authtypecode=>'SNC'},
455         '260'=>{authtypecode=>'PA'},
456         '280'=>{authtypecode=>'GENRE/FORM'},
457     }
458 };
459     foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) {
460        return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field));
461     }
462     return;
463 }
464
465 =head2 GuessAuthId
466
467   my $authtid = GuessAuthId($record);
468
469 Get the record and tries to guess the adequate authtypecode from its content.
470
471 =cut
472
473 sub GuessAuthId {
474     my ($record) = @_;
475     return unless ($record && $record->field('001'));
476 #    my $authtypecode=GuessAuthTypeCode($record);
477 #    my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode);
478 #    if ($tag > 010) {return $record->subfield($tag,$subfield)}
479 #    else {return $record->field($tag)->data}
480     return $record->field('001')->data;
481 }
482
483 =head2 GetTagsLabels
484
485   $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
486
487 returns a ref to hashref of authorities tag and subfield structure.
488
489 tagslabel usage : 
490
491   $tagslabel->{$tag}->{$subfield}->{'attribute'}
492
493 where attribute takes values in :
494
495   lib
496   tab
497   mandatory
498   repeatable
499   authorised_value
500   authtypecode
501   value_builder
502   kohafield
503   seealso
504   hidden
505   isurl
506   link
507
508 =cut
509
510 sub GetTagsLabels {
511   my ($forlibrarian,$authtypecode)= @_;
512   my $dbh=C4::Context->dbh;
513   $authtypecode="" unless $authtypecode;
514   my $sth;
515   my $libfield = ($forlibrarian == 1)? 'liblibrarian' : 'libopac';
516
517
518   # check that authority exists
519   $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
520   $sth->execute($authtypecode);
521   my ($total) = $sth->fetchrow;
522   $authtypecode="" unless ($total >0);
523   $sth= $dbh->prepare(
524 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable 
525  FROM auth_tag_structure 
526  WHERE authtypecode=? 
527  ORDER BY tagfield"
528     );
529
530   $sth->execute($authtypecode);
531   my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
532
533   while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
534         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
535         $res->{$tag}->{tab}        = " ";            # XXX
536         $res->{$tag}->{mandatory}  = $mandatory;
537         $res->{$tag}->{repeatable} = $repeatable;
538   }
539   $sth=      $dbh->prepare(
540 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue
541 FROM auth_subfield_structure 
542 WHERE authtypecode=? 
543 ORDER BY tagfield,tagsubfield"
544     );
545     $sth->execute($authtypecode);
546
547     my $subfield;
548     my $authorised_value;
549     my $value_builder;
550     my $kohafield;
551     my $seealso;
552     my $hidden;
553     my $isurl;
554     my $link;
555     my $defaultvalue;
556
557     while (
558         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
559         $mandatory,     $repeatable, $authorised_value, $authtypecode,
560         $value_builder, $kohafield,  $seealso,          $hidden,
561         $isurl,         $defaultvalue, $link )
562         = $sth->fetchrow
563       )
564     {
565         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
566         $res->{$tag}->{$subfield}->{tab}              = $tab;
567         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
568         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
569         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
570         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
571         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
572         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
573         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
574         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
575         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
576         $res->{$tag}->{$subfield}->{link}            = $link;
577         $res->{$tag}->{$subfield}->{defaultvalue}     = $defaultvalue;
578     }
579     return $res;
580 }
581
582 =head2 AddAuthority
583
584   $authid= &AddAuthority($record, $authid,$authtypecode)
585
586 Either Create Or Modify existing authority.
587 returns authid of the newly created authority
588
589 =cut
590
591 sub AddAuthority {
592 # pass the MARC::Record to this function, and it will create the records in the authority table
593   my ($record,$authid,$authtypecode) = @_;
594   my $dbh=C4::Context->dbh;
595         my $leader='     nz  a22     o  4500';#Leader for incomplete MARC21 record
596
597 # if authid empty => true add, find a new authid number
598     my $format;
599     if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
600         $format= 'UNIMARCAUTH';
601     }
602     else {
603         $format= 'MARC21';
604     }
605
606     #update date/time to 005 for marc and unimarc
607     my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
608     my $f5=$record->field('005');
609     if (!$f5) {
610       $record->insert_fields_ordered( MARC::Field->new('005',$time.".0") );
611     }
612     else {
613       $f5->update($time.".0");
614     }
615
616     SetUTF8Flag($record);
617         if ($format eq "MARC21") {
618                 if (!$record->leader) {
619                         $record->leader($leader);
620                 }
621                 if (!$record->field('003')) {
622                         $record->insert_fields_ordered(
623                                 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
624                         );
625                 }
626                 my $date=POSIX::strftime("%y%m%d",localtime);
627                 if (!$record->field('008')) {
628             # Get a valid default value for field 008
629             my $default_008 = C4::Context->preference('MARCAuthorityControlField008');
630             if(!$default_008 or length($default_008)<34) {
631                 $default_008 = '|| aca||aabn           | a|a     d';
632             }
633             else {
634                 $default_008 = substr($default_008,0,34);
635             }
636
637             $record->insert_fields_ordered( MARC::Field->new('008',$date.$default_008) );
638                 }
639                 if (!$record->field('040')) {
640                  $record->insert_fields_ordered(
641         MARC::Field->new('040','','',
642                                 'a' => C4::Context->preference('MARCOrgCode'),
643                                 'c' => C4::Context->preference('MARCOrgCode')
644                                 ) 
645                         );
646     }
647         }
648
649   if ($format eq "UNIMARCAUTH") {
650         $record->leader("     nx  j22             ") unless ($record->leader());
651         my $date=POSIX::strftime("%Y%m%d",localtime);
652         my $defaultfield100 = C4::Context->preference('UNIMARCAuthorityField100');
653     if (my $string=$record->subfield('100',"a")){
654         $string=~s/fre50/frey50/;
655         $record->field('100')->update('a'=>$string);
656     }
657     elsif ($record->field('100')){
658           $record->field('100')->update('a'=>$date.$defaultfield100);
659     } else {      
660         $record->append_fields(
661         MARC::Field->new('100',' ',' '
662             ,'a'=>$date.$defaultfield100)
663         );
664     }      
665   }
666   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
667   if (!$authid and $format eq "MARC21") {
668     # only need to do this fix when modifying an existing authority
669     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
670   } 
671   if (my $field=$record->field($auth_type_tag)){
672     $field->update($auth_type_subfield=>$authtypecode);
673   }
674   else {
675     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
676   }
677
678   my $auth_exists=0;
679   my $oldRecord;
680   if (!$authid) {
681     my $sth=$dbh->prepare("select max(authid) from auth_header");
682     $sth->execute;
683     ($authid)=$sth->fetchrow;
684     $authid=$authid+1;
685   ##Insert the recordID in MARC record 
686     unless ($record->field('001') && $record->field('001')->data() eq $authid){
687         $record->delete_field($record->field('001'));
688         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
689     }
690   } else {
691     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
692 #     warn "auth_exists = $auth_exists";
693   }
694   if ($auth_exists>0){
695       $oldRecord=GetAuthority($authid);
696       $record->add_fields('001',$authid) unless ($record->field('001'));
697 #       warn "\n\n\n enregistrement".$record->as_formatted;
698       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
699       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
700       $sth->finish;
701   }
702   else {
703     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
704     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
705     $sth->finish;
706     logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
707   }
708   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
709   return ($authid);
710 }
711
712
713 =head2 DelAuthority
714
715   $authid= &DelAuthority($authid)
716
717 Deletes $authid
718
719 =cut
720
721 sub DelAuthority {
722     my ($authid) = @_;
723     my $dbh=C4::Context->dbh;
724
725     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
726     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
727     my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
728     $sth->execute($authid);
729 }
730
731 =head2 ModAuthority
732
733   $authid= &ModAuthority($authid,$record,$authtypecode)
734
735 Modifies authority record, optionally updates attached biblios.
736
737 =cut
738
739 sub ModAuthority {
740   my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
741
742   my $dbh=C4::Context->dbh;
743   #Now rewrite the $record to table with an add
744   my $oldrecord=GetAuthority($authid);
745   $authid=AddAuthority($record,$authid,$authtypecode);
746
747   # If a library thinks that updating all biblios is a long process and wishes
748   # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
749   # In that case set system preference "dontmerge" to 1. Otherwise biblios will
750   # be updated.
751   unless(C4::Context->preference('dontmerge') eq '1'){
752       &merge($authid,$oldrecord,$authid,$record);
753   } else {
754       # save a record in need_merge_authorities table
755       my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
756         "VALUES (?,?)";
757       $dbh->do($sqlinsert,undef,($authid,0));
758   }
759   logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
760   return $authid;
761 }
762
763 =head2 GetAuthorityXML 
764
765   $marcxml= &GetAuthorityXML( $authid)
766
767 returns xml form of record $authid
768
769 =cut
770
771 sub GetAuthorityXML {
772   # Returns MARC::XML of the authority passed in parameter.
773   my ( $authid ) = @_;
774   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
775       my $dbh=C4::Context->dbh;
776       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
777       $sth->execute($authid);
778       my ($marcxml)=$sth->fetchrow;
779       return $marcxml;
780   }
781   else { 
782       # for MARC21, call GetAuthority instead of
783       # getting the XML directly since we may
784       # need to fix up the location of the authority
785       # code -- note that this is reasonably safe
786       # because GetAuthorityXML is used only by the 
787       # indexing processes like zebraqueue_start.pl
788       my $record = GetAuthority($authid);
789       return $record->as_xml_record('MARC21');
790   }
791 }
792
793 =head2 GetAuthority 
794
795   $record= &GetAuthority( $authid)
796
797 Returns MARC::Record of the authority passed in parameter.
798
799 =cut
800
801 sub GetAuthority {
802     my ($authid)=@_;
803     my $authority = Koha::Authority->get_from_authid($authid);
804     return unless $authority;
805     return ($authority->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 =head2 FindDuplicateAuthority
835
836   $record= &FindDuplicateAuthority( $record, $authtypecode)
837
838 return $authid,Summary if duplicate is found.
839
840 Comments : an improvement would be to return All the records that match.
841
842 =cut
843
844 sub FindDuplicateAuthority {
845
846     my ($record,$authtypecode)=@_;
847 #    warn "IN for ".$record->as_formatted;
848     my $dbh = C4::Context->dbh;
849 #    warn "".$record->as_formatted;
850     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
851     $sth->execute($authtypecode);
852     my ($auth_tag_to_report) = $sth->fetchrow;
853     $sth->finish;
854 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
855     # build a request for SearchAuthorities
856     my $QParser;
857     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
858     my $op;
859     if ($QParser) {
860         $op = '&&';
861     } else {
862         $op = 'and';
863     }
864     my $query='at:'.$authtypecode.' ';
865     my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
866     if ($record->field($auth_tag_to_report)) {
867         foreach ($record->field($auth_tag_to_report)->subfields()) {
868             $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
869         }
870     }
871     my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
872     # there is at least 1 result => return the 1st one
873     if (!defined $error && @{$results} ) {
874         my $marcrecord = C4::Search::new_record_from_zebra(
875             'authorityserver',
876             $results->[0]
877         );
878         return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
879     }
880     # no result, returns nothing
881     return;
882 }
883
884 =head2 BuildSummary
885
886   $summary= &BuildSummary( $record, $authid, $authtypecode)
887
888 Returns a hashref with a summary of the specified record.
889
890 Comment : authtypecode can be infered from both record and authid.
891 Moreover, authid can also be inferred from $record.
892 Would it be interesting to delete those things.
893
894 =cut
895
896 sub BuildSummary {
897     ## give this a Marc record to return summary
898     my ($record,$authid,$authtypecode)=@_;
899     my $dbh=C4::Context->dbh;
900     my %summary;
901     my $summary_template;
902     # handle $authtypecode is NULL or eq ""
903     if ($authtypecode) {
904         my $authref = GetAuthType($authtypecode);
905         $summary{authtypecode} = $authref->{authtypecode};
906         $summary{type} = $authref->{authtypetext};
907         $summary_template = $authref->{summary};
908         # for MARC21, the authority type summary displays a label meant for
909         # display
910         if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
911             $summary{summary} = $authref->{summary};
912         }
913     }
914     my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
915     my %marc21controlrefs = ( 'a' => 'earlier',
916         'b' => 'later',
917         'd' => 'acronym',
918         'f' => 'musical',
919         'g' => 'broader',
920         'h' => 'narrower',
921         'n' => 'notapplicable',
922         'i' => 'subfi',
923         't' => 'parent'
924     );
925     my %unimarc_relation_from_code = (
926         g => 'broader',
927         h => 'narrower',
928         a => 'seealso',
929     );
930     my %thesaurus;
931     $thesaurus{'1'}="Peuples";
932     $thesaurus{'2'}="Anthroponymes";
933     $thesaurus{'3'}="Oeuvres";
934     $thesaurus{'4'}="Chronologie";
935     $thesaurus{'5'}="Lieux";
936     $thesaurus{'6'}="Sujets";
937     #thesaurus a remplir
938     my $reported_tag;
939 # if the library has a summary defined, use it. Otherwise, build a standard one
940 # FIXME - it appears that the summary field in the authority frameworks
941 #         can work as a display template.  However, this doesn't
942 #         suit the MARC21 version, so for now the "templating"
943 #         feature will be enabled only for UNIMARC for backwards
944 #         compatibility.
945     if ($summary_template and C4::Context->preference('marcflavour') eq 'UNIMARC') {
946         my @fields = $record->fields();
947 #             $reported_tag = '$9'.$result[$counter];
948         my @repets;
949         foreach my $field (@fields) {
950             my $tag = $field->tag();
951             my $tagvalue = $field->as_string();
952             my $localsummary= $summary_template;
953             $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
954             if ($tag<10) {
955                 if ($tag eq '001') {
956                     $reported_tag.='$3'.$field->data();
957                 }
958             } else {
959                 my @subf = $field->subfields;
960                 for my $i (0..$#subf) {
961                     my $subfieldcode = $subf[$i][0];
962                     my $subfieldvalue = $subf[$i][1];
963                     my $tagsubf = $tag.$subfieldcode;
964                     $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
965                 }
966             }
967             if ($localsummary ne $summary_template) {
968                 $localsummary =~ s/\[(.*?)\]//g;
969                 $localsummary =~ s/\n/<br>/g;
970                 push @repets, $localsummary;
971             }
972         }
973         $summary{repets} = \@repets;
974     }
975     my @authorized;
976     my @notes;
977     my @seefrom;
978     my @seealso;
979     my @otherscript;
980     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
981 # construct UNIMARC summary, that is quite different from MARC21 one
982 # accepted form
983         foreach my $field ($record->field('2..')) {
984             push @authorized, {
985                 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
986                 hemain  => ( $field->subfield('a') // undef ),
987                 field   => $field->tag(),
988             };
989         }
990 # rejected form(s)
991         foreach my $field ($record->field('3..')) {
992             push @notes, { note => $field->subfield('a'), field => $field->tag() };
993         }
994         foreach my $field ($record->field('4..')) {
995             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
996             push @seefrom, {
997                 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
998                 hemain  => ( $field->subfield('a') // undef ),
999                 type    => 'seefrom',
1000                 field   => $field->tag(),
1001             };
1002         }
1003
1004         # see :
1005         @seealso = map {
1006             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1007             my $heading = $_->as_string('abcdefgjxyz');
1008             {
1009                 field   => $_->tag,
1010                 type    => $type,
1011                 heading => $heading,
1012                 hemain  => ( $_->subfield('a') // undef ),
1013                 search  => $heading,
1014                 authid  => ( $_->subfield('9') // undef ),
1015             }
1016         } $record->field('5..');
1017
1018         # Other forms
1019         @otherscript = map { {
1020             lang      => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
1021             term      => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
1022             direction => 'ltr',
1023             field     => $_->tag,
1024         } } $record->field('7..');
1025
1026     } else {
1027 # construct MARC21 summary
1028 # FIXME - looping over 1XX is questionable
1029 # since MARC21 authority should have only one 1XX
1030         my $subfields_to_report;
1031         foreach my $field ($record->field('1..')) {
1032             my $tag = $field->tag();
1033             next if "152" eq $tag;
1034 # FIXME - 152 is not a good tag to use
1035 # in MARC21 -- purely local tags really ought to be
1036 # 9XX
1037             if ($tag eq '100') {
1038                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1039             } elsif ($tag eq '110') {
1040                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1041             } elsif ($tag eq '111') {
1042                 $subfields_to_report = 'acdefghklnpqstvxyz';
1043             } elsif ($tag eq '130') {
1044                 $subfields_to_report = 'adfghklmnoprstvxyz';
1045             } elsif ($tag eq '148') {
1046                 $subfields_to_report = 'abvxyz';
1047             } elsif ($tag eq '150') {
1048                 $subfields_to_report = 'abvxyz';
1049             } elsif ($tag eq '151') {
1050                 $subfields_to_report = 'avxyz';
1051             } elsif ($tag eq '155') {
1052                 $subfields_to_report = 'abvxyz';
1053             } elsif ($tag eq '180') {
1054                 $subfields_to_report = 'vxyz';
1055             } elsif ($tag eq '181') {
1056                 $subfields_to_report = 'vxyz';
1057             } elsif ($tag eq '182') {
1058                 $subfields_to_report = 'vxyz';
1059             } elsif ($tag eq '185') {
1060                 $subfields_to_report = 'vxyz';
1061             }
1062             if ($subfields_to_report) {
1063                 push @authorized, {
1064                     heading => $field->as_string($subfields_to_report),
1065                     hemain  => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
1066                     field   => $tag,
1067                 };
1068             } else {
1069                 push @authorized, {
1070                     heading => $field->as_string(),
1071                     hemain  => ( $field->subfield( 'a' ) // undef ),
1072                     field   => $tag,
1073                 };
1074             }
1075         }
1076         foreach my $field ($record->field('4..')) { #See From
1077             my $type = 'seefrom';
1078             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1079             if ($type eq 'notapplicable') {
1080                 $type = substr $field->subfield('w'), 2, 1;
1081                 $type = 'earlier' if $type && $type ne 'n';
1082             }
1083             if ($type eq 'subfi') {
1084                 push @seefrom, {
1085                     heading => $field->as_string($marc21subfields),
1086                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1087                     type    => ($field->subfield('i') || ''),
1088                     field   => $field->tag(),
1089                 };
1090             } else {
1091                 push @seefrom, {
1092                     heading => $field->as_string($marc21subfields),
1093                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1094                     type    => $type,
1095                     field   => $field->tag(),
1096                 };
1097             }
1098         }
1099         foreach my $field ($record->field('5..')) { #See Also
1100             my $type = 'seealso';
1101             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1102             if ($type eq 'notapplicable') {
1103                 $type = substr $field->subfield('w'), 2, 1;
1104                 $type = 'earlier' if $type && $type ne 'n';
1105             }
1106             if ($type eq 'subfi') {
1107                 push @seealso, {
1108                     heading => $field->as_string($marc21subfields),
1109                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1110                     type    => $field->subfield('i'),
1111                     field   => $field->tag(),
1112                     search  => $field->as_string($marc21subfields) || '',
1113                     authid  => $field->subfield('9') || ''
1114                 };
1115             } else {
1116                 push @seealso, {
1117                     heading => $field->as_string($marc21subfields),
1118                     hemain  => $field->subfield( substr($marc21subfields, 0, 1) ),
1119                     type    => $type,
1120                     field   => $field->tag(),
1121                     search  => $field->as_string($marc21subfields) || '',
1122                     authid  => $field->subfield('9') || ''
1123                 };
1124             }
1125         }
1126         foreach my $field ($record->field('6..')) {
1127             push @notes, { note => $field->as_string(), field => $field->tag() };
1128         }
1129         foreach my $field ($record->field('880')) {
1130             my $linkage = $field->subfield('6');
1131             my $category = substr $linkage, 0, 1;
1132             if ($category eq '1') {
1133                 $category = 'preferred';
1134             } elsif ($category eq '4') {
1135                 $category = 'seefrom';
1136             } elsif ($category eq '5') {
1137                 $category = 'seealso';
1138             }
1139             my $type;
1140             if ($field->subfield('w')) {
1141                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1142             } else {
1143                 $type = $category;
1144             }
1145             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1146             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1147         }
1148     }
1149     $summary{mainentry} = $authorized[0]->{heading};
1150     $summary{mainmainentry} = $authorized[0]->{hemain};
1151     $summary{authorized} = \@authorized;
1152     $summary{notes} = \@notes;
1153     $summary{seefrom} = \@seefrom;
1154     $summary{seealso} = \@seealso;
1155     $summary{otherscript} = \@otherscript;
1156     return \%summary;
1157 }
1158
1159 =head2 GetAuthorizedHeading
1160
1161   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1162
1163 Takes a MARC::Record object describing an authority record or an authid, and
1164 returns a string representation of the first authorized heading. This routine
1165 should be considered a temporary shim to ease the future migration of authority
1166 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1167
1168 =cut
1169
1170 sub GetAuthorizedHeading {
1171     my $args = shift;
1172     my $record;
1173     unless ($record = $args->{record}) {
1174         return unless $args->{authid};
1175         $record = GetAuthority($args->{authid});
1176     }
1177     return unless (ref $record eq 'MARC::Record');
1178     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1179 # construct UNIMARC summary, that is quite different from MARC21 one
1180 # accepted form
1181         foreach my $field ($record->field('2..')) {
1182             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1183         }
1184     } else {
1185         foreach my $field ($record->field('1..')) {
1186             my $tag = $field->tag();
1187             next if "152" eq $tag;
1188 # FIXME - 152 is not a good tag to use
1189 # in MARC21 -- purely local tags really ought to be
1190 # 9XX
1191             if ($tag eq '100') {
1192                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1193             } elsif ($tag eq '110') {
1194                 return $field->as_string('abcdefghklmnoprstvxyz68');
1195             } elsif ($tag eq '111') {
1196                 return $field->as_string('acdefghklnpqstvxyz68');
1197             } elsif ($tag eq '130') {
1198                 return $field->as_string('adfghklmnoprstvxyz68');
1199             } elsif ($tag eq '148') {
1200                 return $field->as_string('abvxyz68');
1201             } elsif ($tag eq '150') {
1202                 return $field->as_string('abvxyz68');
1203             } elsif ($tag eq '151') {
1204                 return $field->as_string('avxyz68');
1205             } elsif ($tag eq '155') {
1206                 return $field->as_string('abvxyz68');
1207             } elsif ($tag eq '180') {
1208                 return $field->as_string('vxyz68');
1209             } elsif ($tag eq '181') {
1210                 return $field->as_string('vxyz68');
1211             } elsif ($tag eq '182') {
1212                 return $field->as_string('vxyz68');
1213             } elsif ($tag eq '185') {
1214                 return $field->as_string('vxyz68');
1215             } else {
1216                 return $field->as_string();
1217             }
1218         }
1219     }
1220     return;
1221 }
1222
1223 =head2 BuildAuthHierarchies
1224
1225   $text= &BuildAuthHierarchies( $authid, $force)
1226
1227 return text containing trees for hierarchies
1228 for them to be stored in auth_header
1229
1230 Example of text:
1231 122,1314,2452;1324,2342,3,2452
1232
1233 =cut
1234
1235 sub BuildAuthHierarchies{
1236     my $authid = shift @_;
1237 #   warn "authid : $authid";
1238     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1239     my @globalresult;
1240     my $dbh=C4::Context->dbh;
1241     my $hierarchies;
1242     my $data = GetHeaderAuthority($authid);
1243     if ($data->{'authtrees'} and not $force){
1244         return $data->{'authtrees'};
1245 #  } elsif ($data->{'authtrees'}){
1246 #    $hierarchies=$data->{'authtrees'};
1247     } else {
1248         my $record = GetAuthority($authid);
1249         my $found;
1250         return unless $record;
1251         foreach my $field ($record->field('5..')){
1252             my $broader = 0;
1253             $broader = 1 if (
1254                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1255                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1256             if ($broader) {
1257                 my $subfauthid=_get_authid_subfield($field) || '';
1258                 next if ($subfauthid eq $authid);
1259                 my $parentrecord = GetAuthority($subfauthid);
1260                 next unless $parentrecord;
1261                 my $localresult=$hierarchies;
1262                 my $trees;
1263                 $trees = BuildAuthHierarchies($subfauthid);
1264                 my @trees;
1265                 if ($trees=~/;/){
1266                     @trees = split(/;/,$trees);
1267                 } else {
1268                     push @trees, $trees;
1269                 }
1270                 foreach (@trees){
1271                     $_.= ",$authid";
1272                 }
1273                 @globalresult = (@globalresult,@trees);
1274                 $found=1;
1275             }
1276             $hierarchies=join(";",@globalresult);
1277         }
1278 #Unless there is no ancestor, I am alone.
1279         $hierarchies="$authid" unless ($hierarchies);
1280     }
1281     AddAuthorityTrees($authid,$hierarchies);
1282     return $hierarchies;
1283 }
1284
1285 =head2 BuildAuthHierarchy
1286
1287   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1288
1289 return a hashref in order to display hierarchy for record and final Authid $authid
1290
1291 "loopparents"
1292 "loopchildren"
1293 "class"
1294 "loopauthid"
1295 "current_value"
1296 "value"
1297
1298 =cut
1299
1300 sub BuildAuthHierarchy{
1301     my $record = shift @_;
1302     my $class = shift @_;
1303     my $authid_constructed = shift @_;
1304     return unless ($record && $record->field('001'));
1305     my $authid=$record->field('001')->data();
1306     my %cell;
1307     my $parents=""; my $children="";
1308     my (@loopparents,@loopchildren);
1309     my $marcflavour = C4::Context->preference('marcflavour');
1310     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1311     foreach my $field ($record->field('5..')){
1312         my $subfauthid=_get_authid_subfield($field);
1313         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1314             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1315             if ($relationship eq 'h'){
1316                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1317             }
1318             elsif ($relationship eq 'g'){
1319                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1320             }
1321 # brothers could get in there with an else
1322         }
1323     }
1324     $cell{"parents"}=\@loopparents;
1325     $cell{"children"}=\@loopchildren;
1326     $cell{"class"}=$class;
1327     $cell{"authid"}=$authid;
1328     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1329     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1330     return \%cell;
1331 }
1332
1333 =head2 BuildAuthHierarchyBranch
1334
1335   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1336
1337 Return a data structure representing an authority hierarchy
1338 given a list of authorities representing a single branch in
1339 an authority hierarchy tree. $authid is the current node in
1340 the tree (which may or may not be somewhere in the middle).
1341 $cnt represents the level of the upper-most item, and is only
1342 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1343 don't ever pass in anything but zero to it).
1344
1345 =cut
1346
1347 sub BuildAuthHierarchyBranch {
1348     my ($tree, $authid, $cnt) = @_;
1349     $cnt |= 0;
1350     my $elementdata = GetAuthority(shift @$tree);
1351     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1352     if (scalar @$tree > 0) {
1353         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1354         my $nextAuthid = $nextBranch->{authid};
1355         my $found;
1356         # If we already have the next branch listed as a child, let's
1357         # replace the old listing with the new one. If not, we will add
1358         # the branch at the end.
1359         foreach my $cell (@{$branch->{children}}) {
1360             if ($cell->{authid} eq $nextAuthid) {
1361                 $cell = $nextBranch;
1362                 $found = 1;
1363                 last;
1364             }
1365         }
1366         push @{$branch->{children}}, $nextBranch unless $found;
1367     }
1368     return $branch;
1369 }
1370
1371 =head2 GenerateHierarchy
1372
1373   $hierarchy = &GenerateHierarchy($authid);
1374
1375 Return an arrayref holding one or more "trees" representing
1376 authority hierarchies.
1377
1378 =cut
1379
1380 sub GenerateHierarchy {
1381     my ($authid) = @_;
1382     my $trees    = BuildAuthHierarchies($authid);
1383     my @trees    = split /;/,$trees ;
1384     push @trees,$trees unless (@trees);
1385     my @loophierarchies;
1386     foreach my $tree (@trees){
1387         my @tree=split /,/,$tree;
1388         push @tree, $tree unless (@tree);
1389         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1390         push @loophierarchies, [ $branch ];
1391     }
1392     return \@loophierarchies;
1393 }
1394
1395 sub _get_authid_subfield{
1396     my ($field)=@_;
1397     return $field->subfield('9')||$field->subfield('3');
1398 }
1399 =head2 GetHeaderAuthority
1400
1401   $ref= &GetHeaderAuthority( $authid)
1402
1403 return a hashref in order auth_header table data
1404
1405 =cut
1406
1407 sub GetHeaderAuthority{
1408   my $authid = shift @_;
1409   my $sql= "SELECT * from auth_header WHERE authid = ?";
1410   my $dbh=C4::Context->dbh;
1411   my $rq= $dbh->prepare($sql);
1412   $rq->execute($authid);
1413   my $data= $rq->fetchrow_hashref;
1414   return $data;
1415 }
1416
1417 =head2 AddAuthorityTrees
1418
1419   $ref= &AddAuthorityTrees( $authid, $trees)
1420
1421 return success or failure
1422
1423 =cut
1424
1425 sub AddAuthorityTrees{
1426   my $authid = shift @_;
1427   my $trees = shift @_;
1428   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1429   my $dbh=C4::Context->dbh;
1430   my $rq= $dbh->prepare($sql);
1431   return $rq->execute($trees,$authid);
1432 }
1433
1434 =head2 merge
1435
1436   $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1437
1438 Could add some feature : Migrating from a typecode to an other for instance.
1439 Then we should add some new parameter : bibliotargettag, authtargettag
1440
1441 =cut
1442
1443 sub merge {
1444     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1445     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1446     my $dbh=C4::Context->dbh;
1447     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1448     my $authtypecodeto = GetAuthTypeCode($mergeto);
1449 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1450     # return if authority does not exist
1451     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1452     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1453     # search the tag to report
1454     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1455     $sth->execute($authtypecodefrom);
1456     my ($auth_tag_to_report_from) = $sth->fetchrow;
1457     $sth->execute($authtypecodeto);
1458     my ($auth_tag_to_report_to) = $sth->fetchrow;
1459     
1460     my @record_to;
1461     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1462     my @record_from;
1463     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1464     
1465     my @reccache;
1466     # search all biblio tags using this authority.
1467     #Getting marcbiblios impacted by the change.
1468     #zebra connection
1469     my $oConnection=C4::Context->Zconn("biblioserver",0);
1470     # We used to use XML syntax here, but that no longer works.
1471     # Thankfully, we don't need it.
1472     my $query;
1473     $query= "an=".$mergefrom;
1474     my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1475     my $count = 0;
1476     if  ($oResult) {
1477         $count=$oResult->size();
1478     }
1479     my $z=0;
1480     while ( $z<$count ) {
1481         my $marcrecordzebra = C4::Search::new_record_from_zebra(
1482             'biblioserver',
1483             $oResult->record($z)->raw()
1484         );
1485         my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1486         my $i = ($biblionumbertagfield < 10)
1487             ? $marcrecordzebra->field( $biblionumbertagfield )->data
1488             : $marcrecordzebra->subfield( $biblionumbertagfield, $biblionumbertagsubfield );
1489         my $marcrecorddb = GetMarcBiblio($i);
1490         push @reccache, $marcrecorddb;
1491         $z++;
1492     }
1493     $oResult->destroy();
1494     #warn scalar(@reccache)." biblios to update";
1495     # Get All candidate Tags for the change 
1496     # (This will reduce the search scope in marc records).
1497     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1498     $sth->execute($authtypecodefrom);
1499     my @tags_using_authtype;
1500     while (my ($tagfield) = $sth->fetchrow) {
1501         push @tags_using_authtype,$tagfield ;
1502     }
1503     my $tag_to=0;  
1504     if ($authtypecodeto ne $authtypecodefrom){  
1505         # If many tags, take the first
1506         $sth->execute($authtypecodeto);    
1507         $tag_to=$sth->fetchrow;
1508         #warn $tag_to;    
1509     }  
1510     # BulkEdit marc records
1511     # May be used as a template for a bulkedit field  
1512     foreach my $marcrecord(@reccache){
1513         my $update;           
1514         foreach my $tagfield (@tags_using_authtype){
1515 #             warn "tagfield : $tagfield ";
1516             foreach my $field ($marcrecord->field($tagfield)){
1517                 # biblio is linked to authority with $9 subfield containing authid
1518                 my $auth_number=$field->subfield("9");
1519                 my $tag=$field->tag();          
1520                 if ($auth_number==$mergefrom) {
1521                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1522                 my $exclude='9';
1523                 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1524                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1525                     $exclude.= $subfield->[0];
1526                 }
1527                 $exclude='['.$exclude.']';
1528 #               add subfields in $field not included in @record_to
1529                 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1530                 foreach my $subfield (@restore) {
1531                    $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1532                 }
1533                 $marcrecord->delete_field($field);
1534                 $marcrecord->insert_grouped_field($field_to);            
1535                 $update=1;
1536                 }
1537             }#for each tag
1538         }#foreach tagfield
1539         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1540         my $biblionumber;
1541         if ($bibliotag<10){
1542             $biblionumber=$marcrecord->field($bibliotag)->data;
1543         }
1544         else {
1545             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1546         }
1547         unless ($biblionumber){
1548             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1549             next;
1550         }
1551         if ($update==1){
1552             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1553             $counteditedbiblio++;
1554             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1555         }    
1556     }#foreach $marc
1557     return $counteditedbiblio;  
1558   # now, find every other authority linked with this authority
1559   # now, find every other authority linked with this authority
1560 #   my $oConnection=C4::Context->Zconn("authorityserver");
1561 #   my $query;
1562 # # att 9210               Auth-Internal-authtype
1563 # # att 9220               Auth-Internal-LN
1564 # # ccl.properties to add for authorities
1565 #   $query= "= ".$mergefrom;
1566 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1567 #   my $count=$oResult->size() if  ($oResult);
1568 #   my @reccache;
1569 #   my $z=0;
1570 #   while ( $z<$count ) {
1571 #   my $rec;
1572 #           $rec=$oResult->record($z);
1573 #       my $marcdata = $rec->raw();
1574 #   push @reccache, $marcdata;
1575 #   $z++;
1576 #   }
1577 #   $oResult->destroy();
1578 #   foreach my $marc(@reccache){
1579 #     my $update;
1580 #     my $marcrecord;
1581 #     $marcrecord = MARC::File::USMARC::decode($marc);
1582 #     foreach my $tagfield (@tags_using_authtype){
1583 #       $tagfield=substr($tagfield,0,3);
1584 #       my @tags = $marcrecord->field($tagfield);
1585 #       foreach my $tag (@tags){
1586 #         my $tagsubs=$tag->subfield("9");
1587 #     #warn "$tagfield:$tagsubs:$mergefrom";
1588 #         if ($tagsubs== $mergefrom) {
1589 #           $tag->update("9" =>$mergeto);
1590 #           foreach my $subfield (@record_to) {
1591 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1592 #             $tag->update($subfield->[0] =>$subfield->[1]);
1593 #           }#for $subfield
1594 #         }
1595 #         $marcrecord->delete_field($tag);
1596 #         $marcrecord->add_fields($tag);
1597 #         $update=1;
1598 #       }#for each tag
1599 #     }#foreach tagfield
1600 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1601 #     if ($update==1){
1602 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1603 #     }
1604
1605 #   }#foreach $marc
1606 }#sub
1607
1608 =head2 get_auth_type_location
1609
1610   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1611
1612 Get the tag and subfield used to store the heading type
1613 for indexing purposes.  The C<$auth_type> parameter is
1614 optional; if it is not supplied, assume ''.
1615
1616 This routine searches the MARC authority framework
1617 for the tag and subfield whose kohafield is 
1618 C<auth_header.authtypecode>; if no such field is
1619 defined in the framework, default to the hardcoded value
1620 specific to the MARC format.
1621
1622 =cut
1623
1624 sub get_auth_type_location {
1625     my $auth_type_code = @_ ? shift : '';
1626
1627     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1628     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1629         return ($tag, $subfield);
1630     } else {
1631         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1632             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1633         } else {
1634             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1635         }
1636     }
1637 }
1638
1639 END { }       # module clean-up code here (global destructor)
1640
1641 1;
1642 __END__
1643
1644 =head1 AUTHOR
1645
1646 Koha Development Team <http://koha-community.org/>
1647
1648 Paul POULAIN paul.poulain@free.fr
1649
1650 =cut
1651