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