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