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