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