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