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