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