Bug 8870 UNIMARC authorities search doesn't display information properly
[srvgit] / 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 %unimarc_relation_from_code = (
963         g => 'broader',
964         h => 'narrower',
965         a => 'seealso',
966     );
967     my %thesaurus;
968     $thesaurus{'1'}="Peuples";
969     $thesaurus{'2'}="Anthroponymes";
970     $thesaurus{'3'}="Oeuvres";
971     $thesaurus{'4'}="Chronologie";
972     $thesaurus{'5'}="Lieux";
973     $thesaurus{'6'}="Sujets";
974     #thesaurus a remplir
975     my $reported_tag;
976 # if the library has a summary defined, use it. Otherwise, build a standard one
977 # FIXME - it appears that the summary field in the authority frameworks
978 #         can work as a display template.  However, this doesn't
979 #         suit the MARC21 version, so for now the "templating"
980 #         feature will be enabled only for UNIMARC for backwards
981 #         compatibility.
982     if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') {
983         my @fields = $record->fields();
984 #             $reported_tag = '$9'.$result[$counter];
985         my @stringssummary;
986         foreach my $field (@fields) {
987             my $tag = $field->tag();
988             my $tagvalue = $field->as_string();
989             my $localsummary= $summary{summary};
990             $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
991             if ($tag<10) {
992                 if ($tag eq '001') {
993                     $reported_tag.='$3'.$field->data();
994                 }
995             } else {
996                 my @subf = $field->subfields;
997                 for my $i (0..$#subf) {
998                     my $subfieldcode = $subf[$i][0];
999                     my $subfieldvalue = $subf[$i][1];
1000                     my $tagsubf = $tag.$subfieldcode;
1001                     $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
1002                 }
1003             }
1004             push @stringssummary, $localsummary if ($localsummary ne $summary{summary});
1005         }
1006         my $resultstring;
1007         $resultstring = join(" -- ",@stringssummary);
1008         $resultstring =~ s/\[(.*?)\]//g;
1009         $resultstring =~ s/\n/<br>/g;
1010         $summary{summary}      =  $resultstring;
1011     }
1012     my @authorized;
1013     my @notes;
1014     my @seefrom;
1015     my @seealso;
1016     my @otherscript;
1017     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1018 # construct UNIMARC summary, that is quite different from MARC21 one
1019 # accepted form
1020         foreach my $field ($record->field('2..')) {
1021             push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), field => $field->tag() };
1022         }
1023 # rejected form(s)
1024         foreach my $field ($record->field('3..')) {
1025             push @notes, { note => $field->subfield('a'), field => $field->tag() };
1026         }
1027         foreach my $field ($record->field('4..')) {
1028             my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : '';
1029             push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), type => 'seefrom', field => $field->tag() };
1030         }
1031
1032         # see :
1033         @seealso = map {
1034             my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'};
1035             my $heading = $_->as_string('abcdefgjxyz');
1036             {
1037                 field   => $_->tag,
1038                 type    => $type,
1039                 heading => $heading,
1040                 search  => $heading,
1041                 authid  => $_->subfield('9'),
1042             }
1043         } $record->field('5..');
1044
1045         # Other forms
1046         @otherscript = map { {
1047             lang      => $_->subfield('8') || '',
1048             term      => $_->subfield('a'),
1049             direction => 'ltr',
1050             field     => $_->tag,
1051         } } $record->field('7..');
1052
1053     } else {
1054 # construct MARC21 summary
1055 # FIXME - looping over 1XX is questionable
1056 # since MARC21 authority should have only one 1XX
1057         my $subfields_to_report;
1058         foreach my $field ($record->field('1..')) {
1059             my $tag = $field->tag();
1060             next if "152" eq $tag;
1061 # FIXME - 152 is not a good tag to use
1062 # in MARC21 -- purely local tags really ought to be
1063 # 9XX
1064             if ($tag eq '100') {
1065                 $subfields_to_report = 'abcdefghjklmnopqrstvxyz';
1066             } elsif ($tag eq '110') {
1067                 $subfields_to_report = 'abcdefghklmnoprstvxyz';
1068             } elsif ($tag eq '111') {
1069                 $subfields_to_report = 'acdefghklnpqstvxyz';
1070             } elsif ($tag eq '130') {
1071                 $subfields_to_report = 'adfghklmnoprstvxyz';
1072             } elsif ($tag eq '148') {
1073                 $subfields_to_report = 'abvxyz';
1074             } elsif ($tag eq '150') {
1075                 $subfields_to_report = 'abvxyz';
1076             } elsif ($tag eq '151') {
1077                 $subfields_to_report = 'avxyz';
1078             } elsif ($tag eq '155') {
1079                 $subfields_to_report = 'abvxyz';
1080             } elsif ($tag eq '180') {
1081                 $subfields_to_report = 'vxyz';
1082             } elsif ($tag eq '181') {
1083                 $subfields_to_report = 'vxyz';
1084             } elsif ($tag eq '182') {
1085                 $subfields_to_report = 'vxyz';
1086             } elsif ($tag eq '185') {
1087                 $subfields_to_report = 'vxyz';
1088             }
1089             if ($subfields_to_report) {
1090                 push @authorized, { heading => $field->as_string($subfields_to_report), field => $tag };
1091             } else {
1092                 push @authorized, { heading => $field->as_string(), field => $tag };
1093             }
1094         }
1095         foreach my $field ($record->field('4..')) { #See From
1096             my $type = 'seefrom';
1097             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1098             if ($type eq 'notapplicable') {
1099                 $type = substr $field->subfield('w'), 2, 1;
1100                 $type = 'earlier' if $type && $type ne 'n';
1101             }
1102             if ($type eq 'subfi') {
1103                 push @seefrom, { heading => $field->as_string($marc21subfields), type => ($field->subfield('i') || ''), field => $field->tag() };
1104             } else {
1105                 push @seefrom, { heading => $field->as_string($marc21subfields), type => $type, field => $field->tag() };
1106             }
1107         }
1108         foreach my $field ($record->field('5..')) { #See Also
1109             my $type = 'seealso';
1110             $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w'));
1111             if ($type eq 'notapplicable') {
1112                 $type = substr $field->subfield('w'), 2, 1;
1113                 $type = 'earlier' if $type && $type ne 'n';
1114             }
1115             if ($type eq 'subfi') {
1116                 push @seealso, {
1117                     heading => $field->as_string($marc21subfields),
1118                     type => $field->subfield('i'),
1119                     field => $field->tag(),
1120                     search => $field->as_string($marc21subfields) || '',
1121                     authid => $field->subfield('9') || ''
1122                 };
1123             } else {
1124                 push @seealso, {
1125                     heading => $field->as_string($marc21subfields),
1126                     type => $type,
1127                     field => $field->tag(),
1128                     search => $field->as_string($marc21subfields) || '',
1129                     authid => $field->subfield('9') || ''
1130                 };
1131             }
1132         }
1133         foreach my $field ($record->field('6..')) {
1134             push @notes, { note => $field->as_string(), field => $field->tag() };
1135         }
1136         foreach my $field ($record->field('880')) {
1137             my $linkage = $field->subfield('6');
1138             my $category = substr $linkage, 0, 1;
1139             if ($category eq '1') {
1140                 $category = 'preferred';
1141             } elsif ($category eq '4') {
1142                 $category = 'seefrom';
1143             } elsif ($category eq '5') {
1144                 $category = 'seealso';
1145             }
1146             my $type;
1147             if ($field->subfield('w')) {
1148                 $type = $marc21controlrefs{substr $field->subfield('w'), '0'};
1149             } else {
1150                 $type = $category;
1151             }
1152             my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr';
1153             push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage };
1154         }
1155     }
1156     $summary{mainentry} = $authorized[0]->{heading};
1157     $summary{authorized} = \@authorized;
1158     $summary{notes} = \@notes;
1159     $summary{seefrom} = \@seefrom;
1160     $summary{seealso} = \@seealso;
1161     $summary{otherscript} = \@otherscript;
1162     return \%summary;
1163 }
1164
1165 =head2 GetAuthorizedHeading
1166
1167   $heading = &GetAuthorizedHeading({ record => $record, authid => $authid })
1168
1169 Takes a MARC::Record object describing an authority record or an authid, and
1170 returns a string representation of the first authorized heading. This routine
1171 should be considered a temporary shim to ease the future migration of authority
1172 data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority.
1173
1174 =cut
1175
1176 sub GetAuthorizedHeading {
1177     my $args = shift;
1178     my $record;
1179     unless ($record = $args->{record}) {
1180         return unless $args->{authid};
1181         $record = GetAuthority($args->{authid});
1182     }
1183     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
1184 # construct UNIMARC summary, that is quite different from MARC21 one
1185 # accepted form
1186         foreach my $field ($record->field('2..')) {
1187             return $field->as_string('abcdefghijlmnopqrstuvwxyz');
1188         }
1189     } else {
1190         foreach my $field ($record->field('1..')) {
1191             my $tag = $field->tag();
1192             next if "152" eq $tag;
1193 # FIXME - 152 is not a good tag to use
1194 # in MARC21 -- purely local tags really ought to be
1195 # 9XX
1196             if ($tag eq '100') {
1197                 return $field->as_string('abcdefghjklmnopqrstvxyz68');
1198             } elsif ($tag eq '110') {
1199                 return $field->as_string('abcdefghklmnoprstvxyz68');
1200             } elsif ($tag eq '111') {
1201                 return $field->as_string('acdefghklnpqstvxyz68');
1202             } elsif ($tag eq '130') {
1203                 return $field->as_string('adfghklmnoprstvxyz68');
1204             } elsif ($tag eq '148') {
1205                 return $field->as_string('abvxyz68');
1206             } elsif ($tag eq '150') {
1207                 return $field->as_string('abvxyz68');
1208             } elsif ($tag eq '151') {
1209                 return $field->as_string('avxyz68');
1210             } elsif ($tag eq '155') {
1211                 return $field->as_string('abvxyz68');
1212             } elsif ($tag eq '180') {
1213                 return $field->as_string('vxyz68');
1214             } elsif ($tag eq '181') {
1215                 return $field->as_string('vxyz68');
1216             } elsif ($tag eq '182') {
1217                 return $field->as_string('vxyz68');
1218             } elsif ($tag eq '185') {
1219                 return $field->as_string('vxyz68');
1220             } else {
1221                 return $field->as_string();
1222             }
1223         }
1224     }
1225     return;
1226 }
1227
1228 =head2 BuildAuthHierarchies
1229
1230   $text= &BuildAuthHierarchies( $authid, $force)
1231
1232 return text containing trees for hierarchies
1233 for them to be stored in auth_header
1234
1235 Example of text:
1236 122,1314,2452;1324,2342,3,2452
1237
1238 =cut
1239
1240 sub BuildAuthHierarchies{
1241     my $authid = shift @_;
1242 #   warn "authid : $authid";
1243     my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1);
1244     my @globalresult;
1245     my $dbh=C4::Context->dbh;
1246     my $hierarchies;
1247     my $data = GetHeaderAuthority($authid);
1248     if ($data->{'authtrees'} and not $force){
1249         return $data->{'authtrees'};
1250 #  } elsif ($data->{'authtrees'}){
1251 #    $hierarchies=$data->{'authtrees'};
1252     } else {
1253         my $record = GetAuthority($authid);
1254         my $found;
1255         return unless $record;
1256         foreach my $field ($record->field('5..')){
1257             my $broader = 0;
1258             $broader = 1 if (
1259                     (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') ||
1260                     (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g'));
1261             if ($broader) {
1262                 my $subfauthid=_get_authid_subfield($field) || '';
1263                 next if ($subfauthid eq $authid);
1264                 my $parentrecord = GetAuthority($subfauthid);
1265                 next unless $parentrecord;
1266                 my $localresult=$hierarchies;
1267                 my $trees;
1268                 $trees = BuildAuthHierarchies($subfauthid);
1269                 my @trees;
1270                 if ($trees=~/;/){
1271                     @trees = split(/;/,$trees);
1272                 } else {
1273                     push @trees, $trees;
1274                 }
1275                 foreach (@trees){
1276                     $_.= ",$authid";
1277                 }
1278                 @globalresult = (@globalresult,@trees);
1279                 $found=1;
1280             }
1281             $hierarchies=join(";",@globalresult);
1282         }
1283 #Unless there is no ancestor, I am alone.
1284         $hierarchies="$authid" unless ($hierarchies);
1285     }
1286     AddAuthorityTrees($authid,$hierarchies);
1287     return $hierarchies;
1288 }
1289
1290 =head2 BuildAuthHierarchy
1291
1292   $ref= &BuildAuthHierarchy( $record, $class,$authid)
1293
1294 return a hashref in order to display hierarchy for record and final Authid $authid
1295
1296 "loopparents"
1297 "loopchildren"
1298 "class"
1299 "loopauthid"
1300 "current_value"
1301 "value"
1302
1303 =cut
1304
1305 sub BuildAuthHierarchy{
1306     my $record = shift @_;
1307     my $class = shift @_;
1308     my $authid_constructed = shift @_;
1309     return unless ($record && $record->field('001'));
1310     my $authid=$record->field('001')->data();
1311     my %cell;
1312     my $parents=""; my $children="";
1313     my (@loopparents,@loopchildren);
1314     my $marcflavour = C4::Context->preference('marcflavour');
1315     my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w';
1316     foreach my $field ($record->field('5..')){
1317         my $subfauthid=_get_authid_subfield($field);
1318         if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){
1319             my $relationship = substr($field->subfield($relationshipsf), 0, 1);
1320             if ($relationship eq 'h'){
1321                 push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1322             }
1323             elsif ($relationship eq 'g'){
1324                 push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')};
1325             }
1326 # brothers could get in there with an else
1327         }
1328     }
1329     $cell{"parents"}=\@loopparents;
1330     $cell{"children"}=\@loopchildren;
1331     $cell{"class"}=$class;
1332     $cell{"authid"}=$authid;
1333     $cell{"current_value"} =1 if ($authid eq $authid_constructed);
1334     $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a');
1335     return \%cell;
1336 }
1337
1338 =head2 BuildAuthHierarchyBranch
1339
1340   $branch = &BuildAuthHierarchyBranch( $tree, $authid[, $cnt])
1341
1342 Return a data structure representing an authority hierarchy
1343 given a list of authorities representing a single branch in
1344 an authority hierarchy tree. $authid is the current node in
1345 the tree (which may or may not be somewhere in the middle).
1346 $cnt represents the level of the upper-most item, and is only
1347 used when BuildAuthHierarchyBranch is called recursively (i.e.,
1348 don't ever pass in anything but zero to it).
1349
1350 =cut
1351
1352 sub BuildAuthHierarchyBranch {
1353     my ($tree, $authid, $cnt) = @_;
1354     $cnt |= 0;
1355     my $elementdata = GetAuthority(shift @$tree);
1356     my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid);
1357     if (scalar @$tree > 0) {
1358         my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt);
1359         my $nextAuthid = $nextBranch->{authid};
1360         my $found;
1361         # If we already have the next branch listed as a child, let's
1362         # replace the old listing with the new one. If not, we will add
1363         # the branch at the end.
1364         foreach my $cell (@{$branch->{children}}) {
1365             if ($cell->{authid} eq $nextAuthid) {
1366                 $cell = $nextBranch;
1367                 $found = 1;
1368                 last;
1369             }
1370         }
1371         push @{$branch->{children}}, $nextBranch unless $found;
1372     }
1373     return $branch;
1374 }
1375
1376 =head2 GenerateHierarchy
1377
1378   $hierarchy = &GenerateHierarchy($authid);
1379
1380 Return an arrayref holding one or more "trees" representing
1381 authority hierarchies.
1382
1383 =cut
1384
1385 sub GenerateHierarchy {
1386     my ($authid) = @_;
1387     my $trees    = BuildAuthHierarchies($authid);
1388     my @trees    = split /;/,$trees ;
1389     push @trees,$trees unless (@trees);
1390     my @loophierarchies;
1391     foreach my $tree (@trees){
1392         my @tree=split /,/,$tree;
1393         push @tree, $tree unless (@tree);
1394         my $branch = BuildAuthHierarchyBranch(\@tree, $authid);
1395         push @loophierarchies, [ $branch ];
1396     }
1397     return \@loophierarchies;
1398 }
1399
1400 sub _get_authid_subfield{
1401     my ($field)=@_;
1402     return $field->subfield('9')||$field->subfield('3');
1403 }
1404 =head2 GetHeaderAuthority
1405
1406   $ref= &GetHeaderAuthority( $authid)
1407
1408 return a hashref in order auth_header table data
1409
1410 =cut
1411
1412 sub GetHeaderAuthority{
1413   my $authid = shift @_;
1414   my $sql= "SELECT * from auth_header WHERE authid = ?";
1415   my $dbh=C4::Context->dbh;
1416   my $rq= $dbh->prepare($sql);
1417   $rq->execute($authid);
1418   my $data= $rq->fetchrow_hashref;
1419   return $data;
1420 }
1421
1422 =head2 AddAuthorityTrees
1423
1424   $ref= &AddAuthorityTrees( $authid, $trees)
1425
1426 return success or failure
1427
1428 =cut
1429
1430 sub AddAuthorityTrees{
1431   my $authid = shift @_;
1432   my $trees = shift @_;
1433   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1434   my $dbh=C4::Context->dbh;
1435   my $rq= $dbh->prepare($sql);
1436   return $rq->execute($trees,$authid);
1437 }
1438
1439 =head2 merge
1440
1441   $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1442
1443 Could add some feature : Migrating from a typecode to an other for instance.
1444 Then we should add some new parameter : bibliotargettag, authtargettag
1445
1446 =cut
1447
1448 sub merge {
1449     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1450     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1451     my $dbh=C4::Context->dbh;
1452     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1453     my $authtypecodeto = GetAuthTypeCode($mergeto);
1454 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1455     # return if authority does not exist
1456     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1457     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1458     # search the tag to report
1459     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1460     $sth->execute($authtypecodefrom);
1461     my ($auth_tag_to_report_from) = $sth->fetchrow;
1462     $sth->execute($authtypecodeto);
1463     my ($auth_tag_to_report_to) = $sth->fetchrow;
1464     
1465     my @record_to;
1466     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1467     my @record_from;
1468     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1469     
1470     my @reccache;
1471     # search all biblio tags using this authority.
1472     #Getting marcbiblios impacted by the change.
1473     if (C4::Context->preference('NoZebra')) {
1474         #nozebra way    
1475         my $dbh=C4::Context->dbh;
1476         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1477         $rq->execute;
1478         while (my $biblionumbers=$rq->fetchrow){
1479             my @biblionumbers=split /;/,$biblionumbers;
1480             foreach (@biblionumbers) {
1481                 if ($_=~/(\d+),.*/) {
1482                     my $marc=GetMarcBiblio($1);
1483                     push @reccache,$marc;
1484                 }
1485             }
1486         }
1487     } else {
1488         #zebra connection  
1489         my $oConnection=C4::Context->Zconn("biblioserver",0);
1490         # We used to use XML syntax here, but that no longer works.
1491         # Thankfully, we don't need it.
1492         my $query;
1493         $query= "an=".$mergefrom;
1494         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1495         my $count = 0;
1496         if  ($oResult) {
1497             $count=$oResult->size();
1498         }
1499         my $z=0;
1500         while ( $z<$count ) {
1501             my $rec;
1502             $rec=$oResult->record($z);
1503             my $marcdata = $rec->raw();
1504             my $marcrecordzebra= MARC::Record->new_from_usmarc($marcdata);
1505             my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1506             my $i = ($biblionumbertagfield < 10) ? $marcrecordzebra->field($biblionumbertagfield)->data : $marcrecordzebra->subfield($biblionumbertagfield, $biblionumbertagsubfield);
1507             my $marcrecorddb=GetMarcBiblio($i);
1508             push @reccache, $marcrecorddb;
1509             $z++;
1510         }
1511         $oResult->destroy();
1512     }
1513     #warn scalar(@reccache)." biblios to update";
1514     # Get All candidate Tags for the change 
1515     # (This will reduce the search scope in marc records).
1516     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1517     $sth->execute($authtypecodefrom);
1518     my @tags_using_authtype;
1519     while (my ($tagfield) = $sth->fetchrow) {
1520         push @tags_using_authtype,$tagfield ;
1521     }
1522     my $tag_to=0;  
1523     if ($authtypecodeto ne $authtypecodefrom){  
1524         # If many tags, take the first
1525         $sth->execute($authtypecodeto);    
1526         $tag_to=$sth->fetchrow;
1527         #warn $tag_to;    
1528     }  
1529     # BulkEdit marc records
1530     # May be used as a template for a bulkedit field  
1531     foreach my $marcrecord(@reccache){
1532         my $update;           
1533         foreach my $tagfield (@tags_using_authtype){
1534 #             warn "tagfield : $tagfield ";
1535             foreach my $field ($marcrecord->field($tagfield)){
1536                 # biblio is linked to authority with $9 subfield containing authid
1537                 my $auth_number=$field->subfield("9");
1538                 my $tag=$field->tag();          
1539                 if ($auth_number==$mergefrom) {
1540                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1541                 my $exclude='9';
1542                 foreach my $subfield (grep {$_->[0] ne '9'} @record_to) {
1543                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1544                     $exclude.= $subfield->[0];
1545                 }
1546                 $exclude='['.$exclude.']';
1547 #               add subfields in $field not included in @record_to
1548                 my @restore= grep {$_->[0]!~/$exclude/} $field->subfields();
1549                 foreach my $subfield (@restore) {
1550                    $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1551                 }
1552                 $marcrecord->delete_field($field);
1553                 $marcrecord->insert_grouped_field($field_to);            
1554                 $update=1;
1555                 }
1556             }#for each tag
1557         }#foreach tagfield
1558         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1559         my $biblionumber;
1560         if ($bibliotag<10){
1561             $biblionumber=$marcrecord->field($bibliotag)->data;
1562         }
1563         else {
1564             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1565         }
1566         unless ($biblionumber){
1567             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1568             next;
1569         }
1570         if ($update==1){
1571             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1572             $counteditedbiblio++;
1573             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1574         }    
1575     }#foreach $marc
1576     return $counteditedbiblio;  
1577   # now, find every other authority linked with this authority
1578   # now, find every other authority linked with this authority
1579 #   my $oConnection=C4::Context->Zconn("authorityserver");
1580 #   my $query;
1581 # # att 9210               Auth-Internal-authtype
1582 # # att 9220               Auth-Internal-LN
1583 # # ccl.properties to add for authorities
1584 #   $query= "= ".$mergefrom;
1585 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1586 #   my $count=$oResult->size() if  ($oResult);
1587 #   my @reccache;
1588 #   my $z=0;
1589 #   while ( $z<$count ) {
1590 #   my $rec;
1591 #           $rec=$oResult->record($z);
1592 #       my $marcdata = $rec->raw();
1593 #   push @reccache, $marcdata;
1594 #   $z++;
1595 #   }
1596 #   $oResult->destroy();
1597 #   foreach my $marc(@reccache){
1598 #     my $update;
1599 #     my $marcrecord;
1600 #     $marcrecord = MARC::File::USMARC::decode($marc);
1601 #     foreach my $tagfield (@tags_using_authtype){
1602 #       $tagfield=substr($tagfield,0,3);
1603 #       my @tags = $marcrecord->field($tagfield);
1604 #       foreach my $tag (@tags){
1605 #         my $tagsubs=$tag->subfield("9");
1606 #     #warn "$tagfield:$tagsubs:$mergefrom";
1607 #         if ($tagsubs== $mergefrom) {
1608 #           $tag->update("9" =>$mergeto);
1609 #           foreach my $subfield (@record_to) {
1610 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1611 #             $tag->update($subfield->[0] =>$subfield->[1]);
1612 #           }#for $subfield
1613 #         }
1614 #         $marcrecord->delete_field($tag);
1615 #         $marcrecord->add_fields($tag);
1616 #         $update=1;
1617 #       }#for each tag
1618 #     }#foreach tagfield
1619 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1620 #     if ($update==1){
1621 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1622 #     }
1623
1624 #   }#foreach $marc
1625 }#sub
1626
1627 =head2 get_auth_type_location
1628
1629   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1630
1631 Get the tag and subfield used to store the heading type
1632 for indexing purposes.  The C<$auth_type> parameter is
1633 optional; if it is not supplied, assume ''.
1634
1635 This routine searches the MARC authority framework
1636 for the tag and subfield whose kohafield is 
1637 C<auth_header.authtypecode>; if no such field is
1638 defined in the framework, default to the hardcoded value
1639 specific to the MARC format.
1640
1641 =cut
1642
1643 sub get_auth_type_location {
1644     my $auth_type_code = @_ ? shift : '';
1645
1646     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1647     if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') {
1648         return ($tag, $subfield);
1649     } else {
1650         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1651             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1652         } else {
1653             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1654         }
1655     }
1656 }
1657
1658 END { }       # module clean-up code here (global destructor)
1659
1660 1;
1661 __END__
1662
1663 =head1 AUTHOR
1664
1665 Koha Development Team <http://koha-community.org/>
1666
1667 Paul POULAIN paul.poulain@free.fr
1668
1669 =cut
1670