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