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