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