Merge branch 'bug_9017' 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                 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     if (my $string=$record->subfield('100',"a")){
711         $string=~s/fre50/frey50/;
712         $record->field('100')->update('a'=>$string);
713     }
714     elsif ($record->field('100')){
715           $record->field('100')->update('a'=>$date."afrey50      ba0");
716     } else {      
717         $record->append_fields(
718         MARC::Field->new('100',' ',' '
719             ,'a'=>$date."afrey50      ba0")
720         );
721     }      
722   }
723   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
724   if (!$authid and $format eq "MARC21") {
725     # only need to do this fix when modifying an existing authority
726     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
727   } 
728   if (my $field=$record->field($auth_type_tag)){
729     $field->update($auth_type_subfield=>$authtypecode);
730   }
731   else {
732     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
733   }
734
735   my $auth_exists=0;
736   my $oldRecord;
737   if (!$authid) {
738     my $sth=$dbh->prepare("select max(authid) from auth_header");
739     $sth->execute;
740     ($authid)=$sth->fetchrow;
741     $authid=$authid+1;
742   ##Insert the recordID in MARC record 
743     unless ($record->field('001') && $record->field('001')->data() eq $authid){
744         $record->delete_field($record->field('001'));
745         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
746     }
747   } else {
748     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
749 #     warn "auth_exists = $auth_exists";
750   }
751   if ($auth_exists>0){
752       $oldRecord=GetAuthority($authid);
753       $record->add_fields('001',$authid) unless ($record->field('001'));
754 #       warn "\n\n\n enregistrement".$record->as_formatted;
755       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
756       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
757       $sth->finish;
758   }
759   else {
760     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
761     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
762     $sth->finish;
763     logaction( "AUTHORITIES", "ADD", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
764   }
765   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
766   return ($authid);
767 }
768
769
770 =head2 DelAuthority
771
772   $authid= &DelAuthority($authid)
773
774 Deletes $authid
775
776 =cut
777
778 sub DelAuthority {
779     my ($authid) = @_;
780     my $dbh=C4::Context->dbh;
781
782     logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog");
783     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
784     my $sth = $dbh->prepare("DELETE FROM auth_header WHERE authid=?");
785     $sth->execute($authid);
786 }
787
788 =head2 ModAuthority
789
790   $authid= &ModAuthority($authid,$record,$authtypecode)
791
792 Modifies authority record, optionally updates attached biblios.
793
794 =cut
795
796 sub ModAuthority {
797   my ($authid,$record,$authtypecode)=@_; # deprecated $merge parameter removed
798
799   my $dbh=C4::Context->dbh;
800   #Now rewrite the $record to table with an add
801   my $oldrecord=GetAuthority($authid);
802   $authid=AddAuthority($record,$authid,$authtypecode);
803
804   # If a library thinks that updating all biblios is a long process and wishes
805   # to leave that to a cron job, use misc/migration_tools/merge_authority.pl.
806   # In that case set system preference "dontmerge" to 1. Otherwise biblios will
807   # be updated.
808   unless(C4::Context->preference('dontmerge') eq '1'){
809       &merge($authid,$oldrecord,$authid,$record);
810   } else {
811       # save a record in need_merge_authorities table
812       my $sqlinsert="INSERT INTO need_merge_authorities (authid, done) ".
813         "VALUES (?,?)";
814       $dbh->do($sqlinsert,undef,($authid,0));
815   }
816   logaction( "AUTHORITIES", "MODIFY", $authid, "BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog");
817   return $authid;
818 }
819
820 =head2 GetAuthorityXML 
821
822   $marcxml= &GetAuthorityXML( $authid)
823
824 returns xml form of record $authid
825
826 =cut
827
828 sub GetAuthorityXML {
829   # Returns MARC::XML of the authority passed in parameter.
830   my ( $authid ) = @_;
831   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
832       my $dbh=C4::Context->dbh;
833       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
834       $sth->execute($authid);
835       my ($marcxml)=$sth->fetchrow;
836       return $marcxml;
837   }
838   else { 
839       # for MARC21, call GetAuthority instead of
840       # getting the XML directly since we may
841       # need to fix up the location of the authority
842       # code -- note that this is reasonably safe
843       # because GetAuthorityXML is used only by the 
844       # indexing processes like zebraqueue_start.pl
845       my $record = GetAuthority($authid);
846       return $record->as_xml_record('MARC21');
847   }
848 }
849
850 =head2 GetAuthority 
851
852   $record= &GetAuthority( $authid)
853
854 Returns MARC::Record of the authority passed in parameter.
855
856 =cut
857
858 sub GetAuthority {
859     my ($authid)=@_;
860     my $authority = Koha::Authority->get_from_authid($authid);
861     return unless $authority;
862     return ($authority->record);
863 }
864
865 =head2 GetAuthType 
866
867   $result = &GetAuthType($authtypecode)
868
869 If the authority type specified by C<$authtypecode> exists,
870 returns a hashref of the type's fields.  If the type
871 does not exist, returns undef.
872
873 =cut
874
875 sub GetAuthType {
876     my ($authtypecode) = @_;
877     my $dbh=C4::Context->dbh;
878     my $sth;
879     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
880                                 # type (FIXME but why?)
881         $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
882         $sth->execute($authtypecode);
883         if (my $res = $sth->fetchrow_hashref) {
884             return $res; 
885         }
886     }
887     return;
888 }
889
890
891 =head2 FindDuplicateAuthority
892
893   $record= &FindDuplicateAuthority( $record, $authtypecode)
894
895 return $authid,Summary if duplicate is found.
896
897 Comments : an improvement would be to return All the records that match.
898
899 =cut
900
901 sub FindDuplicateAuthority {
902
903     my ($record,$authtypecode)=@_;
904 #    warn "IN for ".$record->as_formatted;
905     my $dbh = C4::Context->dbh;
906 #    warn "".$record->as_formatted;
907     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
908     $sth->execute($authtypecode);
909     my ($auth_tag_to_report) = $sth->fetchrow;
910     $sth->finish;
911 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
912     # build a request for SearchAuthorities
913     my $query='at='.$authtypecode.' ';
914     my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
915     if ($record->field($auth_tag_to_report)) {
916       foreach ($record->field($auth_tag_to_report)->subfields()) {
917         $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
918       }
919     }
920     my ($error, $results, $total_hits) = C4::Search::SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
921     # there is at least 1 result => return the 1st one
922     if (!defined $error && @{$results} ) {
923       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
924       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
925     }
926     # no result, returns nothing
927     return;
928 }
929
930 =head2 BuildSummary
931
932   $summary= &BuildSummary( $record, $authid, $authtypecode)
933
934 Returns a hashref with a summary of the specified record.
935
936 Comment : authtypecode can be infered from both record and authid.
937 Moreover, authid can also be inferred from $record.
938 Would it be interesting to delete those things.
939
940 =cut
941
942 sub BuildSummary {
943     ## give this a Marc record to return summary
944     my ($record,$authid,$authtypecode)=@_;
945     my $dbh=C4::Context->dbh;
946     my %summary;
947     # handle $authtypecode is NULL or eq ""
948     if ($authtypecode) {
949         my $authref = GetAuthType($authtypecode);
950         $summary{authtypecode} = $authref->{authtypecode};
951         $summary{type} = $authref->{authtypetext};
952         $summary{summary} = $authref->{summary};
953     }
954     my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68';
955     my %marc21controlrefs = ( 'a' => 'earlier',
956         'b' => 'later',
957         'd' => 'acronym',
958         'f' => 'musical',
959         'g' => 'broader',
960         'h' => 'narrower',
961         'n' => 'notapplicable',
962         'i' => 'subfi',
963         't' => 'parent'
964     );
965     my %unimarc_relation_from_code = (
966         g => 'broader',
967         h => 'narrower',
968         a => 'seealso',
969     );
970     my %thesaurus;
971     $thesaurus{'1'}="Peuples";
972     $thesaurus{'2'}="Anthroponymes";
973     $thesaurus{'3'}="Oeuvres";
974     $thesaurus{'4'}="Chronologie";
975     $thesaurus{'5'}="Lieux";
976     $thesaurus{'6'}="Sujets";
977     #thesaurus a remplir
978     my $reported_tag;
979 # if the library has a summary defined, use it. Otherwise, build a standard one
980 # FIXME - it appears that the summary field in the authority frameworks
981 #         can work as a display template.  However, this doesn't
982 #         suit the MARC21 version, so for now the "templating"
983 #         feature will be enabled only for UNIMARC for backwards
984 #         compatibility.
985     if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
986         my @fields = $record->fields();
987 #             $reported_tag = '$9'.$result[$counter];
988         my @stringssummary;
989         foreach my $field (@fields) {
990             my $tag = $field->tag();
991             my $tagvalue = $field->as_string();
992             my $localsummary= $summary{summary};
993             $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
994             if ($tag<10) {
995                 if ($tag eq '001') {
996                     $reported_tag.='$3'.$field->data();
997                 }
998             } else {
999                 my @subf = $field->subfields;
1000                 for my $i (0..$#subf) {
1001                     my $subfieldcode = $subf[$i][0];
1002                     my $subfieldvalue = $subf[$i][1];
1003                     my $tagsubf = $tag.$subfieldcode;
1004                     $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1005                 }
1006             }
1007             push @stringssummary, $localsummary if ($localsummary ne $summary{summary});
1008         }
1009         my $resultstring;
1010         $resultstring = join(" -- ",@stringssummary);
1011         $resultstring =~ s/\[(.*?)\]//g;
1012         $resultstring =~ s/\n/<br>/g;
1013         $summary{summary}      =  $resultstring;
1014     }
1015     my @authorized;
1016     my @notes;
1017     my @seefrom;
1018     my @seealso;
1019     my @otherscript;
1020     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1021 # construct UNIMARC summary, that is quite different from MARC21 one
1022 # accepted form
1023         foreach my $field ($record->field('2..')) {
1024             push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), field => $field->tag() };
1025         }
1026 # rejected form(s)
1027         foreach my $field ($record->field('3..')) {
1028             push @notes, { note => $field->subfield('a'), field => $field->tag() };
1029         }
1030         foreach my $field ($record->field('4..')) {
1031             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1032             push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), type => 'seefrom', field => $field->tag() };
1033         }
1034
1035         # see :
1036         @seealso = map {
1037             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1038             my $heading = $_->as_string('abcdefgjxyz');
1039             {
1040                 field   => $_->tag,
1041                 type    => $type,
1042                 heading => $heading,
1043                 search  => $heading,
1044                 authid  => $_->subfield('9'),
1045             }
1046         } $record->field('5..');
1047
1048         # Other forms
1049         @otherscript = map { {
1050             lang      => $_->subfield('8') || '',
1051             term      => $_->subfield('a'),
1052             direction => 'ltr',
1053             field     => $_->tag,
1054         } } $record->field('7..');
1055
1056     } else {
1057 # construct MARC21 summary
1058 # FIXME - looping over 1XX is questionable
1059 # since MARC21 authority should have only one 1XX
1060         my $subfields_to_report;
1061         foreach my $field ($record->field('1..')) {
1062             my $tag = $field->tag();
1063             next if "152" eq $tag;
1064 # FIXME - 152 is not a good tag to use
1065 # in MARC21 -- purely local tags really ought to be
1066 # 9XX
1067             if ($tag eq '100') {
1068                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1069             } elsif ($tag eq '110') {
1070                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1071             } elsif ($tag eq '111') {
1072                 $subfields_to_report = 'acdefghklnpqstvxyz';
1073             } elsif ($tag eq '130') {
1074                 $subfields_to_report = 'adfghklmnoprstvxyz';
1075             } elsif ($tag eq '148') {
1076                 $subfields_to_report = 'abvxyz';
1077             } elsif ($tag eq '150') {
1078                 $subfields_to_report = 'abvxyz';
1079             } elsif ($tag eq '151') {
1080                 $subfields_to_report = 'avxyz';
1081             } elsif ($tag eq '155') {
1082                 $subfields_to_report = 'abvxyz';
1083             } elsif ($tag eq '180') {
1084                 $subfields_to_report = 'vxyz';
1085             } elsif ($tag eq '181') {
1086                 $subfields_to_report = 'vxyz';
1087             } elsif ($tag eq '182') {
1088                 $subfields_to_report = 'vxyz';
1089             } elsif ($tag eq '185') {
1090                 $subfields_to_report = 'vxyz';
1091             }
1092             if ($subfields_to_report) {
1093                 push @authorized, { heading => $field->as_string($subfields_to_report), field => $tag };
1094             } else {
1095                 push @authorized, { heading => $field->as_string(), field => $tag };
1096             }
1097         }
1098         foreach my $field ($record->field('4..')) { #See From
1099             my $type = 'seefrom';
1100             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1101             if ($type eq 'notapplicable') {
1102                 $type = substr $field->subfield('w'), 2, 1;
1103                 $type = 'earlier' if $type && $type ne 'n';
1104             }
1105             if ($type eq 'subfi') {
1106                 push @seefrom, { heading => $field->as_string($marc21subfields), type => ($field->subfield('i') || ''), field => $field->tag() };
1107             } else {
1108                 push @seefrom, { heading => $field->as_string($marc21subfields), type => $type, field => $field->tag() };
1109             }
1110         }
1111         foreach my $field ($record->field('5..')) { #See Also
1112             my $type = 'seealso';
1113             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1114             if ($type eq 'notapplicable') {
1115                 $type = substr $field->subfield('w'), 2, 1;
1116                 $type = 'earlier' if $type && $type ne 'n';
1117             }
1118             if ($type eq 'subfi') {
1119                 push @seealso, {
1120                     heading => $field->as_string($marc21subfields),
1121                     type => $field->subfield('i'),
1122                     field => $field->tag(),
1123                     search => $field->as_string($marc21subfields) || '',
1124                     authid => $field->subfield('9') || ''
1125                 };
1126             } else {
1127                 push @seealso, {
1128                     heading => $field->as_string($marc21subfields),
1129                     type => $type,
1130                     field => $field->tag(),
1131                     search => $field->as_string($marc21subfields) || '',
1132                     authid => $field->subfield('9') || ''
1133                 };
1134             }
1135         }
1136         foreach my $field ($record->field('6..')) {
1137             push @notes, { note => $field->as_string(), field => $field->tag() };
1138         }
1139         foreach my $field ($record->field('880')) {
1140             my $linkage = $field->subfield('6');
1141             my $category = substr $linkage, 0, 1;
1142             if ($category eq '1') {
1143                 $category = 'preferred';
1144             } elsif ($category eq '4') {
1145                 $category = 'seefrom';
1146             } elsif ($category eq '5') {
1147                 $category = 'seealso';
1148             }
1149             my $type;
1150             if ($field->subfield('w')) {
1151                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1152             } else {
1153                 $type = $category;
1154             }
1155             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1156             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1157         }
1158     }
1159     $summary{mainentry} = $authorized[0]->{heading};
1160     $summary{authorized} = \@authorized;
1161     $summary{notes} = \@notes;
1162     $summary{seefrom} = \@seefrom;
1163     $summary{seealso} = \@seealso;
1164     $summary{otherscript} = \@otherscript;
1165     return \%summary;
1166 }
1167
1168 =head2 GetAuthorizedHeading
1169
1170   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1171
1172 Takes a MARC::Record object describing an authority record or an authid, and
1173 returns a string representation of the first authorized heading. This routine
1174 should be considered a temporary shim to ease the future migration of authority
1175 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1176
1177 =cut
1178
1179 sub GetAuthorizedHeading {
1180     my $args = shift;
1181     my $record;
1182     unless ($record = $args->{record}) {
1183         return unless $args->{authid};
1184         $record = GetAuthority($args->{authid});
1185     }
1186     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1187 # construct UNIMARC summary, that is quite different from MARC21 one
1188 # accepted form
1189         foreach my $field ($record->field('2..')) {
1190             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1191         }
1192     } else {
1193         foreach my $field ($record->field('1..')) {
1194             my $tag = $field->tag();
1195             next if "152" eq $tag;
1196 # FIXME - 152 is not a good tag to use
1197 # in MARC21 -- purely local tags really ought to be
1198 # 9XX
1199             if ($tag eq '100') {
1200                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1201             } elsif ($tag eq '110') {
1202                 return $field->as_string('abcdefghklmnoprstvxyz68');
1203             } elsif ($tag eq '111') {
1204                 return $field->as_string('acdefghklnpqstvxyz68');
1205             } elsif ($tag eq '130') {
1206                 return $field->as_string('adfghklmnoprstvxyz68');
1207             } elsif ($tag eq '148') {
1208                 return $field->as_string('abvxyz68');
1209             } elsif ($tag eq '150') {
1210                 return $field->as_string('abvxyz68');
1211             } elsif ($tag eq '151') {
1212                 return $field->as_string('avxyz68');
1213             } elsif ($tag eq '155') {
1214                 return $field->as_string('abvxyz68');
1215             } elsif ($tag eq '180') {
1216                 return $field->as_string('vxyz68');
1217             } elsif ($tag eq '181') {
1218                 return $field->as_string('vxyz68');
1219             } elsif ($tag eq '182') {
1220                 return $field->as_string('vxyz68');
1221             } elsif ($tag eq '185') {
1222                 return $field->as_string('vxyz68');
1223             } else {
1224                 return $field->as_string();
1225             }
1226         }
1227     }
1228     return;
1229 }
1230
1231 =head2 BuildAuthHierarchies
1232
1233   $text= &BuildAuthHierarchies( $authid, $force)
1234
1235 return text containing trees for hierarchies
1236 for them to be stored in auth_header
1237
1238 Example of text:
1239 122,1314,2452;1324,2342,3,2452
1240
1241 =cut
1242
1243 sub BuildAuthHierarchies{
1244     my $authid = shift @_;
1245 #   warn "authid : $authid";
1246     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1247     my @globalresult;
1248     my $dbh=C4::Context->dbh;
1249     my $hierarchies;
1250     my $data = GetHeaderAuthority($authid);
1251     if ($data->{'authtrees'} and not $force){
1252         return $data->{'authtrees'};
1253 #  } elsif ($data->{'authtrees'}){
1254 #    $hierarchies=$data->{'authtrees'};
1255     } else {
1256         my $record = GetAuthority($authid);
1257         my $found;
1258         return unless $record;
1259         foreach my $field ($record->field('5..')){
1260             my $broader = 0;
1261             $broader = 1 if (
1262                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1263                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1264             if ($broader) {
1265                 my $subfauthid=_get_authid_subfield($field) || '';
1266                 next if ($subfauthid eq $authid);
1267                 my $parentrecord = GetAuthority($subfauthid);
1268                 next unless $parentrecord;
1269                 my $localresult=$hierarchies;
1270                 my $trees;
1271                 $trees = BuildAuthHierarchies($subfauthid);
1272                 my @trees;
1273                 if ($trees=~/;/){
1274                     @trees = split(/;/,$trees);
1275                 } else {
1276                     push @trees, $trees;
1277                 }
1278                 foreach (@trees){
1279                     $_.= ",$authid";
1280                 }
1281                 @globalresult = (@globalresult,@trees);
1282                 $found=1;
1283             }
1284             $hierarchies=join(";",@globalresult);
1285         }
1286 #Unless there is no ancestor, I am alone.
1287         $hierarchies="$authid" unless ($hierarchies);
1288     }
1289     AddAuthorityTrees($authid,$hierarchies);
1290     return $hierarchies;
1291 }
1292
1293 =head2 BuildAuthHierarchy
1294
1295   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1296
1297 return a hashref in order to display hierarchy for record and final Authid $authid
1298
1299 "loopparents"
1300 "loopchildren"
1301 "class"
1302 "loopauthid"
1303 "current_value"
1304 "value"
1305
1306 =cut
1307
1308 sub BuildAuthHierarchy{
1309     my $record = shift @_;
1310     my $class = shift @_;
1311     my $authid_constructed = shift @_;
1312     return unless ($record && $record->field('001'));
1313     my $authid=$record->field('001')->data();
1314     my %cell;
1315     my $parents=""; my $children="";
1316     my (@loopparents,@loopchildren);
1317     my $marcflavour = C4::Context->preference('marcflavour');
1318     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1319     foreach my $field ($record->field('5..')){
1320         my $subfauthid=_get_authid_subfield($field);
1321         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1322             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1323             if ($relationship eq 'h'){
1324                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1325             }
1326             elsif ($relationship eq 'g'){
1327                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1328             }
1329 # brothers could get in there with an else
1330         }
1331     }
1332     $cell{"parents"}=\@loopparents;
1333     $cell{"children"}=\@loopchildren;
1334     $cell{"class"}=$class;
1335     $cell{"authid"}=$authid;
1336     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1337     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1338     return \%cell;
1339 }
1340
1341 =head2 BuildAuthHierarchyBranch
1342
1343   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1344
1345 Return a data structure representing an authority hierarchy
1346 given a list of authorities representing a single branch in
1347 an authority hierarchy tree. $authid is the current node in
1348 the tree (which may or may not be somewhere in the middle).
1349 $cnt represents the level of the upper-most item, and is only
1350 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1351 don't ever pass in anything but zero to it).
1352
1353 =cut
1354
1355 sub BuildAuthHierarchyBranch {
1356     my ($tree, $authid, $cnt) = @_;
1357     $cnt |= 0;
1358     my $elementdata = GetAuthority(shift @$tree);
1359     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1360     if (scalar @$tree > 0) {
1361         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1362         my $nextAuthid = $nextBranch->{authid};
1363         my $found;
1364         # If we already have the next branch listed as a child, let's
1365         # replace the old listing with the new one. If not, we will add
1366         # the branch at the end.
1367         foreach my $cell (@{$branch->{children}}) {
1368             if ($cell->{authid} eq $nextAuthid) {
1369                 $cell = $nextBranch;
1370                 $found = 1;
1371                 last;
1372             }
1373         }
1374         push @{$branch->{children}}, $nextBranch unless $found;
1375     }
1376     return $branch;
1377 }
1378
1379 =head2 GenerateHierarchy
1380
1381   $hierarchy = &GenerateHierarchy($authid);
1382
1383 Return an arrayref holding one or more "trees" representing
1384 authority hierarchies.
1385
1386 =cut
1387
1388 sub GenerateHierarchy {
1389     my ($authid) = @_;
1390     my $trees    = BuildAuthHierarchies($authid);
1391     my @trees    = split /;/,$trees ;
1392     push @trees,$trees unless (@trees);
1393     my @loophierarchies;
1394     foreach my $tree (@trees){
1395         my @tree=split /,/,$tree;
1396         push @tree, $tree unless (@tree);
1397         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1398         push @loophierarchies, [ $branch ];
1399     }
1400     return \@loophierarchies;
1401 }
1402
1403 sub _get_authid_subfield{
1404     my ($field)=@_;
1405     return $field->subfield('9')||$field->subfield('3');
1406 }
1407 =head2 GetHeaderAuthority
1408
1409   $ref= &GetHeaderAuthority( $authid)
1410
1411 return a hashref in order auth_header table data
1412
1413 =cut
1414
1415 sub GetHeaderAuthority{
1416   my $authid = shift @_;
1417   my $sql= "SELECT * from auth_header WHERE authid = ?";
1418   my $dbh=C4::Context->dbh;
1419   my $rq= $dbh->prepare($sql);
1420   $rq->execute($authid);
1421   my $data= $rq->fetchrow_hashref;
1422   return $data;
1423 }
1424
1425 =head2 AddAuthorityTrees
1426
1427   $ref= &AddAuthorityTrees( $authid, $trees)
1428
1429 return success or failure
1430
1431 =cut
1432
1433 sub AddAuthorityTrees{
1434   my $authid = shift @_;
1435   my $trees = shift @_;
1436   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1437   my $dbh=C4::Context->dbh;
1438   my $rq= $dbh->prepare($sql);
1439   return $rq->execute($trees,$authid);
1440 }
1441
1442 =head2 merge
1443
1444   $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1445
1446 Could add some feature : Migrating from a typecode to an other for instance.
1447 Then we should add some new parameter : bibliotargettag, authtargettag
1448
1449 =cut
1450
1451 sub merge {
1452     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1453     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1454     my $dbh=C4::Context->dbh;
1455     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1456     my $authtypecodeto = GetAuthTypeCode($mergeto);
1457 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1458     # return if authority does not exist
1459     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1460     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1461     # search the tag to report
1462     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1463     $sth->execute($authtypecodefrom);
1464     my ($auth_tag_to_report_from) = $sth->fetchrow;
1465     $sth->execute($authtypecodeto);
1466     my ($auth_tag_to_report_to) = $sth->fetchrow;
1467     
1468     my @record_to;
1469     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1470     my @record_from;
1471     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1472     
1473     my @reccache;
1474     # search all biblio tags using this authority.
1475     #Getting marcbiblios impacted by the change.
1476     if (C4::Context->preference('NoZebra')) {
1477         #nozebra way    
1478         my $dbh=C4::Context->dbh;
1479         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1480         $rq->execute;
1481         while (my $biblionumbers=$rq->fetchrow){
1482             my @biblionumbers=split /;/,$biblionumbers;
1483             foreach (@biblionumbers) {
1484                 if ($_=~/(\d+),.*/) {
1485                     my $marc=GetMarcBiblio($1);
1486                     push @reccache,$marc;
1487                 }
1488             }
1489         }
1490     } else {
1491         #zebra connection  
1492         my $oConnection=C4::Context->Zconn("biblioserver",0);
1493         # We used to use XML syntax here, but that no longer works.
1494         # Thankfully, we don't need it.
1495         my $query;
1496         $query= "an=".$mergefrom;
1497         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1498         my $count = 0;
1499         if  ($oResult) {
1500             $count=$oResult->size();
1501         }
1502         my $z=0;
1503         while ( $z<$count ) {
1504             my $rec;
1505             $rec=$oResult->record($z);
1506             my $marcdata = $rec->raw();
1507             my $marcrecordzebra= MARC::Record->new_from_usmarc($marcdata);
1508             my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1509             my $i = ($biblionumbertagfield < 10) ? $marcrecordzebra->field($biblionumbertagfield)->data : $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1510             my $marcrecorddb=GetMarcBiblio($i);
1511             push @reccache, $marcrecorddb;
1512             $z++;
1513         }
1514         $oResult->destroy();
1515     }
1516     #warn scalar(@reccache)." biblios to update";
1517     # Get All candidate Tags for the change 
1518     # (This will reduce the search scope in marc records).
1519     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1520     $sth->execute($authtypecodefrom);
1521     my @tags_using_authtype;
1522     while (my ($tagfield) = $sth->fetchrow) {
1523         push @tags_using_authtype,$tagfield ;
1524     }
1525     my $tag_to=0;  
1526     if ($authtypecodeto ne $authtypecodefrom){  
1527         # If many tags, take the first
1528         $sth->execute($authtypecodeto);    
1529         $tag_to=$sth->fetchrow;
1530         #warn $tag_to;    
1531     }  
1532     # BulkEdit marc records
1533     # May be used as a template for a bulkedit field  
1534     foreach my $marcrecord(@reccache){
1535         my $update;           
1536         foreach my $tagfield (@tags_using_authtype){
1537 #             warn "tagfield : $tagfield ";
1538             foreach my $field ($marcrecord->field($tagfield)){
1539                 # biblio is linked to authority with $9 subfield containing authid
1540                 my $auth_number=$field->subfield("9");
1541                 my $tag=$field->tag();          
1542                 if ($auth_number==$mergefrom) {
1543                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1544                 my $exclude='9';
1545                 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1546                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1547                     $exclude.= $subfield->[0];
1548                 }
1549                 $exclude='['.$exclude.']';
1550 #               add subfields in $field not included in @record_to
1551                 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1552                 foreach my $subfield (@restore) {
1553                    $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1554                 }
1555                 $marcrecord->delete_field($field);
1556                 $marcrecord->insert_grouped_field($field_to);            
1557                 $update=1;
1558                 }
1559             }#for each tag
1560         }#foreach tagfield
1561         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1562         my $biblionumber;
1563         if ($bibliotag<10){
1564             $biblionumber=$marcrecord->field($bibliotag)->data;
1565         }
1566         else {
1567             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1568         }
1569         unless ($biblionumber){
1570             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1571             next;
1572         }
1573         if ($update==1){
1574             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1575             $counteditedbiblio++;
1576             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1577         }    
1578     }#foreach $marc
1579     return $counteditedbiblio;  
1580   # now, find every other authority linked with this authority
1581   # now, find every other authority linked with this authority
1582 #   my $oConnection=C4::Context->Zconn("authorityserver");
1583 #   my $query;
1584 # # att 9210               Auth-Internal-authtype
1585 # # att 9220               Auth-Internal-LN
1586 # # ccl.properties to add for authorities
1587 #   $query= "= ".$mergefrom;
1588 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1589 #   my $count=$oResult->size() if  ($oResult);
1590 #   my @reccache;
1591 #   my $z=0;
1592 #   while ( $z<$count ) {
1593 #   my $rec;
1594 #           $rec=$oResult->record($z);
1595 #       my $marcdata = $rec->raw();
1596 #   push @reccache, $marcdata;
1597 #   $z++;
1598 #   }
1599 #   $oResult->destroy();
1600 #   foreach my $marc(@reccache){
1601 #     my $update;
1602 #     my $marcrecord;
1603 #     $marcrecord = MARC::File::USMARC::decode($marc);
1604 #     foreach my $tagfield (@tags_using_authtype){
1605 #       $tagfield=substr($tagfield,0,3);
1606 #       my @tags = $marcrecord->field($tagfield);
1607 #       foreach my $tag (@tags){
1608 #         my $tagsubs=$tag->subfield("9");
1609 #     #warn "$tagfield:$tagsubs:$mergefrom";
1610 #         if ($tagsubs== $mergefrom) {
1611 #           $tag->update("9" =>$mergeto);
1612 #           foreach my $subfield (@record_to) {
1613 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1614 #             $tag->update($subfield->[0] =>$subfield->[1]);
1615 #           }#for $subfield
1616 #         }
1617 #         $marcrecord->delete_field($tag);
1618 #         $marcrecord->add_fields($tag);
1619 #         $update=1;
1620 #       }#for each tag
1621 #     }#foreach tagfield
1622 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1623 #     if ($update==1){
1624 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1625 #     }
1626
1627 #   }#foreach $marc
1628 }#sub
1629
1630 =head2 get_auth_type_location
1631
1632   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1633
1634 Get the tag and subfield used to store the heading type
1635 for indexing purposes.  The C<$auth_type> parameter is
1636 optional; if it is not supplied, assume ''.
1637
1638 This routine searches the MARC authority framework
1639 for the tag and subfield whose kohafield is 
1640 C<auth_header.authtypecode>; if no such field is
1641 defined in the framework, default to the hardcoded value
1642 specific to the MARC format.
1643
1644 =cut
1645
1646 sub get_auth_type_location {
1647     my $auth_type_code = @_ ? shift : '';
1648
1649     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1650     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1651         return ($tag, $subfield);
1652     } else {
1653         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1654             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1655         } else {
1656             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1657         }
1658     }
1659 }
1660
1661 END { }       # module clean-up code here (global destructor)
1662
1663 1;
1664 __END__
1665
1666 =head1 AUTHOR
1667
1668 Koha Development Team <http://koha-community.org/>
1669
1670 Paul POULAIN paul.poulain@free.fr
1671
1672 =cut
1673