WARNING: Updates to Index Defs for Authorities
[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 require Exporter;
21 use C4::Context;
22 use C4::Koha;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26
27 use vars qw($VERSION @ISA @EXPORT);
28
29 # set the version for version checking
30 $VERSION = 3.00;
31
32 @ISA = qw(Exporter);
33 @EXPORT = qw(
34     &GetTagsLabels
35     &GetAuthType
36     &GetAuthTypeCode
37     &GetAuthMARCFromKohaField 
38     &AUTHhtml2marc
39
40     &AddAuthority
41     &ModAuthority
42     &DelAuthority
43     &GetAuthority
44     &GetAuthorityXML
45     
46     &CountUsage
47     &CountUsageChildren
48     &SearchAuthorities
49     
50     &BuildSummary
51     &BuildUnimarcHierarchies
52     &BuildUnimarcHierarchy
53     
54     &merge
55     &FindDuplicateAuthority
56  );
57
58 =head2 GetAuthMARCFromKohaField 
59
60 =over 4
61
62 ( $tag, $subfield ) = &GetAuthMARCFromKohaField ($kohafield,$authtypecode);
63 returns tag and subfield linked to kohafield
64
65 Comment :
66 Suppose Kohafield is only linked to ONE subfield
67 =back
68
69 =cut
70 sub GetAuthMARCFromKohaField {
71 #AUTHfind_marc_from_kohafield
72   my ( $kohafield,$authtypecode ) = @_;
73   my $dbh=C4::Context->dbh;
74   return 0, 0 unless $kohafield;
75   $authtypecode="" unless $authtypecode;
76   my $marcfromkohafield;
77   my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
78   $sth->execute($kohafield,$authtypecode);
79   my ($tagfield,$tagsubfield) = $sth->fetchrow;
80     
81   return  ($tagfield,$tagsubfield);
82 }
83
84 =head2 SearchAuthorities 
85
86 =over 4
87
88 (\@finalresult, $nbresults)= &SearchAuthorities($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby)
89 returns ref to array result and count of results returned
90
91 =back
92
93 =cut
94 sub SearchAuthorities {
95     my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
96 #     warn "CALL : $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby";
97     my $dbh=C4::Context->dbh;
98     if (C4::Context->preference('NoZebra')) {
99     
100         #
101         # build the query
102         #
103         my $query;
104         my @auths=split / /,$authtypecode ;
105         foreach my  $auth (@auths){
106             $query .="AND auth_type= $auth ";
107         }
108         $query =~ s/^AND //;
109         my $dosearch;
110         for(my $i = 0 ; $i <= $#{$value} ; $i++)
111         {
112             if (@$value[$i]){
113                 if (@$tags[$i] eq "mainmainentry") {
114                     $query .=" AND mainmainentry";
115                 }elsif (@$tags[$i] eq "mainentry") {
116                     $query .=" AND mainentry";
117                 } else {
118                     $query .=" AND ";
119                 }
120                 if (@$operator[$i] eq 'is') {
121                     $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
122                 }elsif (@$operator[$i] eq "="){
123                     $query.=(@$tags[$i]?"=":""). '"'.@$value[$i].'"';
124                 }elsif (@$operator[$i] eq "start"){
125                     $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
126                 } else {
127                     $query.=(@$tags[$i]?"=":"").'"'.@$value[$i].'%"';
128                 }
129                 $dosearch=1;
130             }#if value
131         }
132         #
133         # do the query (if we had some search term
134         #
135         if ($dosearch) {
136 #             warn "QUERY : $query";
137             my $result = C4::Search::NZanalyse($query,'authorityserver');
138 #             warn "result : $result";
139             my %result;
140             foreach (split /;/,$result) {
141                 my ($authid,$title) = split /,/,$_;
142                 # hint : the result is sorted by title.biblionumber because we can have X biblios with the same title
143                 # and we don't want to get only 1 result for each of them !!!
144                 # hint & speed improvement : we can order without reading the record
145                 # so order, and read records only for the requested page !
146                 $result{$title.$authid}=$authid;
147             }
148             # sort the hash and return the same structure as GetRecords (Zebra querying)
149             my @listresult = ();
150             my $numbers=0;
151             if ($sortby eq 'HeadingDsc') { # sort by mainmainentry desc
152                 foreach my $key (sort {$b cmp $a} (keys %result)) {
153                     push @listresult, $result{$key};
154 #                     warn "push..."$#finalresult;
155                     $numbers++;
156                 }
157             } else { # sort by mainmainentry ASC
158                 foreach my $key (sort (keys %result)) {
159                     push @listresult, $result{$key};
160 #                     warn "push..."$#finalresult;
161                     $numbers++;
162                 }
163             }
164             # limit the $results_per_page to result size if it's more
165             $length = $numbers-$offset if $numbers < ($offset+$length);
166             # for the requested page, replace authid by the complete record
167             # speed improvement : avoid reading too much things
168             my @finalresult;      
169             for (my $counter=$offset;$counter<=$offset+$length-1;$counter++) {
170 #                 $finalresult[$counter] = GetAuthority($finalresult[$counter])->as_usmarc;
171                 my $separator=C4::Context->preference('authoritysep');
172                 my $authrecord =GetAuthority($listresult[$counter]);
173                 my $authid=$listresult[$counter]; 
174                 my $summary=BuildSummary($authrecord,$authid,$authtypecode);
175                 my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
176                 my $sth = $dbh->prepare($query_auth_tag);
177                 $sth->execute($authtypecode);
178                 my $auth_tag_to_report = $sth->fetchrow;
179                 my %newline;
180                 $newline{used}=CountUsage($authid);
181                 $newline{summary} = $summary;
182                 $newline{authid} = $authid;
183                 $newline{even} = $counter % 2;
184                 push @finalresult, \%newline;
185             }
186             return (\@finalresult, $numbers);
187         } else {
188             return;
189         }
190     } else {
191         my $query;
192         my $attr;
193             # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
194             # the authtypecode. Then, search on $a of this tag_to_report
195             # also store main entry MARC tag, to extract it at end of search
196         my $mainentrytag;
197         ##first set the authtype search and may be multiple authorities
198         my $n=0;
199         my @authtypecode;
200         my @auths=split / /,$authtypecode ;
201         foreach my  $auth (@auths){
202             $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype
203             push @authtypecode ,$auth;
204             $n++;
205         }
206         if ($n>1){
207             while ($n>1){$query= "\@or ".$query;$n--;}
208         }
209         
210         my $dosearch;
211         my $and;
212         my $q2;
213         for(my $i = 0 ; $i <= $#{$value} ; $i++)
214         {
215             if (@$value[$i]){
216             ##If mainentry search $a tag
217                 if (@$tags[$i] eq "mainmainentry") {
218                 $attr =" \@attr 1=Heading ";
219                 }elsif (@$tags[$i] eq "mainentry") {
220                 $attr =" \@attr 1=Heading ";
221                 }else{
222                 $attr =" \@attr 1=Any ";
223                 }
224                 if (@$operator[$i] eq 'is') {
225                     $attr.=" \@attr 4=1  \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
226                 }elsif (@$operator[$i] eq "="){
227                     $attr.=" \@attr 4=107 ";           #Number Exact match
228                 }elsif (@$operator[$i] eq "start"){
229                     $attr.=" \@attr 4=1 \@attr 5=1 ";#Phrase, Right truncated
230                 } else {
231                     $attr .=" \@attr 5=1 \@attr 4=6 ";## Word list, right truncated, anywhere
232                 }
233                 $and .=" \@and " ;
234                 $attr =$attr."\"".@$value[$i]."\"";
235                 $q2 .=$attr;
236             $dosearch=1;
237             }#if value
238         }
239         ##Add how many queries generated
240         if ($query=~/\S+/){    
241           $query= $and.$query.$q2 
242         } else {
243           $query=$q2;    
244         }         
245         ## Adding order
246         #$query=' @or  @attr 7=2 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc");
247         $query=' @or  @attr 7=1 @attr 1=Heading 0'.$query if ($sortby eq "HeadingAsc");
248         $query=' @or  @attr 7=2 @attr 1=Heading 0'.$query if ($sortby eq "HeadingDsc");
249         
250         $offset=0 unless $offset;
251         my $counter = $offset;
252         $length=10 unless $length;
253         my @oAuth;
254         my $i;
255         $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
256         my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
257         my $oAResult;
258         $oAResult= $oAuth[0]->search($Anewq) ; 
259         while (($i = ZOOM::event(\@oAuth)) != 0) {
260             my $ev = $oAuth[$i-1]->last_event();
261             last if $ev == ZOOM::Event::ZEND;
262         }
263         my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
264         if ($error) {
265             warn  "oAuth error: $errmsg ($error) $addinfo $diagset\n";
266             goto NOLUCK;
267         }
268         
269         my $nbresults;
270         $nbresults=$oAResult->size();
271         my $nremains=$nbresults;    
272         my @result = ();
273         my @finalresult = ();
274         
275         if ($nbresults>0){
276         
277         ##Find authid and linkid fields
278         ##we may be searching multiple authoritytypes.
279         ## FIXME this assumes that all authid and linkid fields are the same for all authority types
280         # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]);
281         # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]);
282             while (($counter < $nbresults) && ($counter < ($offset + $length))) {
283             
284             ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
285             my $rec=$oAResult->record($counter);
286             my $marcdata=$rec->raw();
287             my $authrecord;
288             my $separator=C4::Context->preference('authoritysep');
289             $authrecord = MARC::File::USMARC::decode($marcdata);
290             my $authid=$authrecord->field('001')->data(); 
291             my $summary=BuildSummary($authrecord,$authid,$authtypecode);
292             my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
293             my $sth = $dbh->prepare($query_auth_tag);
294             $sth->execute($authtypecode);
295             my $auth_tag_to_report = $sth->fetchrow;
296             my $reported_tag;
297             my $mainentry = $authrecord->field($auth_tag_to_report);
298             if ($mainentry) {
299                 foreach ($mainentry->subfields()) {
300                     $reported_tag .='$'.$_->[0].$_->[1];
301                 }
302             }
303             my %newline;
304             $newline{summary} = $summary;
305             $newline{authid} = $authid;
306             $newline{even} = $counter % 2;
307             $newline{reported_tag} = $reported_tag;
308             $counter++;
309             push @finalresult, \%newline;
310             }## while counter
311         ###
312         for (my $z=0; $z<@finalresult; $z++){
313                 my  $count=CountUsage($finalresult[$z]{authid});
314                 $finalresult[$z]{used}=$count;
315         }# all $z's
316         
317         }## if nbresult
318         NOLUCK:
319         # $oAResult->destroy();
320         # $oAuth[0]->destroy();
321         
322         return (\@finalresult, $nbresults);
323     }
324 }
325
326 =head2 CountUsage 
327
328 =over 4
329
330 $count= &CountUsage($authid)
331 counts Usage of Authid in bibliorecords. 
332
333 =back
334
335 =cut
336
337 sub CountUsage {
338     my ($authid) = @_;
339     if (C4::Context->preference('NoZebra')) {
340         # Read the index Koha-Auth-Number for this authid and count the lines
341         my $result = C4::Search::NZanalyse("an=$authid");
342         my @tab = split /;/,$result;
343         return scalar @tab;
344     } else {
345         ### ZOOM search here
346         my $oConnection=C4::Context->Zconn("biblioserver",1);
347         my $query;
348         $query= "an=".$authid;
349         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
350         my $result;
351         while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
352             my $ev = $oConnection->last_event();
353             if ($ev == ZOOM::Event::ZEND) {
354                 $result = $oResult->size();
355             }
356         }
357         return ($result);
358     }
359 }
360
361 =head2 CountUsageChildren 
362
363 =over 4
364
365 $count= &CountUsageChildren($authid)
366 counts Usage of narrower terms of Authid in bibliorecords.
367
368 =back
369
370 =cut
371 sub CountUsageChildren {
372   my ($authid) = @_;
373 }
374
375 =head2 GetAuthTypeCode
376
377 =over 4
378
379 $authtypecode= &GetAuthTypeCode($authid)
380 returns authtypecode of an authid
381
382 =back
383
384 =cut
385 sub GetAuthTypeCode {
386 #AUTHfind_authtypecode
387   my ($authid) = @_;
388   my $dbh=C4::Context->dbh;
389   my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
390   $sth->execute($authid);
391   my ($authtypecode) = $sth->fetchrow;
392   return $authtypecode;
393 }
394  
395 =head2 GetTagsLabels
396
397 =over 4
398
399 $tagslabel= &GetTagsLabels($forlibrarian,$authtypecode)
400 returns a ref to hashref of authorities tag and subfield structure.
401
402 tagslabel usage : 
403 $tagslabel->{$tag}->{$subfield}->{'attribute'}
404 where attribute takes values in :
405   lib
406   tab
407   mandatory
408   repeatable
409   authorised_value
410   authtypecode
411   value_builder
412   kohafield
413   seealso
414   hidden
415   isurl
416   link
417
418 =back
419
420 =cut
421 sub GetTagsLabels {
422   my ($forlibrarian,$authtypecode)= @_;
423   my $dbh=C4::Context->dbh;
424   $authtypecode="" unless $authtypecode;
425   my $sth;
426   my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
427
428
429   # check that authority exists
430   $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?");
431   $sth->execute($authtypecode);
432   my ($total) = $sth->fetchrow;
433   $authtypecode="" unless ($total >0);
434   $sth= $dbh->prepare(
435 "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable 
436  FROM auth_tag_structure 
437  WHERE authtypecode=? 
438  ORDER BY tagfield"
439     );
440
441   $sth->execute($authtypecode);
442   my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
443
444   while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
445         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
446         $res->{$tag}->{tab}        = " ";            # XXX
447         $res->{$tag}->{mandatory}  = $mandatory;
448         $res->{$tag}->{repeatable} = $repeatable;
449   }
450   $sth=      $dbh->prepare(
451 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl 
452 FROM auth_subfield_structure 
453 WHERE authtypecode=? 
454 ORDER BY tagfield,tagsubfield"
455     );
456     $sth->execute($authtypecode);
457
458     my $subfield;
459     my $authorised_value;
460     my $value_builder;
461     my $kohafield;
462     my $seealso;
463     my $hidden;
464     my $isurl;
465     my $link;
466
467     while (
468         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
469         $mandatory,     $repeatable, $authorised_value, $authtypecode,
470         $value_builder, $kohafield,  $seealso,          $hidden,
471         $isurl,            $link )
472         = $sth->fetchrow
473       )
474     {
475         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
476         $res->{$tag}->{$subfield}->{tab}              = $tab;
477         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
478         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
479         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
480         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
481         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
482         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
483         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
484         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
485         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
486         $res->{$tag}->{$subfield}->{link}            = $link;
487     }
488     return $res;
489 }
490
491 =head2 AddAuthority
492
493 =over 4
494
495 $authid= &AddAuthority($record, $authid,$authtypecode)
496 returns authid of the newly created authority
497
498 Either Create Or Modify existing authority.
499
500 =back
501
502 =cut
503 sub AddAuthority {
504 # pass the MARC::Record to this function, and it will create the records in the authority table
505   my ($record,$authid,$authtypecode) = @_;
506   my $dbh=C4::Context->dbh;
507   my $leader='         a              ';##Fixme correct leader as this one just adds utf8 to MARC21
508
509 # if authid empty => true add, find a new authid number
510   my $format= 'UNIMARCAUTH' if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC');
511   $format= 'MARC21' if (uc(C4::Context->preference('marcflavour')) ne 'UNIMARC');
512   if (($format eq "UNIMARCAUTH") && (!$record->subfield('100','a'))){
513         $record->leader("     nx  j22             ");
514         my $date=POSIX::strftime("%Y%m%d",localtime);    
515         if ($record->field('100')){
516           $record->field('100')->update('a'=>$date."afrey50      ba0");
517         } else {      
518           $record->append_fields(
519             MARC::Field->new('100',' ',' '
520               ,'a'=>$date."afrey50      ba0")
521           );
522         }      
523   }    
524   $record->add_fields('152','','','b'=>$authtypecode) unless ($record->field('152') && $record->subfield('152','b'));
525   if (!$authid) {
526     my $sth=$dbh->prepare("select max(authid) from auth_header");
527     $sth->execute;
528     ($authid)=$sth->fetchrow;
529     $authid=$authid+1;
530   ##Insert the recordID in MARC record 
531     unless ($record->field('001') && $record->field('001')->data() eq $authid){
532         $record->delete_field($record->field('001'));
533         $record->insert_fields_ordered(MARC::Field->new('001',$authid));
534     }
535 #     warn $record->as_formatted;
536     $dbh->do("lock tables auth_header WRITE");
537     $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc,marcxml) values (?,now(),?,?,?)");
538     $sth->execute($authid,$authtypecode,$record->as_usmarc,$record->as_xml_record($format));
539     $sth->finish;
540   }else{
541       $record->add_fields('001',$authid) unless ($record->field('001'));
542       $dbh->do("lock tables auth_header WRITE");
543       my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
544       $sth->execute($record->as_usmarc,$record->as_xml_record($format),$authid);
545       $sth->finish;
546   }
547   $dbh->do("unlock tables");
548   ModZebra($authid,'specialUpdate',"authorityserver",$record);
549   return ($authid);
550 }
551
552
553 =head2 DelAuthority
554
555 =over 4
556
557 $authid= &DelAuthority($authid)
558 Deletes $authid
559
560 =back
561
562 =cut
563
564
565 sub DelAuthority {
566     my ($authid) = @_;
567     my $dbh=C4::Context->dbh;
568
569     ModZebra($authid,"recordDelete","authorityserver",GetAuthority($authid));
570     $dbh->do("delete from auth_header where authid=$authid") ;
571
572 }
573
574 sub ModAuthority {
575   my ($authid,$record,$authtypecode,$merge)=@_;
576   my $dbh=C4::Context->dbh;
577 #   my ($oldrecord)=&GetAuthority($authid);
578 #   if ($oldrecord eq $record) {
579 #       return;
580 #   }
581 #   my $sth=$dbh->prepare("update auth_header set marc=?,marcxml=? where authid=?");
582   #Now rewrite the $record to table with an add
583   $authid=AddAuthority($record,$authid,$authtypecode);
584
585 ### 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
586 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
587 ### the $merge flag is now depreceated and will be removed at code cleaning
588   if (C4::Context->preference('dontmerge') ){
589   # save the file in tmp/modified_authorities
590       my $cgidir = C4::Context->intranetdir ."/cgi-bin";
591       unless (opendir(DIR,"$cgidir")) {
592               $cgidir = C4::Context->intranetdir."/";
593       }
594   
595       my $filename = $cgidir."/tmp/modified_authorities/$authid.authid";
596       open AUTH, "> $filename";
597       print AUTH $authid;
598       close AUTH;
599   } else {
600 #        &merge($authid,$record,$authid,$record);
601   }
602   return $authid;
603 }
604
605 =head2 GetAuthorityXML 
606
607 =over 4
608
609 $marcxml= &GetAuthorityXML( $authid)
610 returns xml form of record $authid
611
612 =back
613
614 =cut
615 sub GetAuthorityXML {
616   # Returns MARC::XML of the authority passed in parameter.
617   my ( $authid ) = @_;
618   my $dbh=C4::Context->dbh;
619   my $sth =
620       $dbh->prepare("select marcxml from auth_header where authid=? "  );
621   $sth->execute($authid);
622   my ($marcxml)=$sth->fetchrow;
623   return $marcxml;
624
625 }
626
627 =head2 GetAuthority 
628
629 =over 4
630
631 $record= &GetAuthority( $authid)
632 Returns MARC::Record of the authority passed in parameter.
633
634 =back
635
636 =cut
637 sub GetAuthority {
638     my ($authid)=@_;
639     my $dbh=C4::Context->dbh;
640     my $sth=$dbh->prepare("select marcxml from auth_header where authid=?");
641     $sth->execute($authid);
642     my ($marcxml) = $sth->fetchrow;
643     my $record=MARC::Record->new_from_xml($marcxml,'UTF-8',(C4::Context->preference("marcflavour") eq "UNIMARC"?"UNIMARCAUTH":C4::Context->preference("marcflavour")));
644     $record->encoding('UTF-8');
645     return ($record);
646 }
647
648 =head2 GetAuthType 
649
650 =over 4
651
652 $result= &GetAuthType( $authtypecode)
653 If $authtypecode is not "" then 
654   Returns hashref to authtypecode information
655 else 
656   returns ref to array of hashref information of all Authtypes
657
658 =back
659
660 =cut
661 sub GetAuthType {
662     my ($authtypecode) = @_;
663     my $dbh=C4::Context->dbh;
664     my $sth;
665     if (defined $authtypecode){ # NOTE - in MARC21 framework, '' is a valid authority 
666                                 # type
667       $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
668       $sth->execute($authtypecode);
669     } else {
670       $sth=$dbh->prepare("select * from auth_types");
671       $sth->execute;
672     }
673     my $res=$sth->fetchall_arrayref({});
674     if (scalar(@$res)==1){
675       return $res->[0];
676     } else {
677       return $res;
678     }
679 }
680
681
682 sub AUTHhtml2marc {
683     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
684     my $dbh=C4::Context->dbh;
685     my $prevtag = -1;
686     my $record = MARC::Record->new();
687 #---- TODO : the leader is missing
688
689 #     my %subfieldlist=();
690     my $prevvalue; # if tag <10
691     my $field; # if tag >=10
692     for (my $i=0; $i< @$rtags; $i++) {
693         # rebuild MARC::Record
694         if (@$rtags[$i] ne $prevtag) {
695             if ($prevtag < 10) {
696                 if ($prevvalue) {
697                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
698                 }
699             } else {
700                 if ($field) {
701                     $record->add_fields($field);
702                 }
703             }
704             $indicators{@$rtags[$i]}.='  ';
705             if (@$rtags[$i] <10) {
706                 $prevvalue= @$rvalues[$i];
707                 undef $field;
708             } else {
709                 undef $prevvalue;
710                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
711             }
712             $prevtag = @$rtags[$i];
713         } else {
714             if (@$rtags[$i] <10) {
715                 $prevvalue=@$rvalues[$i];
716             } else {
717                 if (length(@$rvalues[$i])>0) {
718                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
719                 }
720             }
721             $prevtag= @$rtags[$i];
722         }
723     }
724     # the last has not been included inside the loop... do it now !
725     $record->add_fields($field) if $field;
726     return $record;
727 }
728
729 =head2 FindDuplicateAuthority
730
731 =over 4
732
733 $record= &FindDuplicateAuthority( $record, $authtypecode)
734 return $authid,Summary if duplicate is found.
735
736 Comments : an improvement would be to return All the records that match.
737
738 =back
739
740 =cut
741
742 sub FindDuplicateAuthority {
743
744     my ($record,$authtypecode)=@_;
745 #    warn "IN for ".$record->as_formatted;
746     my $dbh = C4::Context->dbh;
747 #    warn "".$record->as_formatted;
748     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
749     $sth->execute($authtypecode);
750     my ($auth_tag_to_report) = $sth->fetchrow;
751     $sth->finish;
752 #     warn "record :".$record->as_formatted."  auth_tag_to_report :$auth_tag_to_report";
753     # build a request for SearchAuthorities
754     my $query='at='.$authtypecode.' ';
755     map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)}  $record->field($auth_tag_to_report)->subfields() if $record->field($auth_tag_to_report);
756     my ($error,$results)=SimpleSearch($query,"authorityserver");
757     # there is at least 1 result => return the 1st one
758     if (@$results>0) {
759       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
760       return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
761     }
762     # no result, returns nothing
763     return;
764 }
765
766 =head2 BuildSummary
767
768 =over 4
769
770 $text= &BuildSummary( $record, $authid, $authtypecode)
771 return HTML encoded Summary
772
773 Comment : authtypecode can be infered from both record and authid.
774 Moreover, authid can also be inferred from $record.
775 Would it be interesting to delete those things.
776
777 =back
778
779 =cut
780
781 sub BuildSummary{
782 ## give this a Marc record to return summary
783   my ($record,$authid,$authtypecode)=@_;
784   my $dbh=C4::Context->dbh;
785   my $summary;
786   # handle $authtypecode is NULL or eq ""
787   if ($authtypecode) {
788         my $authref = GetAuthType($authtypecode);
789         $summary = $authref->{summary};
790   }
791   # FIXME: should use I18N.pm
792   my %language;
793   $language{'fre'}="Français";
794   $language{'eng'}="Anglais";
795   $language{'ger'}="Allemand";
796   $language{'ita'}="Italien";
797   $language{'spa'}="Espagnol";
798   my %thesaurus;
799   $thesaurus{'1'}="Peuples";
800   $thesaurus{'2'}="Anthroponymes";
801   $thesaurus{'3'}="Oeuvres";
802   $thesaurus{'4'}="Chronologie";
803   $thesaurus{'5'}="Lieux";
804   $thesaurus{'6'}="Sujets";
805   #thesaurus a remplir
806   my @fields = $record->fields();
807   my $reported_tag;
808   # if the library has a summary defined, use it. Otherwise, build a standard one
809   # FIXME - it appears that the summary field in the authority frameworks
810   #         can work as a display template.  However, this doesn't
811   #         suit the MARC21 version, so for now the "templating"
812   #         feature will be enabled only for UNIMARC for backwards
813   #         compatibility.
814   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
815     my @fields = $record->fields();
816     #             $reported_tag = '$9'.$result[$counter];
817     foreach my $field (@fields) {
818       my $tag = $field->tag();
819       my $tagvalue = $field->as_string();
820       $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
821       if ($tag<10) {
822         if ($tag eq '001') {
823           $reported_tag.='$3'.$field->data();
824         }
825       } else {
826         my @subf = $field->subfields;
827         for my $i (0..$#subf) {
828           my $subfieldcode = $subf[$i][0];
829           my $subfieldvalue = $subf[$i][1];
830           my $tagsubf = $tag.$subfieldcode;
831           $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
832         }
833       }
834     }
835     $summary =~ s/\[(.*?)]//g;
836     $summary =~ s/\n/<br>/g;
837   } else {
838     my $heading; 
839     my $authid; 
840     my $altheading;
841     my $seealso;
842     my $broaderterms;
843     my $narrowerterms;
844     my $see;
845     my $seeheading;
846         my $notes;
847     my @fields = $record->fields();
848     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
849     # construct UNIMARC summary, that is quite different from MARC21 one
850       # accepted form
851       foreach my $field ($record->field('2..')) {
852         $heading.= $field->subfield('a');
853                 $authid=$field->subfield('3');
854       }
855       # rejected form(s)
856       foreach my $field ($record->field('3..')) {
857         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
858       }
859       foreach my $field ($record->field('4..')) {
860         my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : " if ($field->subfield('2'));
861         $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
862       }
863       # see :
864       foreach my $field ($record->field('5..')) {
865             
866         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
867           $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
868         } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
869           $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
870         } elsif ($field->subfield('a')) {
871           $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
872         }
873       }
874       # // form
875       foreach my $field ($record->field('7..')) {
876         my $lang = substr($field->subfield('8'),3,3);
877         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
878       }
879             $broaderterms =~s/-- \n$//;
880             $narrowerterms =~s/-- \n$//;
881             $seealso =~s/-- \n$//;
882             $see =~s/-- \n$//;
883       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
884       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
885       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
886       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
887       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
888       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
889       } else {
890       # construct MARC21 summary
891           # FIXME - looping over 1XX is questionable
892           # since MARC21 authority should have only one 1XX
893           foreach my $field ($record->field('1..')) {
894               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
895                                               # in MARC21 -- purely local tags really ought to be
896                                               # 9XX
897               if ($record->field('100')) {
898                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
899               } elsif ($record->field('110')) {
900                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
901               } elsif ($record->field('111')) {
902                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
903               } elsif ($record->field('130')) {
904                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
905               } elsif ($record->field('148')) {
906                                       $heading.= $field->as_string('abvxyz68');
907               } elsif ($record->field('150')) {
908           #    $heading.= $field->as_string('abvxyz68');
909           $heading.= $field->as_formatted();
910               my $tag=$field->tag();
911               $heading=~s /^$tag//g;
912               $heading =~s /\_/\$/g;
913               } elsif ($record->field('151')) {
914                                       $heading.= $field->as_string('avxyz68');
915               } elsif ($record->field('155')) {
916                                       $heading.= $field->as_string('abvxyz68');
917               } elsif ($record->field('180')) {
918                                       $heading.= $field->as_string('vxyz68');
919               } elsif ($record->field('181')) {
920                                       $heading.= $field->as_string('vxyz68');
921               } elsif ($record->field('182')) {
922                                       $heading.= $field->as_string('vxyz68');
923               } elsif ($record->field('185')) {
924                                       $heading.= $field->as_string('vxyz68');
925               } else {
926                   $heading.= $field->as_string();
927               }
928           } #See From
929           foreach my $field ($record->field('4..')) {
930               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
931           } #See Also
932           foreach my $field ($record->field('5..')) {
933               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
934           }
935           $summary .= ": " if $summary;
936           $summary.=$heading.$seeheading.$altheading;
937       }
938   }
939   return $summary;
940 }
941
942 =head2 BuildUnimarcHierarchies
943
944 =over 4
945
946 $text= &BuildUnimarcHierarchies( $authid, $force)
947 return text containing trees for hierarchies
948 for them to be stored in auth_header
949
950 Example of text:
951 122,1314,2452;1324,2342,3,2452
952
953 =back
954
955 =cut
956 sub BuildUnimarcHierarchies{
957   my $authid = shift @_;
958 #   warn "authid : $authid";
959   my $force = shift @_;
960   my @globalresult;
961   my $dbh=C4::Context->dbh;
962   my $hierarchies;
963   my $data = GetHeaderAuthority($authid);
964   if ($data->{'authtrees'} and not $force){
965     return $data->{'authtrees'};
966   } elsif ($data->{'authtrees'}){
967     $hierarchies=$data->{'authtrees'};
968   } else {
969     my $record = GetAuthority($authid);
970     my $found;
971     foreach my $field ($record->field('550')){
972       if ($field->subfield('5') && $field->subfield('5') eq 'g'){
973         my $parentrecord = GetAuthority($field->subfield('3'));
974         my $localresult=$hierarchies;
975         my $trees;
976         $trees = BuildUnimarcHierarchies($field->subfield('3'));
977         my @trees;
978         if ($trees=~/;/){
979            @trees = split(/;/,$trees);
980         } else {
981            push @trees, $trees;
982         }
983         foreach (@trees){
984           $_.= ",$authid";
985         }
986         @globalresult = (@globalresult,@trees);
987         $found=1;
988       }
989       $hierarchies=join(";",@globalresult);
990     }
991     #Unless there is no ancestor, I am alone.
992     $hierarchies="$authid" unless ($hierarchies);
993   }
994   AddAuthorityTrees($authid,$hierarchies);
995   return $hierarchies;
996 }
997
998 =head2 BuildUnimarcHierarchy
999
1000 =over 4
1001
1002 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1003 return a hashref in order to display hierarchy for record and final Authid $authid
1004
1005 "loopparents"
1006 "loopchildren"
1007 "class"
1008 "loopauthid"
1009 "current_value"
1010 "value"
1011
1012 "ifparents"  
1013 "ifchildren" 
1014 Those two latest ones should disappear soon.
1015
1016 =back
1017
1018 =cut
1019 sub BuildUnimarcHierarchy{
1020   my $record = shift @_;
1021   my $class = shift @_;
1022   my $authid_constructed = shift @_;
1023   my $authid=$record->subfield('250','3');
1024   my %cell;
1025   my $parents=""; my $children="";
1026   my (@loopparents,@loopchildren);
1027   foreach my $field ($record->field('550')){
1028     if ($field->subfield('5') && $field->subfield('a')){
1029       if ($field->subfield('5') eq 'h'){
1030         push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1031       }elsif ($field->subfield('5') eq 'g'){
1032         push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1033       }
1034           # brothers could get in there with an else
1035     }
1036   }
1037   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1038   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1039   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1040   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1041   $cell{"class"}=$class;
1042   $cell{"loopauthid"}=$authid;
1043   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1044   $cell{"value"}=$record->subfield('250',"a");
1045   return \%cell;
1046 }
1047
1048 =head2 GetHeaderAuthority
1049
1050 =over 4
1051
1052 $ref= &GetHeaderAuthority( $authid)
1053 return a hashref in order auth_header table data
1054
1055 =back
1056
1057 =cut
1058 sub GetHeaderAuthority{
1059   my $authid = shift @_;
1060   my $sql= "SELECT * from auth_header WHERE authid = ?";
1061   my $dbh=C4::Context->dbh;
1062   my $rq= $dbh->prepare($sql);
1063   $rq->execute($authid);
1064   my $data= $rq->fetchrow_hashref;
1065   return $data;
1066 }
1067
1068 =head2 AddAuthorityTrees
1069
1070 =over 4
1071
1072 $ref= &AddAuthorityTrees( $authid, $trees)
1073 return success or failure
1074
1075 =back
1076
1077 =cut
1078
1079 sub AddAuthorityTrees{
1080   my $authid = shift @_;
1081   my $trees = shift @_;
1082   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1083   my $dbh=C4::Context->dbh;
1084   my $rq= $dbh->prepare($sql);
1085   return $rq->execute($trees,$authid);
1086 }
1087
1088 =head2 merge
1089
1090 =over 4
1091
1092 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1093
1094
1095 Could add some feature : Migrating from a typecode to an other for instance.
1096 Then we should add some new parameter : bibliotargettag, authtargettag
1097
1098 =back
1099
1100 =cut
1101 sub merge {
1102     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1103     my $dbh=C4::Context->dbh;
1104     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1105     my $authtypecodeto = GetAuthTypeCode($mergeto);
1106     # return if authority does not exist
1107     my @X = $MARCfrom->fields();
1108     return if $#X == -1;
1109     @X = $MARCto->fields();
1110     return if $#X == -1;
1111     # search the tag to report
1112     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1113     $sth->execute($authtypecodefrom);
1114     my ($auth_tag_to_report) = $sth->fetchrow;
1115     
1116     my @record_to;
1117     @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
1118     my @record_from;
1119     @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
1120     
1121     # search all biblio tags using this authority.
1122     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1123     $sth->execute($authtypecodefrom);
1124     my @tags_using_authtype;
1125     while (my ($tagfield) = $sth->fetchrow) {
1126         push @tags_using_authtype,$tagfield."9" ;
1127     }
1128
1129     if (C4::Context->preference('NoZebra')) {
1130         warn "MERGE TO DO";
1131     } else {
1132         # now, find every biblio using this authority
1133         my $oConnection=C4::Context->Zconn("biblioserver");
1134         my $query;
1135         $query= "an= ".$mergefrom;
1136         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1137         my $count=$oResult->size() if  ($oResult);
1138         my @reccache;
1139         my $z=0;
1140         while ( $z<$count ) {
1141         my $rec;
1142                 $rec=$oResult->record($z);
1143             my $marcdata = $rec->raw();
1144         push @reccache, $marcdata;
1145         $z++;
1146         }
1147         $oResult->destroy();
1148         foreach my $marc(@reccache){
1149             my $update;
1150             my $marcrecord;
1151             $marcrecord = MARC::File::USMARC::decode($marc);
1152             foreach my $tagfield (@tags_using_authtype){
1153             $tagfield=substr($tagfield,0,3);
1154             my @tags = $marcrecord->field($tagfield);
1155             foreach my $tag (@tags){
1156                 my $tagsubs=$tag->subfield("9");
1157             #warn "$tagfield:$tagsubs:$mergefrom";
1158                 if ($tagsubs== $mergefrom) {
1159                 $tag->update("9" =>$mergeto);
1160                 foreach my $subfield (@record_to) {
1161             #        warn "$subfield,$subfield->[0],$subfield->[1]";
1162                     $tag->update($subfield->[0] =>$subfield->[1]);
1163                 }#for $subfield
1164                 }
1165                 $marcrecord->delete_field($tag);
1166                 $marcrecord->add_fields($tag);
1167                 $update=1;
1168             }#for each tag
1169             }#foreach tagfield
1170             my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,"") ;
1171             if ($update==1){
1172             &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},GetFrameworkCode($oldbiblio->{'biblionumber'})) ;
1173             }
1174             
1175         }#foreach $marc
1176     }
1177   # now, find every other authority linked with this authority
1178 #   my $oConnection=C4::Context->Zconn("authorityserver");
1179 #   my $query;
1180 # # att 9210               Auth-Internal-authtype
1181 # # att 9220               Auth-Internal-LN
1182 # # ccl.properties to add for authorities
1183 #   $query= "= ".$mergefrom;
1184 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1185 #   my $count=$oResult->size() if  ($oResult);
1186 #   my @reccache;
1187 #   my $z=0;
1188 #   while ( $z<$count ) {
1189 #   my $rec;
1190 #           $rec=$oResult->record($z);
1191 #       my $marcdata = $rec->raw();
1192 #   push @reccache, $marcdata;
1193 #   $z++;
1194 #   }
1195 #   $oResult->destroy();
1196 #   foreach my $marc(@reccache){
1197 #     my $update;
1198 #     my $marcrecord;
1199 #     $marcrecord = MARC::File::USMARC::decode($marc);
1200 #     foreach my $tagfield (@tags_using_authtype){
1201 #       $tagfield=substr($tagfield,0,3);
1202 #       my @tags = $marcrecord->field($tagfield);
1203 #       foreach my $tag (@tags){
1204 #         my $tagsubs=$tag->subfield("9");
1205 #     #warn "$tagfield:$tagsubs:$mergefrom";
1206 #         if ($tagsubs== $mergefrom) {
1207 #           $tag->update("9" =>$mergeto);
1208 #           foreach my $subfield (@record_to) {
1209 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1210 #             $tag->update($subfield->[0] =>$subfield->[1]);
1211 #           }#for $subfield
1212 #         }
1213 #         $marcrecord->delete_field($tag);
1214 #         $marcrecord->add_fields($tag);
1215 #         $update=1;
1216 #       }#for each tag
1217 #     }#foreach tagfield
1218 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1219 #     if ($update==1){
1220 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1221 #     }
1222
1223 #   }#foreach $marc
1224 }#sub
1225 END { }       # module clean-up code here (global destructor)
1226
1227 =back
1228
1229 =head1 AUTHOR
1230
1231 Koha Developement team <info@koha.org>
1232
1233 Paul POULAIN paul.poulain@free.fr
1234
1235 =cut