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