Bug 24217: use Modern::Perl for modules when strict is missing
[koha.git] / C4 / AuthoritiesMarc.pm
1 package C4::AuthoritiesMarc;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22 use C4::Context;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26 use C4::AuthoritiesMarc::MARC21;
27 use C4::AuthoritiesMarc::UNIMARC;
28 use C4::Charset;
29 use C4::Log;
30 use Koha::MetadataRecord::Authority;
31 use Koha::Authorities;
32 use Koha::Authority::MergeRequest;
33 use Koha::Authority::Types;
34 use Koha::Authority;
35 use Koha::Libraries;
36 use Koha::SearchEngine;
37 use Koha::SearchEngine::Search;
38
39 use vars qw(@ISA @EXPORT);
40
41 BEGIN {
42
43         require Exporter;
44         @ISA = qw(Exporter);
45         @EXPORT = qw(
46             &GetTagsLabels
47         &GetAuthMARCFromKohaField 
48
49         &AddAuthority
50         &ModAuthority
51         &DelAuthority
52         &GetAuthority
53         &GetAuthorityXML
54
55         &SearchAuthorities
56     
57         &BuildSummary
58         &BuildAuthHierarchies
59         &BuildAuthHierarchy
60         &GenerateHierarchy
61     
62         &merge
63         &FindDuplicateAuthority
64
65         &GuessAuthTypeCode
66         &GuessAuthId
67         );
68 }
69
70
71 =head1 NAME
72
73 C4::AuthoritiesMarc
74
75 =head2 GetAuthMARCFromKohaField 
76
77   ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
78
79 returns tag and subfield linked to kohafield
80
81 Comment :
82 Suppose Kohafield is only linked to ONE subfield
83
84 =cut
85
86 sub GetAuthMARCFromKohaField {
87 #AUTHfind_marc_from_kohafield
88   my ( $kohafield,$authtypecode ) = @_;
89   my $dbh=C4::Context->dbh;
90   return 0, 0 unless $kohafield;
91   $authtypecode="" unless $authtypecode;
92   my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
93   $sth->execute($kohafield,$authtypecode);
94   my ($tagfield,$tagsubfield) = $sth->fetchrow;
95     
96   return  ($tagfield,$tagsubfield);
97 }
98
99 =head2 SearchAuthorities 
100
101   (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, 
102      $excluding, $operator, $value, $offset,$length,$authtypecode,
103      $sortby[, $skipmetadata])
104
105 returns ref to array result and count of results returned
106
107 =cut
108
109 sub SearchAuthorities {
110     my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_;
111     # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby);
112     my $dbh=C4::Context->dbh;
113     $sortby="" unless $sortby;
114     my $query;
115     my $qpquery = '';
116     my $QParser;
117     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
118     my $attr = '';
119         # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
120         # the authtypecode. Then, search on $a of this tag_to_report
121         # also store main entry MARC tag, to extract it at end of search
122     my $mainentrytag;
123     ##first set the authtype search and may be multiple authorities
124     if ($authtypecode) {
125         my $n=0;
126         my @authtypecode;
127         my @auths=split / /,$authtypecode ;
128         foreach my  $auth (@auths){
129             $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
130                 push @authtypecode ,$auth;
131             $n++;
132         }
133         if ($n>1){
134             while ($n>1){$query= "\@or ".$query;$n--;}
135         }
136         if ($QParser) {
137             $qpquery .= '(authtype:' . join('|| authtype:', @auths) . ')';
138         }
139     }
140
141     my $dosearch;
142     my $and=" \@and " ;
143     my $q2;
144     my $attr_cnt = 0;
145     for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) {
146         if ( @$value[$i] ) {
147             if ( @$tags[$i] ) {
148                 if ( @$tags[$i] eq "mainmainentry" ) {
149                     $attr = " \@attr 1=Heading-Main ";
150                 }
151                 elsif ( @$tags[$i] eq "mainentry" ) {
152                     $attr = " \@attr 1=Heading ";
153                 }
154                 elsif ( @$tags[$i] eq "match" ) {
155                     $attr = " \@attr 1=Match ";
156                 }
157                 elsif ( @$tags[$i] eq "match-heading" ) {
158                     $attr = " \@attr 1=Match-heading ";
159                 }
160                 elsif ( @$tags[$i] eq "see-from" ) {
161                     $attr = " \@attr 1=Match-heading-see-from ";
162                 }
163                 elsif ( @$tags[$i] eq "thesaurus" ) {
164                     $attr = " \@attr 1=Subject-heading-thesaurus ";
165                 }
166                 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     merge({ mergefrom => $authid }) if !$skip_merge;
674     $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid );
675     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
676     ModZebra( $authid, "recordDelete", "authorityserver", undef);
677 }
678
679 =head2 ModAuthority
680
681   $authid= &ModAuthority($authid,$record,$authtypecode)
682
683 Modifies authority record, optionally updates attached biblios.
684
685 =cut
686
687 sub ModAuthority {
688     my ( $authid, $record, $authtypecode ) = @_;
689     my $oldrecord = GetAuthority($authid);
690     #Now rewrite the $record to table with an add
691     $authid = AddAuthority($record, $authid, $authtypecode);
692     merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record });
693     logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
694     return $authid;
695 }
696
697 =head2 GetAuthorityXML 
698
699   $marcxml= &GetAuthorityXML( $authid)
700
701 returns xml form of record $authid
702
703 =cut
704
705 sub GetAuthorityXML {
706   # Returns MARC::XML of the authority passed in parameter.
707   my ( $authid ) = @_;
708   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
709       my $dbh=C4::Context->dbh;
710       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
711       $sth->execute($authid);
712       my ($marcxml)=$sth->fetchrow;
713       return $marcxml;
714   }
715   else { 
716       # for MARC21, call GetAuthority instead of
717       # getting the XML directly since we may
718       # need to fix up the location of the authority
719       # code -- note that this is reasonably safe
720       # because GetAuthorityXML is used only by the 
721       # indexing processes like zebraqueue_start.pl
722       my $record = GetAuthority($authid);
723       return $record->as_xml_record('MARC21');
724   }
725 }
726
727 =head2 GetAuthority 
728
729   $record= &GetAuthority( $authid)
730
731 Returns MARC::Record of the authority passed in parameter.
732
733 =cut
734
735 sub GetAuthority {
736     my ($authid)=@_;
737     my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
738     return unless $authority;
739     return ($authority->record);
740 }
741
742 =head2 FindDuplicateAuthority
743
744   $record= &FindDuplicateAuthority( $record, $authtypecode)
745
746 return $authid,Summary if duplicate is found.
747
748 Comments : an improvement would be to return All the records that match.
749
750 =cut
751
752 sub FindDuplicateAuthority {
753
754     my ($record,$authtypecode)=@_;
755 #    warn "IN for ".$record->as_formatted;
756     my $dbh = C4::Context->dbh;
757 #    warn "".$record->as_formatted;
758     my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report;
759 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
760     # build a request for SearchAuthorities
761     my $QParser;
762     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
763     my $op;
764     if ($QParser) {
765         $op = '&&';
766     } else {
767         $op = 'AND';
768     }
769     my $query='at:'.$authtypecode.' ';
770     my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]);
771     if ($record->field($auth_tag_to_report)) {
772         foreach ($record->field($auth_tag_to_report)->subfields()) {
773             $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
774         }
775     }
776     my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX});
777     my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver' ] );
778     # there is at least 1 result => return the 1st one
779     if (!defined $error && @{$results} ) {
780         my $marcrecord = C4::Search::new_record_from_zebra(
781             'authorityserver',
782             $results->[0]
783         );
784         return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
785     }
786     # no result, returns nothing
787     return;
788 }
789
790 =head2 BuildSummary
791
792   $summary= &BuildSummary( $record, $authid, $authtypecode)
793
794 Returns a hashref with a summary of the specified record.
795
796 Comment : authtypecode can be inferred from both record and authid.
797 Moreover, authid can also be inferred from $record.
798 Would it be interesting to delete those things.
799
800 =cut
801
802 sub BuildSummary {
803     ## give this a Marc record to return summary
804     my ($record,$authid,$authtypecode)=@_;
805     my $dbh=C4::Context->dbh;
806     my %summary;
807     my $summary_template;
808     # handle $authtypecode is NULL or eq ""
809     if ($authtypecode) {
810         my $authref = Koha::Authority::Types->find($authtypecode);
811         if ( $authref ) {
812             $summary{authtypecode} = $authref->authtypecode;
813             $summary{type} = $authref->authtypetext;
814             $summary_template = $authref->summary;
815             # for MARC21, the authority type summary displays a label meant for
816             # display
817             if (C4::Context->preference('marcflavour') ne 'UNIMARC') {
818                 $summary{label} = $authref->summary;
819             } else {
820                 $summary{summary} = $authref->summary;
821             }
822         }
823     }
824     my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
825     my %marc21controlrefs = ( 'a' => 'earlier',
826         'b' => 'later',
827         'd' => 'acronym',
828         'f' => 'musical',
829         'g' => 'broader',
830         'h' => 'narrower',
831         'n' => 'notapplicable',
832         'i' => 'subfi',
833         't' => 'parent'
834     );
835     my %unimarc_relation_from_code = (
836         g => 'broader',
837         h => 'narrower',
838         a => 'seealso',
839     );
840     my %thesaurus;
841     $thesaurus{'1'}="Peuples";
842     $thesaurus{'2'}="Anthroponymes";
843     $thesaurus{'3'}="Oeuvres";
844     $thesaurus{'4'}="Chronologie";
845     $thesaurus{'5'}="Lieux";
846     $thesaurus{'6'}="Sujets";
847     #thesaurus a remplir
848     my $reported_tag;
849 # if the library has a summary defined, use it. Otherwise, build a standard one
850 # FIXME - it appears that the summary field in the authority frameworks
851 #         can work as a display template.  However, this doesn't
852 #         suit the MARC21 version, so for now the "templating"
853 #         feature will be enabled only for UNIMARC for backwards
854 #         compatibility.
855     if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
856         my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g);
857         my (@textbefore, @tag, @subtag, @textafter);
858         for(my $i = 0; $i < scalar @matches; $i++){
859             push @textbefore, $matches[$i] if($i%4 == 0);
860             push @tag,        $matches[$i] if($i%4 == 1);
861             push @subtag,     $matches[$i] if($i%4 == 2);
862             push @textafter,  $matches[$i] if($i%4 == 3);
863         }
864         for(my $i = scalar @tag; $i >= 0; $i--){
865             my $textbefore = $textbefore[$i] || '';
866             my $tag = $tag[$i] || '';
867             my $subtag = $subtag[$i] || '';
868             my $textafter = $textafter[$i] || '';
869             my $value = '';
870             my $field = $record->field($tag);
871             if ( $field ) {
872                 if($subtag eq '*') {
873                     if($tag < 10) {
874                         $value = $textbefore . $field->data() . $textafter;
875                     }
876                 } else {
877                     my @subfields = $field->subfield($subtag);
878                     if(@subfields > 0) {
879                         $value = $textbefore . join (" - ", @subfields) . $textafter;
880                     }
881                 }
882             }
883             $summary{summary} =~ s/\[\Q$textbefore$tag$subtag$textafter\E\]/$value/;
884         }
885         $summary{summary} =~ s/\\n/<br \/>/g;
886     }
887     my @authorized;
888     my @notes;
889     my @seefrom;
890     my @seealso;
891     my @otherscript;
892     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
893 # construct UNIMARC summary, that is quite different from MARC21 one
894 # accepted form
895         foreach my $field ($record->field('2..')) {
896             push @authorized, {
897                 heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'),
898                 hemain  => ( $field->subfield('a') // undef ),
899                 field   => $field->tag(),
900             };
901         }
902 # rejected form(s)
903         foreach my $field ($record->field('3..')) {
904             push @notes, { note => $field->subfield('a'), field => $field->tag() };
905         }
906         foreach my $field ($record->field('4..')) {
907             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
908             push @seefrom, {
909                 heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'),
910                 hemain  => ( $field->subfield('a') // undef ),
911                 type    => 'seefrom',
912                 field   => $field->tag(),
913             };
914         }
915
916         # see :
917         @seealso = map {
918             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
919             my $heading = $_->as_string('abcdefgjxyz');
920             {
921                 field   => $_->tag,
922                 type    => $type,
923                 heading => $heading,
924                 hemain  => ( $_->subfield('a') // undef ),
925                 search  => $heading,
926                 authid  => ( $_->subfield('9') // undef ),
927             }
928         } $record->field('5..');
929
930         # Other forms
931         @otherscript = map { {
932             lang      => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '',
933             term      => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''),
934             direction => 'ltr',
935             field     => $_->tag,
936         } } $record->field('7..');
937
938     } else {
939 # construct MARC21 summary
940 # FIXME - looping over 1XX is questionable
941 # since MARC21 authority should have only one 1XX
942         my $subfields_to_report;
943         foreach my $field ($record->field('1..')) {
944             my $tag = $field->tag();
945             next if "152" eq $tag;
946 # FIXME - 152 is not a good tag to use
947 # in MARC21 -- purely local tags really ought to be
948 # 9XX
949             if ($tag eq '100') {
950                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
951             } elsif ($tag eq '110') {
952                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
953             } elsif ($tag eq '111') {
954                 $subfields_to_report = 'acdefghklnpqstvxyz';
955             } elsif ($tag eq '130') {
956                 $subfields_to_report = 'adfghklmnoprstvxyz';
957             } elsif ($tag eq '148') {
958                 $subfields_to_report = 'abvxyz';
959             } elsif ($tag eq '150') {
960                 $subfields_to_report = 'abvxyz';
961             } elsif ($tag eq '151') {
962                 $subfields_to_report = 'avxyz';
963             } elsif ($tag eq '155') {
964                 $subfields_to_report = 'abvxyz';
965             } elsif ($tag eq '180') {
966                 $subfields_to_report = 'vxyz';
967             } elsif ($tag eq '181') {
968                 $subfields_to_report = 'vxyz';
969             } elsif ($tag eq '182') {
970                 $subfields_to_report = 'vxyz';
971             } elsif ($tag eq '185') {
972                 $subfields_to_report = 'vxyz';
973             }
974             if ($subfields_to_report) {
975                 push @authorized, {
976                     heading => $field->as_string($subfields_to_report),
977                     hemain  => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ),
978                     field   => $tag,
979                 };
980             } else {
981                 push @authorized, {
982                     heading => $field->as_string(),
983                     hemain  => ( $field->subfield( 'a' ) // undef ),
984                     field   => $tag,
985                 };
986             }
987         }
988         foreach my $field ($record->field('4..')) { #See From
989             my $type = 'seefrom';
990             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
991             if ($type eq 'notapplicable') {
992                 $type = substr $field->subfield('w'), 2, 1;
993                 $type = 'earlier' if $type && $type ne 'n';
994             }
995             if ($type eq 'subfi') {
996                 push @seefrom, {
997                     heading => $field->as_string($marc21subfields),
998                     hemain  => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
999                     type    => ($field->subfield('i') || ''),
1000                     field   => $field->tag(),
1001                 };
1002             } else {
1003                 push @seefrom, {
1004                     heading => $field->as_string($marc21subfields),
1005                     hemain  => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1006                     type    => $type,
1007                     field   => $field->tag(),
1008                 };
1009             }
1010         }
1011         foreach my $field ($record->field('5..')) { #See Also
1012             my $type = 'seealso';
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 @seealso, {
1020                     heading => $field->as_string($marc21subfields),
1021                     hemain  => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1022                     type    => scalar $field->subfield('i'),
1023                     field   => $field->tag(),
1024                     search  => $field->as_string($marc21subfields) || '',
1025                     authid  => $field->subfield('9') || ''
1026                 };
1027             } else {
1028                 push @seealso, {
1029                     heading => $field->as_string($marc21subfields),
1030                     hemain  => scalar $field->subfield( substr($marc21subfields, 0, 1) ),
1031                     type    => $type,
1032                     field   => $field->tag(),
1033                     search  => $field->as_string($marc21subfields) || '',
1034                     authid  => $field->subfield('9') || ''
1035                 };
1036             }
1037         }
1038         foreach my $field ($record->field('6..')) {
1039             push @notes, { note => $field->as_string(), field => $field->tag() };
1040         }
1041         foreach my $field ($record->field('880')) {
1042             my $linkage = $field->subfield('6');
1043             my $category = substr $linkage, 0, 1;
1044             if ($category eq '1') {
1045                 $category = 'preferred';
1046             } elsif ($category eq '4') {
1047                 $category = 'seefrom';
1048             } elsif ($category eq '5') {
1049                 $category = 'seealso';
1050             }
1051             my $type;
1052             if ($field->subfield('w')) {
1053                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1054             } else {
1055                 $type = $category;
1056             }
1057             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1058             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1059         }
1060     }
1061     $summary{mainentry} = $authorized[0]->{heading};
1062     $summary{mainmainentry} = $authorized[0]->{hemain};
1063     $summary{authorized} = \@authorized;
1064     $summary{notes} = \@notes;
1065     $summary{seefrom} = \@seefrom;
1066     $summary{seealso} = \@seealso;
1067     $summary{otherscript} = \@otherscript;
1068     return \%summary;
1069 }
1070
1071 =head2 GetAuthorizedHeading
1072
1073   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1074
1075 Takes a MARC::Record object describing an authority record or an authid, and
1076 returns a string representation of the first authorized heading. This routine
1077 should be considered a temporary shim to ease the future migration of authority
1078 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1079
1080 =cut
1081
1082 sub GetAuthorizedHeading {
1083     my $args = shift;
1084     my $record;
1085     unless ($record = $args->{record}) {
1086         return unless $args->{authid};
1087         $record = GetAuthority($args->{authid});
1088     }
1089     return unless (ref $record eq 'MARC::Record');
1090     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1091 # construct UNIMARC summary, that is quite different from MARC21 one
1092 # accepted form
1093         foreach my $field ($record->field('2..')) {
1094             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1095         }
1096     } else {
1097         foreach my $field ($record->field('1..')) {
1098             my $tag = $field->tag();
1099             next if "152" eq $tag;
1100 # FIXME - 152 is not a good tag to use
1101 # in MARC21 -- purely local tags really ought to be
1102 # 9XX
1103             if ($tag eq '100') {
1104                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1105             } elsif ($tag eq '110') {
1106                 return $field->as_string('abcdefghklmnoprstvxyz68');
1107             } elsif ($tag eq '111') {
1108                 return $field->as_string('acdefghklnpqstvxyz68');
1109             } elsif ($tag eq '130') {
1110                 return $field->as_string('adfghklmnoprstvxyz68');
1111             } elsif ($tag eq '148') {
1112                 return $field->as_string('abvxyz68');
1113             } elsif ($tag eq '150') {
1114                 return $field->as_string('abvxyz68');
1115             } elsif ($tag eq '151') {
1116                 return $field->as_string('avxyz68');
1117             } elsif ($tag eq '155') {
1118                 return $field->as_string('abvxyz68');
1119             } elsif ($tag eq '180') {
1120                 return $field->as_string('vxyz68');
1121             } elsif ($tag eq '181') {
1122                 return $field->as_string('vxyz68');
1123             } elsif ($tag eq '182') {
1124                 return $field->as_string('vxyz68');
1125             } elsif ($tag eq '185') {
1126                 return $field->as_string('vxyz68');
1127             } else {
1128                 return $field->as_string();
1129             }
1130         }
1131     }
1132     return;
1133 }
1134
1135 =head2 BuildAuthHierarchies
1136
1137   $text= &BuildAuthHierarchies( $authid, $force)
1138
1139 return text containing trees for hierarchies
1140 for them to be stored in auth_header
1141
1142 Example of text:
1143 122,1314,2452;1324,2342,3,2452
1144
1145 =cut
1146
1147 sub BuildAuthHierarchies{
1148     my $authid = shift @_;
1149 #   warn "authid : $authid";
1150     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1151     my @globalresult;
1152     my $dbh=C4::Context->dbh;
1153     my $hierarchies;
1154     my $data = GetHeaderAuthority($authid);
1155     if ($data->{'authtrees'} and not $force){
1156         return $data->{'authtrees'};
1157 #  } elsif ($data->{'authtrees'}){
1158 #    $hierarchies=$data->{'authtrees'};
1159     } else {
1160         my $record = GetAuthority($authid);
1161         my $found;
1162         return unless $record;
1163         foreach my $field ($record->field('5..')){
1164             my $broader = 0;
1165             $broader = 1 if (
1166                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1167                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1168             if ($broader) {
1169                 my $subfauthid=_get_authid_subfield($field) || '';
1170                 next if ($subfauthid eq $authid);
1171                 my $parentrecord = GetAuthority($subfauthid);
1172                 next unless $parentrecord;
1173                 my $localresult=$hierarchies;
1174                 my $trees;
1175                 $trees = BuildAuthHierarchies($subfauthid);
1176                 my @trees;
1177                 if ($trees=~/;/){
1178                     @trees = split(/;/,$trees);
1179                 } else {
1180                     push @trees, $trees;
1181                 }
1182                 foreach (@trees){
1183                     $_.= ",$authid";
1184                 }
1185                 @globalresult = (@globalresult,@trees);
1186                 $found=1;
1187             }
1188             $hierarchies=join(";",@globalresult);
1189         }
1190 #Unless there is no ancestor, I am alone.
1191         $hierarchies="$authid" unless ($hierarchies);
1192     }
1193     AddAuthorityTrees($authid,$hierarchies);
1194     return $hierarchies;
1195 }
1196
1197 =head2 BuildAuthHierarchy
1198
1199   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1200
1201 return a hashref in order to display hierarchy for record and final Authid $authid
1202
1203 "loopparents"
1204 "loopchildren"
1205 "class"
1206 "loopauthid"
1207 "current_value"
1208 "value"
1209
1210 =cut
1211
1212 sub BuildAuthHierarchy{
1213     my $record = shift @_;
1214     my $class = shift @_;
1215     my $authid_constructed = shift @_;
1216     return unless ($record && $record->field('001'));
1217     my $authid=$record->field('001')->data();
1218     my %cell;
1219     my $parents=""; my $children="";
1220     my (@loopparents,@loopchildren);
1221     my $marcflavour = C4::Context->preference('marcflavour');
1222     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1223     foreach my $field ($record->field('5..')){
1224         my $subfauthid=_get_authid_subfield($field);
1225         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1226             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1227             if ($relationship eq 'h'){
1228                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1229             }
1230             elsif ($relationship eq 'g'){
1231                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1232             }
1233 # brothers could get in there with an else
1234         }
1235     }
1236     $cell{"parents"}=\@loopparents;
1237     $cell{"children"}=\@loopchildren;
1238     $cell{"class"}=$class;
1239     $cell{"authid"}=$authid;
1240     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1241     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1242     return \%cell;
1243 }
1244
1245 =head2 BuildAuthHierarchyBranch
1246
1247   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1248
1249 Return a data structure representing an authority hierarchy
1250 given a list of authorities representing a single branch in
1251 an authority hierarchy tree. $authid is the current node in
1252 the tree (which may or may not be somewhere in the middle).
1253 $cnt represents the level of the upper-most item, and is only
1254 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1255 don't ever pass in anything but zero to it).
1256
1257 =cut
1258
1259 sub BuildAuthHierarchyBranch {
1260     my ($tree, $authid, $cnt) = @_;
1261     $cnt |= 0;
1262     my $elementdata = GetAuthority(shift @$tree);
1263     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1264     if (scalar @$tree > 0) {
1265         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1266         my $nextAuthid = $nextBranch->{authid};
1267         my $found;
1268         # If we already have the next branch listed as a child, let's
1269         # replace the old listing with the new one. If not, we will add
1270         # the branch at the end.
1271         foreach my $cell (@{$branch->{children}}) {
1272             if ($cell->{authid} eq $nextAuthid) {
1273                 $cell = $nextBranch;
1274                 $found = 1;
1275                 last;
1276             }
1277         }
1278         push @{$branch->{children}}, $nextBranch unless $found;
1279     }
1280     return $branch;
1281 }
1282
1283 =head2 GenerateHierarchy
1284
1285   $hierarchy = &GenerateHierarchy($authid);
1286
1287 Return an arrayref holding one or more "trees" representing
1288 authority hierarchies.
1289
1290 =cut
1291
1292 sub GenerateHierarchy {
1293     my ($authid) = @_;
1294     my $trees    = BuildAuthHierarchies($authid);
1295     my @trees    = split /;/,$trees ;
1296     push @trees,$trees unless (@trees);
1297     my @loophierarchies;
1298     foreach my $tree (@trees){
1299         my @tree=split /,/,$tree;
1300         push @tree, $tree unless (@tree);
1301         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1302         push @loophierarchies, [ $branch ];
1303     }
1304     return \@loophierarchies;
1305 }
1306
1307 sub _get_authid_subfield{
1308     my ($field)=@_;
1309     return $field->subfield('9')||$field->subfield('3');
1310 }
1311
1312 =head2 GetHeaderAuthority
1313
1314   $ref= &GetHeaderAuthority( $authid)
1315
1316 return a hashref in order auth_header table data
1317
1318 =cut
1319
1320 sub GetHeaderAuthority{
1321   my $authid = shift @_;
1322   my $sql= "SELECT * from auth_header WHERE authid = ?";
1323   my $dbh=C4::Context->dbh;
1324   my $rq= $dbh->prepare($sql);
1325   $rq->execute($authid);
1326   my $data= $rq->fetchrow_hashref;
1327   return $data;
1328 }
1329
1330 =head2 AddAuthorityTrees
1331
1332   $ref= &AddAuthorityTrees( $authid, $trees)
1333
1334 return success or failure
1335
1336 =cut
1337
1338 sub AddAuthorityTrees{
1339   my $authid = shift @_;
1340   my $trees = shift @_;
1341   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1342   my $dbh=C4::Context->dbh;
1343   my $rq= $dbh->prepare($sql);
1344   return $rq->execute($trees,$authid);
1345 }
1346
1347 =head2 merge
1348
1349     $count = merge({
1350         mergefrom => $mergefrom,
1351         [ MARCfrom => $MARCfrom, ]
1352         [ mergeto => $mergeto, ]
1353         [ MARCto => $MARCto, ]
1354         [ biblionumbers => [ $a, $b, $c ], ]
1355         [ override_limit => 1, ]
1356     });
1357
1358 Merge biblios linked to authority $mergefrom (mandatory parameter).
1359 If $mergeto equals mergefrom, the linked biblio field is updated.
1360 If $mergeto is different, the biblio field will be linked to $mergeto.
1361 If $mergeto is missing, the biblio field is deleted.
1362
1363 MARCfrom is used to determine if a cleared subfield in the authority record
1364 should be removed from a biblio. MARCto is used to populate the biblio
1365 record with the updated values; if you do not pass it, the biblio field
1366 will be deleted (same as missing mergeto).
1367
1368 Normally all biblio records linked to $mergefrom, will be considered. But
1369 you can pass specific numbers via the biblionumbers parameter.
1370
1371 The parameter override_limit is used by the cron job to force larger
1372 postponed merges.
1373
1374 Note: Although $mergefrom and $mergeto will normally be of the same
1375 authority type, merge also supports moving to another authority type.
1376
1377 =cut
1378
1379 sub merge {
1380     my ( $params ) = @_;
1381     my $mergefrom = $params->{mergefrom} || return;
1382     my $MARCfrom = $params->{MARCfrom};
1383     my $mergeto = $params->{mergeto};
1384     my $MARCto = $params->{MARCto};
1385     my $override_limit = $params->{override_limit};
1386
1387     # If we do not have biblionumbers, we get all linked biblios if the
1388     # number of linked records does not exceed the limit UNLESS we override.
1389     my @biblionumbers;
1390     if( $params->{biblionumbers} ) {
1391         @biblionumbers = @{ $params->{biblionumbers} };
1392     } elsif( $override_limit ) {
1393         @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1394     } else { # now first check number of linked records
1395         my $max = C4::Context->preference('AuthorityMergeLimit') // 0;
1396         my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom });
1397         if( $hits > 0 && $hits <= $max ) {
1398             @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom });
1399         } elsif( $hits > $max ) { #postpone this merge to the cron job
1400             Koha::Authority::MergeRequest->new({
1401                 authid => $mergefrom,
1402                 oldrecord => $MARCfrom,
1403                 authid_new => $mergeto,
1404             })->store;
1405         }
1406     }
1407     return 0 if !@biblionumbers;
1408
1409     # Search authtypes and reporting tags
1410     my $authfrom = Koha::Authorities->find($mergefrom);
1411     my $authto = Koha::Authorities->find($mergeto);
1412     my $authtypefrom = $authfrom ? Koha::Authority::Types->find($authfrom->authtypecode) : undef;
1413     my $authtypeto   = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef;
1414     my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : '';
1415     my $auth_tag_to_report_to   = $authtypeto ? $authtypeto->auth_tag_to_report : '';
1416
1417     my @record_to;
1418     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to);
1419     # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to
1420     # is empty, make sure that $9 and $a remain (instead of clearing the
1421     # reference) in order to allow for data recovery.
1422     # Note: We need $a too, since a single $9 does not pass ModBiblio.
1423     if( $MARCto && $authtypeto && !@record_to  ) {
1424         push @record_to, [ 'a', ' ' ]; # do not remove the space
1425     }
1426
1427     my @record_from;
1428     if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) {
1429     # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC)
1430     # 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
1431         @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields;
1432     } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) {
1433         @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields;
1434     }
1435
1436     # Get all candidate tags for the change
1437     # (This will reduce the search scope in marc records).
1438     # For a deleted authority record, we scan all auth controlled fields
1439     my $dbh = C4::Context->dbh;
1440     my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?";
1441     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<>''" );
1442     my $tags_new;
1443     if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) {
1444         $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ));
1445     }  
1446
1447     my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict';
1448     my $skip_subfields = $overwrite
1449         # This hash contains all subfields from the authority report fields
1450         # Including $MARCfrom as well as $MARCto
1451         # We only need it in loose merge mode; replaces the former $exclude
1452         ? {}
1453         : { map { ( $_->[0], 1 ); } ( @record_from, @record_to ) };
1454
1455     my $counteditedbiblio = 0;
1456     foreach my $biblionumber ( @biblionumbers ) {
1457         my $marcrecord = GetMarcBiblio({ biblionumber => $biblionumber });
1458         next if !$marcrecord;
1459         my $update = 0;
1460         foreach my $tagfield (@$tags_using_authtype) {
1461             my $countfrom = 0;    # used in strict mode to remove duplicates
1462             foreach my $field ( $marcrecord->field($tagfield) ) {
1463                 my $auth_number = $field->subfield("9");    # link to authority
1464                 my $tag         = $field->tag();
1465                 next if !defined($auth_number) || $auth_number ne $mergefrom;
1466                 $countfrom++;
1467                 if ( !$mergeto || !@record_to ||
1468                   ( $overwrite && $countfrom > 1 ) ) {
1469                     # !mergeto or !record_to indicates a delete
1470                     # Other condition: remove this duplicate in strict mode
1471                     $marcrecord->delete_field($field);
1472                     $update = 1;
1473                     next;
1474                 }
1475                 my $newtag = $tags_new && @$tags_new
1476                   ? _merge_newtag( $tag, $tags_new )
1477                   : $tag;
1478                 my $controlled_ind = $authto->controlled_indicators({ record => $MARCto, biblio_tag => $newtag });
1479                 my $field_to = MARC::Field->new(
1480                     $newtag,
1481                     $controlled_ind->{ind1} // $field->indicator(1),
1482                     $controlled_ind->{ind2} // $field->indicator(2),
1483                     9 => $mergeto, # Needed to create field, will be moved
1484                 );
1485                 my ( @prefix, @postfix );
1486                 if ( !$overwrite ) {
1487                     # add subfields back in loose mode, check skip_subfields
1488                     # The first extra subfields will be in front of the
1489                     # controlled block, the rest at the end.
1490                     my $prefix_flag = 1;
1491                     foreach my $subfield ( $field->subfields ) {
1492                         next if $subfield->[0] eq '9'; # skip but leave flag
1493                         if ( $skip_subfields->{ $subfield->[0] } ) {
1494                             # This marks the beginning of the controlled block
1495                             $prefix_flag = 0;
1496                             next;
1497                         }
1498                         if ($prefix_flag) {
1499                             push @prefix, [ $subfield->[0], $subfield->[1] ];
1500                         } else {
1501                             push @postfix, [ $subfield->[0], $subfield->[1] ];
1502                         }
1503                     }
1504                 }
1505                 foreach my $subfield ( @prefix, @record_to, @postfix ) {
1506                     $field_to->add_subfields($subfield->[0] => $subfield->[1]);
1507                 }
1508                 if( exists $controlled_ind->{sub2} ) { # thesaurus info
1509                     if( defined $controlled_ind->{sub2} ) {
1510                         # Add or replace
1511                         $field_to->update( 2 => $controlled_ind->{sub2} );
1512                     } else {
1513                         # Key alerts us here to remove $2
1514                         $field_to->delete_subfield( code => '2' );
1515                     }
1516                 }
1517                 # Move $9 to the end
1518                 $field_to->delete_subfield( code => '9' );
1519                 $field_to->add_subfields( 9 => $mergeto );
1520
1521                 if ($tags_new && @$tags_new) {
1522                     $marcrecord->delete_field($field);
1523                     append_fields_ordered( $marcrecord, $field_to );
1524                 } else {
1525                     $field->replace_with($field_to);
1526                 }
1527                 $update = 1;
1528             }
1529         }
1530         next if !$update;
1531         ModBiblio($marcrecord, $biblionumber, GetFrameworkCode($biblionumber));
1532         $counteditedbiblio++;
1533     }
1534     return $counteditedbiblio;
1535 }
1536
1537 sub _merge_newtag {
1538 # Routine is only called for an (exceptional) authtypecode change
1539 # Fixes old behavior of returning the first tag found
1540     my ( $oldtag, $new_tags ) = @_;
1541
1542     # If we e.g. have 650 and 151,651,751 try 651 and check presence
1543     my $prefix = substr( $oldtag, 0, 1 );
1544     my $guess = $prefix . substr( $new_tags->[0], -2 );
1545     if( grep { $_ eq $guess } @$new_tags ) {
1546         return $guess;
1547     }
1548     # Otherwise return one from the same block e.g. 6XX for 650
1549     # If not there too, fall back to first new tag (old behavior!)
1550     my @same_block = grep { /^$prefix/ } @$new_tags;
1551     return @same_block ? $same_block[0] : $new_tags->[0];
1552 }
1553
1554 sub append_fields_ordered {
1555 # while we lack this function in MARC::Record
1556 # we do not want insert_fields_ordered since it inserts before
1557     my ( $record, $field ) = @_;
1558     if( my @flds = $record->field( $field->tag ) ) {
1559         $record->insert_fields_after( pop @flds, $field );
1560     } else { # now fallback to insert_fields_ordered
1561         $record->insert_fields_ordered( $field );
1562     }
1563 }
1564
1565 =head2 get_auth_type_location
1566
1567   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1568
1569 Get the tag and subfield used to store the heading type
1570 for indexing purposes.  The C<$auth_type> parameter is
1571 optional; if it is not supplied, assume ''.
1572
1573 This routine searches the MARC authority framework
1574 for the tag and subfield whose kohafield is 
1575 C<auth_header.authtypecode>; if no such field is
1576 defined in the framework, default to the hardcoded value
1577 specific to the MARC format.
1578
1579 =cut
1580
1581 sub get_auth_type_location {
1582     my $auth_type_code = @_ ? shift : '';
1583
1584     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1585     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1586         return ($tag, $subfield);
1587     } else {
1588         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1589             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1590         } else {
1591             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1592         }
1593     }
1594 }
1595
1596 END { }       # module clean-up code here (global destructor)
1597
1598 1;
1599 __END__
1600
1601 =head1 AUTHOR
1602
1603 Koha Development Team <http://koha-community.org/>
1604
1605 Paul POULAIN paul.poulain@free.fr
1606
1607 =cut
1608