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