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