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