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