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