replace references to defunct info email address
[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         if ($format eq "MARC21") {
614                 if (!$record->leader) {
615                         $record->leader($leader);
616                 }
617                 if (!$record->field('003')) {
618                         $record->insert_fields_ordered(
619                                 MARC::Field->new('003',C4::Context->preference('MARCOrgCode'))
620                         );
621                 }
622                 my $time=POSIX::strftime("%Y%m%d%H%M%S",localtime);
623                 if (!$record->field('005')) {
624                         $record->insert_fields_ordered(
625                                 MARC::Field->new('005',$time.".0")
626                         );
627                 }
628                 my $date=POSIX::strftime("%y%m%d",localtime);
629                 if (!$record->field('008')) {
630                         $record->insert_fields_ordered(
631                                 MARC::Field->new('008',$date."|||a||||||           | |||     d")
632                         );
633                 }
634                 if (!$record->field('040')) {
635                  $record->insert_fields_ordered(
636         MARC::Field->new('040','','',
637                                 'a' => C4::Context->preference('MARCOrgCode'),
638                                 'c' => C4::Context->preference('MARCOrgCode')
639                                 ) 
640                         );
641     }
642         }
643
644   if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
645         $record->leader("     nx  j22             ");
646         my $date=POSIX::strftime("%Y%m%d",localtime);    
647         if ($record->field('100')){
648           $record->field('100')->update('a'=>$date."afrey50      ba0");
649         } else {      
650           $record->append_fields(
651             MARC::Field->new('100',' ',' '
652               ,'a'=>$date."afrey50      ba0")
653           );
654         }      
655   }
656   my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
657   if (!$authid and $format eq "MARC21") {
658     # only need to do this fix when modifying an existing authority
659     C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
660   } 
661   if (my $field=$record->field($auth_type_tag)){
662     $field->update($auth_type_subfield=>$authtypecode);
663   }
664   else {
665     $record->add_fields($auth_type_tag,'','', $auth_type_subfield=>$authtypecode); 
666   }
667
668   my $auth_exists=0;
669   my $oldRecord;
670   if (!$authid) {
671     my $sth=$dbh->prepare("select max(authid) from auth_header");
672     $sth->execute;
673     ($authid)=$sth->fetchrow;
674     $authid=$authid+1;
675   ##Insert the recordID in MARC record 
676     unless ($record->field('001') && $record->field('001')->data() eq $authid){
677         $record->delete_field($record->field('001'));
678         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
679     }
680   } else {
681     $auth_exists=$dbh->do(qq(select authid from auth_header where authid=?),undef,$authid);
682 #     warn "auth_exists = $auth_exists";
683   }
684   if ($auth_exists>0){
685       $oldRecord=GetAuthority($authid);
686       $record->add_fields('001',$authid) unless ($record->field('001'));
687 #       warn "\n\n\n enregistrement".$record->as_formatted;
688       my $sth=$dbh->prepare("update auth_header set authtypecode=?,marc=?,marcxml=? where authid=?");
689       $sth->execute($authtypecode,$record->as_usmarc,$record->as_xml_record($format),$authid) or die $sth->errstr;
690       $sth->finish;
691   }
692   else {
693     my $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
694     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
695     $sth->finish;
696   }
697   ModZebra($authid,'specialUpdate',"authorityserver",$oldRecord,$record);
698   return ($authid);
699 }
700
701
702 =head2 DelAuthority
703
704   $authid= &DelAuthority($authid)
705
706 Deletes $authid
707
708 =cut
709
710 sub DelAuthority {
711     my ($authid) = @_;
712     my $dbh=C4::Context->dbh;
713
714     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid),undef);
715     $dbh->do("delete from auth_header where authid=$authid") ;
716
717 }
718
719 sub ModAuthority {
720   my ($authid,$record,$authtypecode,$merge)=@_;
721   my $dbh=C4::Context->dbh;
722   #Now rewrite the $record to table with an add
723   my $oldrecord=GetAuthority($authid);
724   $authid=AddAuthority($record,$authid,$authtypecode);
725
726 ### 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
727 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
728 ### the $merge flag is now depreceated and will be removed at code cleaning
729   if (C4::Context->preference('MergeAuthoritiesOnUpdate') ){
730       &merge($authid,$oldrecord,$authid,$record);
731   } else {
732   # save the file in tmp/modified_authorities
733       my $cgidir = C4::Context->intranetdir ."/cgi-bin";
734       unless (opendir(DIR,"$cgidir")) {
735               $cgidir = C4::Context->intranetdir."/";
736               closedir(DIR);
737       }
738   
739       my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
740       open AUTH, "> $filename";
741       print AUTH $authid;
742       close AUTH;
743   }
744   return $authid;
745 }
746
747 =head2 GetAuthorityXML 
748
749   $marcxml= &GetAuthorityXML( $authid)
750
751 returns xml form of record $authid
752
753 =cut
754
755 sub GetAuthorityXML {
756   # Returns MARC::XML of the authority passed in parameter.
757   my ( $authid ) = @_;
758   if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') {
759       my $dbh=C4::Context->dbh;
760       my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "  );
761       $sth->execute($authid);
762       my ($marcxml)=$sth->fetchrow;
763       return $marcxml;
764   }
765   else { 
766       # for MARC21, call GetAuthority instead of
767       # getting the XML directly since we may
768       # need to fix up the location of the authority
769       # code -- note that this is reasonably safe
770       # because GetAuthorityXML is used only by the 
771       # indexing processes like zebraqueue_start.pl
772       my $record = GetAuthority($authid);
773       return $record->as_xml_record('MARC21');
774   }
775 }
776
777 =head2 GetAuthority 
778
779   $record= &GetAuthority( $authid)
780
781 Returns MARC::Record of the authority passed in parameter.
782
783 =cut
784
785 sub GetAuthority {
786     my ($authid)=@_;
787     my $dbh=C4::Context->dbh;
788     my $sth=$dbh->prepare("select authtypecode, marcxml from auth_header where authid=?");
789     $sth->execute($authid);
790     my ($authtypecode, $marcxml) = $sth->fetchrow;
791     my $record=eval {MARC::Record->new_from_xml(StripNonXmlChars($marcxml),'UTF-8',
792         (C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")))};
793     return undef if ($@);
794     $record->encoding('UTF-8');
795     if (C4::Context->preference("marcflavour") eq "MARC21") {
796       my ($auth_type_tag, $auth_type_subfield) = get_auth_type_location($authtypecode);
797       C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($record, $auth_type_tag, $auth_type_subfield);
798     }
799     return ($record);
800 }
801
802 =head2 GetAuthType 
803
804   $result = &GetAuthType($authtypecode)
805
806 If the authority type specified by C<$authtypecode> exists,
807 returns a hashref of the type's fields.  If the type
808 does not exist, returns undef.
809
810 =cut
811
812 sub GetAuthType {
813     my ($authtypecode) = @_;
814     my $dbh=C4::Context->dbh;
815     my $sth;
816     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
817                                 # type (FIXME but why?)
818         $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
819         $sth->execute($authtypecode);
820         if (my $res = $sth->fetchrow_hashref) {
821             return $res; 
822         }
823     }
824     return;
825 }
826
827
828 sub AUTHhtml2marc {
829     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
830     my $dbh=C4::Context->dbh;
831     my $prevtag = -1;
832     my $record = MARC::Record->new();
833 #---- TODO : the leader is missing
834
835 #     my %subfieldlist=();
836     my $prevvalue; # if tag <10
837     my $field; # if tag >=10
838     for (my $i=0; $i< @$rtags; $i++) {
839         # rebuild MARC::Record
840         if (@$rtags[$i] ne $prevtag) {
841             if ($prevtag < 10) {
842                 if ($prevvalue) {
843                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
844                 }
845             } else {
846                 if ($field) {
847                     $record->add_fields($field);
848                 }
849             }
850             $indicators{@$rtags[$i]}.='  ';
851             if (@$rtags[$i] <10) {
852                 $prevvalue= @$rvalues[$i];
853                 undef $field;
854             } else {
855                 undef $prevvalue;
856                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
857             }
858             $prevtag = @$rtags[$i];
859         } else {
860             if (@$rtags[$i] <10) {
861                 $prevvalue=@$rvalues[$i];
862             } else {
863                 if (length(@$rvalues[$i])>0) {
864                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
865                 }
866             }
867             $prevtag= @$rtags[$i];
868         }
869     }
870     # the last has not been included inside the loop... do it now !
871     $record->add_fields($field) if $field;
872     return $record;
873 }
874
875 =head2 FindDuplicateAuthority
876
877   $record= &FindDuplicateAuthority( $record, $authtypecode)
878
879 return $authid,Summary if duplicate is found.
880
881 Comments : an improvement would be to return All the records that match.
882
883 =cut
884
885 sub FindDuplicateAuthority {
886
887     my ($record,$authtypecode)=@_;
888 #    warn "IN for ".$record->as_formatted;
889     my $dbh = C4::Context->dbh;
890 #    warn "".$record->as_formatted;
891     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
892     $sth->execute($authtypecode);
893     my ($auth_tag_to_report) = $sth->fetchrow;
894     $sth->finish;
895 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
896     # build a request for SearchAuthorities
897     my $query='at='.$authtypecode.' ';
898     my $filtervalues=qr([\001-\040\!\'\"\`\#\$\%\&\*\+,\-\./:;<=>\?\@\(\)\{\[\]\}_\|\~]);
899     if ($record->field($auth_tag_to_report)) {
900       foreach ($record->field($auth_tag_to_report)->subfields()) {
901         $_->[1]=~s/$filtervalues/ /g; $query.= " and he,wrdl=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/);
902       }
903     }
904     my ($error, $results, $total_hits)=SimpleSearch( $query, 0, 1, [ "authorityserver" ] );
905     # there is at least 1 result => return the 1st one
906     if (@$results>0) {
907       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
908       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
909     }
910     # no result, returns nothing
911     return;
912 }
913
914 =head2 BuildSummary
915
916   $text= &BuildSummary( $record, $authid, $authtypecode)
917
918 return HTML encoded Summary
919
920 Comment : authtypecode can be infered from both record and authid.
921 Moreover, authid can also be inferred from $record.
922 Would it be interesting to delete those things.
923
924 =cut
925
926 sub BuildSummary{
927 ## give this a Marc record to return summary
928   my ($record,$authid,$authtypecode)=@_;
929   my $dbh=C4::Context->dbh;
930   my $summary;
931   # handle $authtypecode is NULL or eq ""
932   if ($authtypecode) {
933         my $authref = GetAuthType($authtypecode);
934         $summary = $authref->{summary};
935   }
936   # FIXME: should use I18N.pm
937   my %language;
938   $language{'fre'}="Français";
939   $language{'eng'}="Anglais";
940   $language{'ger'}="Allemand";
941   $language{'ita'}="Italien";
942   $language{'spa'}="Espagnol";
943   my %thesaurus;
944   $thesaurus{'1'}="Peuples";
945   $thesaurus{'2'}="Anthroponymes";
946   $thesaurus{'3'}="Oeuvres";
947   $thesaurus{'4'}="Chronologie";
948   $thesaurus{'5'}="Lieux";
949   $thesaurus{'6'}="Sujets";
950   #thesaurus a remplir
951   my @fields = $record->fields();
952   my $reported_tag;
953   # if the library has a summary defined, use it. Otherwise, build a standard one
954   # FIXME - it appears that the summary field in the authority frameworks
955   #         can work as a display template.  However, this doesn't
956   #         suit the MARC21 version, so for now the "templating"
957   #         feature will be enabled only for UNIMARC for backwards
958   #         compatibility.
959   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
960     my @fields = $record->fields();
961     #             $reported_tag = '$9'.$result[$counter];
962         my @stringssummary;
963     foreach my $field (@fields) {
964       my $tag = $field->tag();
965       my $tagvalue = $field->as_string();
966       my $localsummary= $summary;
967           $localsummary =~ s/\[(.?.?.?.?)$tag\*(.*?)\]/$1$tagvalue$2\[$1$tag$2\]/g;
968       if ($tag<10) {
969         if ($tag eq '001') {
970           $reported_tag.='$3'.$field->data();
971         }
972       } else {
973         my @subf = $field->subfields;
974         for my $i (0..$#subf) {
975           my $subfieldcode = $subf[$i][0];
976           my $subfieldvalue = $subf[$i][1];
977           my $tagsubf = $tag.$subfieldcode;
978           $localsummary =~ s/\[(.?.?.?.?)$tagsubf(.*?)\]/$1$subfieldvalue$2\[$1$tagsubf$2\]/g;
979         }
980       }
981           push @stringssummary, $localsummary if ($localsummary ne $summary);
982     }
983         my $resultstring;
984         $resultstring = join(" -- ",@stringssummary);
985     $resultstring =~ s/\[(.*?)\]//g;
986     $resultstring =~ s/\n/<br>/g;
987         $summary      =  $resultstring;
988   } else {
989     my $heading; 
990     my $altheading;
991     my $seealso;
992     my $broaderterms;
993     my $narrowerterms;
994     my $see;
995     my $seeheading;
996         my $notes;
997     my @fields = $record->fields();
998     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
999     # construct UNIMARC summary, that is quite different from MARC21 one
1000       # accepted form
1001       foreach my $field ($record->field('2..')) {
1002         $heading.= $field->as_string('abcdefghijlmnopqrstuvwxyz');
1003       }
1004       # rejected form(s)
1005       foreach my $field ($record->field('3..')) {
1006         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
1007       }
1008       foreach my $field ($record->field('4..')) {
1009         if ($field->subfield('2')) {
1010             my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : ";
1011             $see.= '<span class="UF">'.$thesaurus.$field->as_string('abcdefghijlmnopqrstuvwxyz')."</span> -- \n";
1012         }
1013       }
1014       # see :
1015       foreach my $field ($record->field('5..')) {
1016             
1017         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
1018           $broaderterms.= '<span class="BT"> '.$field->as_string('abcdefgjxyz')."</span> -- \n";
1019         } elsif (($field->subfield('5')) && ($field->as_string) && ($field->subfield('5') eq 'h')){
1020           $narrowerterms.= '<span class="NT">'.$field->as_string('abcdefgjxyz')."</span> -- \n";
1021         } elsif ($field->subfield('a')) {
1022           $seealso.= '<span class="RT">'.$field->as_string('abcdefgxyz')."</a></span> -- \n";
1023         }
1024       }
1025       # // form
1026       foreach my $field ($record->field('7..')) {
1027         my $lang = substr($field->subfield('8'),3,3);
1028         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
1029       }
1030             $broaderterms =~s/-- \n$//;
1031             $narrowerterms =~s/-- \n$//;
1032             $seealso =~s/-- \n$//;
1033             $see =~s/-- \n$//;
1034       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
1035       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
1036       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
1037       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
1038       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
1039       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
1040       } else {
1041       # construct MARC21 summary
1042           # FIXME - looping over 1XX is questionable
1043           # since MARC21 authority should have only one 1XX
1044           foreach my $field ($record->field('1..')) {
1045               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
1046                                               # in MARC21 -- purely local tags really ought to be
1047                                               # 9XX
1048               if ($record->field('100')) {
1049                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
1050               } elsif ($record->field('110')) {
1051                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
1052               } elsif ($record->field('111')) {
1053                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
1054               } elsif ($record->field('130')) {
1055                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
1056               } elsif ($record->field('148')) {
1057                                       $heading.= $field->as_string('abvxyz68');
1058               } elsif ($record->field('150')) {
1059           #    $heading.= $field->as_string('abvxyz68');
1060           $heading.= $field->as_formatted();
1061               my $tag=$field->tag();
1062               $heading=~s /^$tag//g;
1063               $heading =~s /\_/\$/g;
1064               } elsif ($record->field('151')) {
1065                                       $heading.= $field->as_string('avxyz68');
1066               } elsif ($record->field('155')) {
1067                                       $heading.= $field->as_string('abvxyz68');
1068               } elsif ($record->field('180')) {
1069                                       $heading.= $field->as_string('vxyz68');
1070               } elsif ($record->field('181')) {
1071                                       $heading.= $field->as_string('vxyz68');
1072               } elsif ($record->field('182')) {
1073                                       $heading.= $field->as_string('vxyz68');
1074               } elsif ($record->field('185')) {
1075                                       $heading.= $field->as_string('vxyz68');
1076               } else {
1077                   $heading.= $field->as_string();
1078               }
1079           } #See From
1080           foreach my $field ($record->field('4..')) {
1081               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
1082           } #See Also
1083           foreach my $field ($record->field('5..')) {
1084               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
1085           }
1086           $summary .= ": " if $summary;
1087           $summary.=$heading.$seeheading.$altheading;
1088       }
1089   }
1090   return $summary;
1091 }
1092
1093 =head2 BuildUnimarcHierarchies
1094
1095   $text= &BuildUnimarcHierarchies( $authid, $force)
1096
1097 return text containing trees for hierarchies
1098 for them to be stored in auth_header
1099
1100 Example of text:
1101 122,1314,2452;1324,2342,3,2452
1102
1103 =cut
1104
1105 sub BuildUnimarcHierarchies{
1106   my $authid = shift @_;
1107 #   warn "authid : $authid";
1108   my $force = shift @_;
1109   my @globalresult;
1110   my $dbh=C4::Context->dbh;
1111   my $hierarchies;
1112   my $data = GetHeaderAuthority($authid);
1113   if ($data->{'authtrees'} and not $force){
1114     return $data->{'authtrees'};
1115   } elsif ($data->{'authtrees'}){
1116     $hierarchies=$data->{'authtrees'};
1117   } else {
1118     my $record = GetAuthority($authid);
1119     my $found;
1120         if ($record){
1121                 foreach my $field ($record->field('550')){
1122                   if ($field->subfield('5') && $field->subfield('5') eq 'g'){
1123                         my $parentrecord = GetAuthority($field->subfield('3'));
1124                         my $localresult=$hierarchies;
1125                         my $trees;
1126                         $trees = BuildUnimarcHierarchies($field->subfield('3'));
1127                         my @trees;
1128                         if ($trees=~/;/){
1129                            @trees = split(/;/,$trees);
1130                         } else {
1131                            push @trees, $trees;
1132                         }
1133                         foreach (@trees){
1134                           $_.= ",$authid";
1135                         }
1136                         @globalresult = (@globalresult,@trees);
1137                         $found=1;
1138                   }
1139                   $hierarchies=join(";",@globalresult);
1140                 }
1141         }
1142     #Unless there is no ancestor, I am alone.
1143     $hierarchies="$authid" unless ($hierarchies);
1144   }
1145   AddAuthorityTrees($authid,$hierarchies);
1146   return $hierarchies;
1147 }
1148
1149 =head2 BuildUnimarcHierarchy
1150
1151   $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1152
1153 return a hashref in order to display hierarchy for record and final Authid $authid
1154
1155 "loopparents"
1156 "loopchildren"
1157 "class"
1158 "loopauthid"
1159 "current_value"
1160 "value"
1161
1162 "ifparents"  
1163 "ifchildren" 
1164 Those two latest ones should disappear soon.
1165
1166 =cut
1167
1168 sub BuildUnimarcHierarchy{
1169   my $record = shift @_;
1170   my $class = shift @_;
1171   my $authid_constructed = shift @_;
1172   return undef unless ($record);
1173   my $authid=$record->subfield('2..','3');
1174   my %cell;
1175   my $parents=""; my $children="";
1176   my (@loopparents,@loopchildren);
1177   foreach my $field ($record->field('550')){
1178     if ($field->subfield('5') && $field->subfield('a')){
1179       if ($field->subfield('5') eq 'h'){
1180         push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1181       }elsif ($field->subfield('5') eq 'g'){
1182         push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1183       }
1184           # brothers could get in there with an else
1185     }
1186   }
1187   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1188   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1189   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1190   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1191   $cell{"class"}=$class;
1192   $cell{"loopauthid"}=$authid;
1193   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1194   $cell{"value"}=$record->subfield('2..',"a");
1195   return \%cell;
1196 }
1197
1198 =head2 GetHeaderAuthority
1199
1200   $ref= &GetHeaderAuthority( $authid)
1201
1202 return a hashref in order auth_header table data
1203
1204 =cut
1205
1206 sub GetHeaderAuthority{
1207   my $authid = shift @_;
1208   my $sql= "SELECT * from auth_header WHERE authid = ?";
1209   my $dbh=C4::Context->dbh;
1210   my $rq= $dbh->prepare($sql);
1211   $rq->execute($authid);
1212   my $data= $rq->fetchrow_hashref;
1213   return $data;
1214 }
1215
1216 =head2 AddAuthorityTrees
1217
1218   $ref= &AddAuthorityTrees( $authid, $trees)
1219
1220 return success or failure
1221
1222 =cut
1223
1224 sub AddAuthorityTrees{
1225   my $authid = shift @_;
1226   my $trees = shift @_;
1227   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1228   my $dbh=C4::Context->dbh;
1229   my $rq= $dbh->prepare($sql);
1230   return $rq->execute($trees,$authid);
1231 }
1232
1233 =head2 merge
1234
1235   $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1236
1237 Could add some feature : Migrating from a typecode to an other for instance.
1238 Then we should add some new parameter : bibliotargettag, authtargettag
1239
1240 =cut
1241
1242 sub merge {
1243     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1244     my ($counteditedbiblio,$countunmodifiedbiblio,$counterrors)=(0,0,0);        
1245     my $dbh=C4::Context->dbh;
1246     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1247     my $authtypecodeto = GetAuthTypeCode($mergeto);
1248 #     warn "mergefrom : $authtypecodefrom $mergefrom mergeto : $authtypecodeto $mergeto ";
1249     # return if authority does not exist
1250     return "error MARCFROM not a marcrecord ".Data::Dumper::Dumper($MARCfrom) if scalar($MARCfrom->fields()) == 0;
1251     return "error MARCTO not a marcrecord".Data::Dumper::Dumper($MARCto) if scalar($MARCto->fields()) == 0;
1252     # search the tag to report
1253     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1254     $sth->execute($authtypecodefrom);
1255     my ($auth_tag_to_report_from) = $sth->fetchrow;
1256     $sth->execute($authtypecodeto);
1257     my ($auth_tag_to_report_to) = $sth->fetchrow;
1258     
1259     my @record_to;
1260     @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $MARCto->field($auth_tag_to_report_to);
1261     my @record_from;
1262     @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields() if $MARCfrom->field($auth_tag_to_report_from);
1263     
1264     my @reccache;
1265     # search all biblio tags using this authority.
1266     #Getting marcbiblios impacted by the change.
1267     if (C4::Context->preference('NoZebra')) {
1268         #nozebra way    
1269         my $dbh=C4::Context->dbh;
1270         my $rq=$dbh->prepare(qq(SELECT biblionumbers from nozebra where indexname="an" and server="biblioserver" and value="$mergefrom" ));
1271         $rq->execute;
1272         while (my $biblionumbers=$rq->fetchrow){
1273             my @biblionumbers=split /;/,$biblionumbers;
1274             foreach (@biblionumbers) {
1275                 if ($_=~/(\d+),.*/) {
1276                     my $marc=GetMarcBiblio($1);
1277                     push @reccache,$marc;
1278                 }
1279             }
1280         }
1281     } else {
1282         #zebra connection  
1283         my $oConnection=C4::Context->Zconn("biblioserver",0);
1284         $oConnection->option("preferredRecordSyntax"=>"XML");
1285         my $query;
1286         $query= "an=".$mergefrom;
1287         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1288         my $count = 0;
1289         if  ($oResult) {
1290             $count=$oResult->size();
1291         }
1292         my $z=0;
1293         while ( $z<$count ) {
1294             my $rec;
1295             $rec=$oResult->record($z);
1296             my $marcdata = $rec->raw();
1297             push @reccache, $marcdata;
1298             $z++;
1299         }
1300         $oConnection->destroy();    
1301     }
1302     #warn scalar(@reccache)." biblios to update";
1303     # Get All candidate Tags for the change 
1304     # (This will reduce the search scope in marc records).
1305     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1306     $sth->execute($authtypecodefrom);
1307     my @tags_using_authtype;
1308     while (my ($tagfield) = $sth->fetchrow) {
1309         push @tags_using_authtype,$tagfield ;
1310     }
1311     my $tag_to=0;  
1312     if ($authtypecodeto ne $authtypecodefrom){  
1313         # If many tags, take the first
1314         $sth->execute($authtypecodeto);    
1315         $tag_to=$sth->fetchrow;
1316         #warn $tag_to;    
1317     }  
1318     # BulkEdit marc records
1319     # May be used as a template for a bulkedit field  
1320     foreach my $marcrecord(@reccache){
1321         my $update;           
1322         $marcrecord= MARC::Record->new_from_xml($marcrecord,"utf8",C4::Context->preference("marcflavour")) unless(C4::Context->preference('NoZebra'));
1323         foreach my $tagfield (@tags_using_authtype){
1324 #             warn "tagfield : $tagfield ";
1325             foreach my $field ($marcrecord->field($tagfield)){
1326                 my $auth_number=$field->subfield("9");
1327                 my $tag=$field->tag();          
1328                 if ($auth_number==$mergefrom) {
1329                 my $field_to=MARC::Field->new(($tag_to?$tag_to:$tag),$field->indicator(1),$field->indicator(2),"9"=>$mergeto);
1330                 foreach my $subfield (@record_to) {
1331                     $field_to->add_subfields($subfield->[0] =>$subfield->[1]);
1332                 }
1333                 $marcrecord->delete_field($field);
1334                 $marcrecord->insert_grouped_field($field_to);            
1335                 $update=1;
1336                 }
1337             }#for each tag
1338         }#foreach tagfield
1339         my ($bibliotag,$bibliosubf) = GetMarcFromKohaField("biblio.biblionumber","") ;
1340         my $biblionumber;
1341         if ($bibliotag<10){
1342             $biblionumber=$marcrecord->field($bibliotag)->data;
1343         }
1344         else {
1345             $biblionumber=$marcrecord->subfield($bibliotag,$bibliosubf);
1346         }
1347         unless ($biblionumber){
1348             warn "pas de numéro de notice bibliographique dans : ".$marcrecord->as_formatted;
1349             next;
1350         }
1351         if ($update==1){
1352             &ModBiblio($marcrecord,$biblionumber,GetFrameworkCode($biblionumber)) ;
1353             $counteditedbiblio++;
1354             warn $counteditedbiblio if (($counteditedbiblio % 10) and $ENV{DEBUG});
1355         }    
1356     }#foreach $marc
1357     return $counteditedbiblio;  
1358   # now, find every other authority linked with this authority
1359   # now, find every other authority linked with this authority
1360 #   my $oConnection=C4::Context->Zconn("authorityserver");
1361 #   my $query;
1362 # # att 9210               Auth-Internal-authtype
1363 # # att 9220               Auth-Internal-LN
1364 # # ccl.properties to add for authorities
1365 #   $query= "= ".$mergefrom;
1366 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1367 #   my $count=$oResult->size() if  ($oResult);
1368 #   my @reccache;
1369 #   my $z=0;
1370 #   while ( $z<$count ) {
1371 #   my $rec;
1372 #           $rec=$oResult->record($z);
1373 #       my $marcdata = $rec->raw();
1374 #   push @reccache, $marcdata;
1375 #   $z++;
1376 #   }
1377 #   $oResult->destroy();
1378 #   foreach my $marc(@reccache){
1379 #     my $update;
1380 #     my $marcrecord;
1381 #     $marcrecord = MARC::File::USMARC::decode($marc);
1382 #     foreach my $tagfield (@tags_using_authtype){
1383 #       $tagfield=substr($tagfield,0,3);
1384 #       my @tags = $marcrecord->field($tagfield);
1385 #       foreach my $tag (@tags){
1386 #         my $tagsubs=$tag->subfield("9");
1387 #     #warn "$tagfield:$tagsubs:$mergefrom";
1388 #         if ($tagsubs== $mergefrom) {
1389 #           $tag->update("9" =>$mergeto);
1390 #           foreach my $subfield (@record_to) {
1391 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1392 #             $tag->update($subfield->[0] =>$subfield->[1]);
1393 #           }#for $subfield
1394 #         }
1395 #         $marcrecord->delete_field($tag);
1396 #         $marcrecord->add_fields($tag);
1397 #         $update=1;
1398 #       }#for each tag
1399 #     }#foreach tagfield
1400 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1401 #     if ($update==1){
1402 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1403 #     }
1404
1405 #   }#foreach $marc
1406 }#sub
1407
1408 =head2 get_auth_type_location
1409
1410   my ($tag, $subfield) = get_auth_type_location($auth_type_code);
1411
1412 Get the tag and subfield used to store the heading type
1413 for indexing purposes.  The C<$auth_type> parameter is
1414 optional; if it is not supplied, assume ''.
1415
1416 This routine searches the MARC authority framework
1417 for the tag and subfield whose kohafield is 
1418 C<auth_header.authtypecode>; if no such field is
1419 defined in the framework, default to the hardcoded value
1420 specific to the MARC format.
1421
1422 =cut
1423
1424 sub get_auth_type_location {
1425     my $auth_type_code = @_ ? shift : '';
1426
1427     my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code);
1428     if (defined $tag and defined $subfield and $tag != 0 and $subfield != 0) {
1429         return ($tag, $subfield);
1430     } else {
1431         if (C4::Context->preference('marcflavour') eq "MARC21")  {
1432             return C4::AuthoritiesMarc::MARC21::default_auth_type_location();
1433         } else {
1434             return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location();
1435         }
1436     }
1437 }
1438
1439 END { }       # module clean-up code here (global destructor)
1440
1441 1;
1442 __END__
1443
1444 =head1 AUTHOR
1445
1446 Koha Development Team <http://koha-community.org/>
1447
1448 Paul POULAIN paul.poulain@free.fr
1449
1450 =cut
1451