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