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