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