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