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