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