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