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