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