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