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