BIG COMMIT: minimal fix to authorities search
[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=Authority/format-id \@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-Entity ";
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         # I get an error 207 from zebra 'cannot sort according to sequence', so I'm modifying as below - JF
247         #$query=' @or  @attr 7=1 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading-Entity 1'.$query if ($sortby eq "HeadingAsc");
248         #$query=' @or  @attr 7=2 @attr 1=Heading 0 @or  @attr 7=1 @attr 1=Heading-Entity 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 $authref = GetAuthType($authtypecode);
788   my $summary = $authref->{summary};
789   my %language;
790   $language{'fre'}="Français";
791   $language{'eng'}="Anglais";
792   $language{'ger'}="Allemand";
793   $language{'ita'}="Italien";
794   $language{'spa'}="Espagnol";
795   my %thesaurus;
796   $thesaurus{'1'}="Peuples";
797   $thesaurus{'2'}="Anthroponymes";
798   $thesaurus{'3'}="Oeuvres";
799   $thesaurus{'4'}="Chronologie";
800   $thesaurus{'5'}="Lieux";
801   $thesaurus{'6'}="Sujets";
802   #thesaurus a remplir
803   my @fields = $record->fields();
804   my $reported_tag;
805   # if the library has a summary defined, use it. Otherwise, build a standard one
806   # FIXME - it appears that the summary field in the authority frameworks
807   #         can work as a display template.  However, this doesn't
808   #         suit the MARC21 version, so for now the "templating"
809   #         feature will be enabled only for UNIMARC for backwards
810   #         compatibility.
811   if ($summary and C4::Context->preference('marcflavour') eq 'UNIMARC') {
812     my @fields = $record->fields();
813     #             $reported_tag = '$9'.$result[$counter];
814     foreach my $field (@fields) {
815       my $tag = $field->tag();
816       my $tagvalue = $field->as_string();
817       $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
818       if ($tag<10) {
819         if ($tag eq '001') {
820           $reported_tag.='$3'.$field->data();
821         }
822       } else {
823         my @subf = $field->subfields;
824         for my $i (0..$#subf) {
825           my $subfieldcode = $subf[$i][0];
826           my $subfieldvalue = $subf[$i][1];
827           my $tagsubf = $tag.$subfieldcode;
828           $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
829         }
830       }
831     }
832     $summary =~ s/\[(.*?)]//g;
833     $summary =~ s/\n/<br>/g;
834   } else {
835     my $heading; 
836     my $authid; 
837     my $altheading;
838     my $seealso;
839     my $broaderterms;
840     my $narrowerterms;
841     my $see;
842     my $seeheading;
843         my $notes;
844     my @fields = $record->fields();
845     if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
846     # construct UNIMARC summary, that is quite different from MARC21 one
847       # accepted form
848       foreach my $field ($record->field('2..')) {
849         $heading.= $field->subfield('a');
850                 $authid=$field->subfield('3');
851       }
852       # rejected form(s)
853       foreach my $field ($record->field('3..')) {
854         $notes.= '<span class="note">'.$field->subfield('a')."</span>\n";
855       }
856       foreach my $field ($record->field('4..')) {
857         my $thesaurus = "thes. : ".$thesaurus{"$field->subfield('2')"}." : " if ($field->subfield('2'));
858         $see.= '<span class="UF">'.$thesaurus.$field->subfield('a')."</span> -- \n";
859       }
860       # see :
861       foreach my $field ($record->field('5..')) {
862             
863         if (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'g')) {
864           $broaderterms.= '<span class="BT"> <a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
865         } elsif (($field->subfield('5')) && ($field->subfield('a')) && ($field->subfield('5') eq 'h')){
866           $narrowerterms.= '<span class="NT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
867         } elsif ($field->subfield('a')) {
868           $seealso.= '<span class="RT"><a href="detail.pl?authid='.$field->subfield('3').'">'.$field->subfield('a')."</a></span> -- \n";
869         }
870       }
871       # // form
872       foreach my $field ($record->field('7..')) {
873         my $lang = substr($field->subfield('8'),3,3);
874         $seeheading.= '<span class="langue"> En '.$language{$lang}.' : </span><span class="OT"> '.$field->subfield('a')."</span><br />\n";  
875       }
876             $broaderterms =~s/-- \n$//;
877             $narrowerterms =~s/-- \n$//;
878             $seealso =~s/-- \n$//;
879             $see =~s/-- \n$//;
880       $summary = "<b><a href=\"detail.pl?authid=$authid\">".$heading."</a></b><br />".($notes?"$notes <br />":"");
881       $summary.= '<p><div class="label">TG : '.$broaderterms.'</div></p>' if ($broaderterms);
882       $summary.= '<p><div class="label">TS : '.$narrowerterms.'</div></p>' if ($narrowerterms);
883       $summary.= '<p><div class="label">TA : '.$seealso.'</div></p>' if ($seealso);
884       $summary.= '<p><div class="label">EP : '.$see.'</div></p>' if ($see);
885       $summary.= '<p><div class="label">'.$seeheading.'</div></p>' if ($seeheading);
886       } else {
887       # construct MARC21 summary
888           # FIXME - looping over 1XX is questionable
889           # since MARC21 authority should have only one 1XX
890           foreach my $field ($record->field('1..')) {
891               next if "152" eq $field->tag(); # FIXME - 152 is not a good tag to use
892                                               # in MARC21 -- purely local tags really ought to be
893                                               # 9XX
894               if ($record->field('100')) {
895                   $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
896               } elsif ($record->field('110')) {
897                                       $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
898               } elsif ($record->field('111')) {
899                                       $heading.= $field->as_string('acdefghklnpqstvxyz68');
900               } elsif ($record->field('130')) {
901                                       $heading.= $field->as_string('adfghklmnoprstvxyz68');
902               } elsif ($record->field('148')) {
903                                       $heading.= $field->as_string('abvxyz68');
904               } elsif ($record->field('150')) {
905           #    $heading.= $field->as_string('abvxyz68');
906           $heading.= $field->as_formatted();
907               my $tag=$field->tag();
908               $heading=~s /^$tag//g;
909               $heading =~s /\_/\$/g;
910               } elsif ($record->field('151')) {
911                                       $heading.= $field->as_string('avxyz68');
912               } elsif ($record->field('155')) {
913                                       $heading.= $field->as_string('abvxyz68');
914               } elsif ($record->field('180')) {
915                                       $heading.= $field->as_string('vxyz68');
916               } elsif ($record->field('181')) {
917                                       $heading.= $field->as_string('vxyz68');
918               } elsif ($record->field('182')) {
919                                       $heading.= $field->as_string('vxyz68');
920               } elsif ($record->field('185')) {
921                                       $heading.= $field->as_string('vxyz68');
922               } else {
923                   $heading.= $field->as_string();
924               }
925           } #See From
926           foreach my $field ($record->field('4..')) {
927               $seeheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>used for/see from:</i> ".$field->as_string();
928           } #See Also
929           foreach my $field ($record->field('5..')) {
930               $altheading.= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string();
931           }
932           $summary .= ": " if $summary;
933           $summary.=$heading.$seeheading.$altheading;
934       }
935   }
936   return $summary;
937 }
938
939 =head2 BuildUnimarcHierarchies
940
941 =over 4
942
943 $text= &BuildUnimarcHierarchies( $authid, $force)
944 return text containing trees for hierarchies
945 for them to be stored in auth_header
946
947 Example of text:
948 122,1314,2452;1324,2342,3,2452
949
950 =back
951
952 =cut
953 sub BuildUnimarcHierarchies{
954   my $authid = shift @_;
955 #   warn "authid : $authid";
956   my $force = shift @_;
957   my @globalresult;
958   my $dbh=C4::Context->dbh;
959   my $hierarchies;
960   my $data = GetHeaderAuthority($authid);
961   if ($data->{'authtrees'} and not $force){
962     return $data->{'authtrees'};
963   } elsif ($data->{'authtrees'}){
964     $hierarchies=$data->{'authtrees'};
965   } else {
966     my $record = GetAuthority($authid);
967     my $found;
968     foreach my $field ($record->field('550')){
969       if ($field->subfield('5') && $field->subfield('5') eq 'g'){
970         my $parentrecord = GetAuthority($field->subfield('3'));
971         my $localresult=$hierarchies;
972         my $trees;
973         $trees = BuildUnimarcHierarchies($field->subfield('3'));
974         my @trees;
975         if ($trees=~/;/){
976            @trees = split(/;/,$trees);
977         } else {
978            push @trees, $trees;
979         }
980         foreach (@trees){
981           $_.= ",$authid";
982         }
983         @globalresult = (@globalresult,@trees);
984         $found=1;
985       }
986       $hierarchies=join(";",@globalresult);
987     }
988     #Unless there is no ancestor, I am alone.
989     $hierarchies="$authid" unless ($hierarchies);
990   }
991   AddAuthorityTrees($authid,$hierarchies);
992   return $hierarchies;
993 }
994
995 =head2 BuildUnimarcHierarchy
996
997 =over 4
998
999 $ref= &BuildUnimarcHierarchy( $record, $class,$authid)
1000 return a hashref in order to display hierarchy for record and final Authid $authid
1001
1002 "loopparents"
1003 "loopchildren"
1004 "class"
1005 "loopauthid"
1006 "current_value"
1007 "value"
1008
1009 "ifparents"  
1010 "ifchildren" 
1011 Those two latest ones should disappear soon.
1012
1013 =back
1014
1015 =cut
1016 sub BuildUnimarcHierarchy{
1017   my $record = shift @_;
1018   my $class = shift @_;
1019   my $authid_constructed = shift @_;
1020   my $authid=$record->subfield('250','3');
1021   my %cell;
1022   my $parents=""; my $children="";
1023   my (@loopparents,@loopchildren);
1024   foreach my $field ($record->field('550')){
1025     if ($field->subfield('5') && $field->subfield('a')){
1026       if ($field->subfield('5') eq 'h'){
1027         push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
1028       }elsif ($field->subfield('5') eq 'g'){
1029         push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
1030       }
1031           # brothers could get in there with an else
1032     }
1033   }
1034   $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
1035   $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
1036   $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
1037   $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
1038   $cell{"class"}=$class;
1039   $cell{"loopauthid"}=$authid;
1040   $cell{"current_value"} =1 if $authid eq $authid_constructed;
1041   $cell{"value"}=$record->subfield('250',"a");
1042   return \%cell;
1043 }
1044
1045 =head2 GetHeaderAuthority
1046
1047 =over 4
1048
1049 $ref= &GetHeaderAuthority( $authid)
1050 return a hashref in order auth_header table data
1051
1052 =back
1053
1054 =cut
1055 sub GetHeaderAuthority{
1056   my $authid = shift @_;
1057   my $sql= "SELECT * from auth_header WHERE authid = ?";
1058   my $dbh=C4::Context->dbh;
1059   my $rq= $dbh->prepare($sql);
1060   $rq->execute($authid);
1061   my $data= $rq->fetchrow_hashref;
1062   return $data;
1063 }
1064
1065 =head2 AddAuthorityTrees
1066
1067 =over 4
1068
1069 $ref= &AddAuthorityTrees( $authid, $trees)
1070 return success or failure
1071
1072 =back
1073
1074 =cut
1075
1076 sub AddAuthorityTrees{
1077   my $authid = shift @_;
1078   my $trees = shift @_;
1079   my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
1080   my $dbh=C4::Context->dbh;
1081   my $rq= $dbh->prepare($sql);
1082   return $rq->execute($trees,$authid);
1083 }
1084
1085 =head2 merge
1086
1087 =over 4
1088
1089 $ref= &merge(mergefrom,$MARCfrom,$mergeto,$MARCto)
1090
1091
1092 Could add some feature : Migrating from a typecode to an other for instance.
1093 Then we should add some new parameter : bibliotargettag, authtargettag
1094
1095 =back
1096
1097 =cut
1098 sub merge {
1099     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
1100     my $dbh=C4::Context->dbh;
1101     my $authtypecodefrom = GetAuthTypeCode($mergefrom);
1102     my $authtypecodeto = GetAuthTypeCode($mergeto);
1103     # return if authority does not exist
1104     my @X = $MARCfrom->fields();
1105     return if $#X == -1;
1106     @X = $MARCto->fields();
1107     return if $#X == -1;
1108     # search the tag to report
1109     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
1110     $sth->execute($authtypecodefrom);
1111     my ($auth_tag_to_report) = $sth->fetchrow;
1112     
1113     my @record_to;
1114     @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
1115     my @record_from;
1116     @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
1117     
1118     # search all biblio tags using this authority.
1119     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
1120     $sth->execute($authtypecodefrom);
1121     my @tags_using_authtype;
1122     while (my ($tagfield) = $sth->fetchrow) {
1123         push @tags_using_authtype,$tagfield."9" ;
1124     }
1125
1126     if (C4::Context->preference('NoZebra')) {
1127         warn "MERGE TO DO";
1128     } else {
1129         # now, find every biblio using this authority
1130         my $oConnection=C4::Context->Zconn("biblioserver");
1131         my $query;
1132         $query= "an= ".$mergefrom;
1133         my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1134         my $count=$oResult->size() if  ($oResult);
1135         my @reccache;
1136         my $z=0;
1137         while ( $z<$count ) {
1138         my $rec;
1139                 $rec=$oResult->record($z);
1140             my $marcdata = $rec->raw();
1141         push @reccache, $marcdata;
1142         $z++;
1143         }
1144         $oResult->destroy();
1145         foreach my $marc(@reccache){
1146             my $update;
1147             my $marcrecord;
1148             $marcrecord = MARC::File::USMARC::decode($marc);
1149             foreach my $tagfield (@tags_using_authtype){
1150             $tagfield=substr($tagfield,0,3);
1151             my @tags = $marcrecord->field($tagfield);
1152             foreach my $tag (@tags){
1153                 my $tagsubs=$tag->subfield("9");
1154             #warn "$tagfield:$tagsubs:$mergefrom";
1155                 if ($tagsubs== $mergefrom) {
1156                 $tag->update("9" =>$mergeto);
1157                 foreach my $subfield (@record_to) {
1158             #        warn "$subfield,$subfield->[0],$subfield->[1]";
1159                     $tag->update($subfield->[0] =>$subfield->[1]);
1160                 }#for $subfield
1161                 }
1162                 $marcrecord->delete_field($tag);
1163                 $marcrecord->add_fields($tag);
1164                 $update=1;
1165             }#for each tag
1166             }#foreach tagfield
1167             my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,"") ;
1168             if ($update==1){
1169             &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},GetFrameworkCode($oldbiblio->{'biblionumber'})) ;
1170             }
1171             
1172         }#foreach $marc
1173     }
1174   # now, find every other authority linked with this authority
1175 #   my $oConnection=C4::Context->Zconn("authorityserver");
1176 #   my $query;
1177 # # att 9210               Auth-Internal-authtype
1178 # # att 9220               Auth-Internal-LN
1179 # # ccl.properties to add for authorities
1180 #   $query= "= ".$mergefrom;
1181 #   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
1182 #   my $count=$oResult->size() if  ($oResult);
1183 #   my @reccache;
1184 #   my $z=0;
1185 #   while ( $z<$count ) {
1186 #   my $rec;
1187 #           $rec=$oResult->record($z);
1188 #       my $marcdata = $rec->raw();
1189 #   push @reccache, $marcdata;
1190 #   $z++;
1191 #   }
1192 #   $oResult->destroy();
1193 #   foreach my $marc(@reccache){
1194 #     my $update;
1195 #     my $marcrecord;
1196 #     $marcrecord = MARC::File::USMARC::decode($marc);
1197 #     foreach my $tagfield (@tags_using_authtype){
1198 #       $tagfield=substr($tagfield,0,3);
1199 #       my @tags = $marcrecord->field($tagfield);
1200 #       foreach my $tag (@tags){
1201 #         my $tagsubs=$tag->subfield("9");
1202 #     #warn "$tagfield:$tagsubs:$mergefrom";
1203 #         if ($tagsubs== $mergefrom) {
1204 #           $tag->update("9" =>$mergeto);
1205 #           foreach my $subfield (@record_to) {
1206 #     #        warn "$subfield,$subfield->[0],$subfield->[1]";
1207 #             $tag->update($subfield->[0] =>$subfield->[1]);
1208 #           }#for $subfield
1209 #         }
1210 #         $marcrecord->delete_field($tag);
1211 #         $marcrecord->add_fields($tag);
1212 #         $update=1;
1213 #       }#for each tag
1214 #     }#foreach tagfield
1215 #     my $authoritynumber = TransformMarcToKoha($dbh,$marcrecord,"") ;
1216 #     if ($update==1){
1217 #       &ModAuthority($marcrecord,$authoritynumber,GetAuthTypeCode($authoritynumber)) ;
1218 #     }
1219
1220 #   }#foreach $marc
1221 }#sub
1222 END { }       # module clean-up code here (global destructor)
1223
1224 =back
1225
1226 =head1 AUTHOR
1227
1228 Koha Developement team <info@koha.org>
1229
1230 Paul POULAIN paul.poulain@free.fr
1231
1232 =cut