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