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