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