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