All support for auth_subfield_tables is removed. All search is now with zebra authori...
[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::Database;
23 use C4::Koha;
24 use MARC::Record;
25 use C4::Biblio;
26 #use ZOOM;
27 use vars qw($VERSION @ISA @EXPORT);
28
29 # set the version for version checking
30 $VERSION = 0.01;
31
32 @ISA = qw(Exporter);
33 @EXPORT = qw(
34         &AUTHgettagslib
35         &AUTHfindsubfield
36         &AUTHfind_authtypecode
37
38         &AUTHaddauthority
39         &AUTHmodauthority
40         &AUTHdelauthority
41         &AUTHaddsubfield
42         &AUTHgetauthority
43         &AUTHfind_marc_from_kohafield
44         &AUTHgetauth_type
45         &AUTHcount_usage
46         &getsummary
47         &authoritysearch
48         
49         
50         &AUTHhtml2marc
51         
52         &merge
53         &FindDuplicate
54  );
55
56 sub AUTHfind_marc_from_kohafield {
57     my ( $dbh, $kohafield,$authtypecode ) = @_;
58     return 0, 0 unless $kohafield;
59 $authtypecode="" unless $authtypecode;
60 my $marcfromkohafield;
61         my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
62         $sth->execute($kohafield,$authtypecode);
63         my ($tagfield,$tagsubfield) = $sth->fetchrow;
64                 
65         return  ($tagfield,$tagsubfield);
66 }
67 sub authoritysearch {
68         my ($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode) = @_;
69         my $query;
70         my $attr;
71         # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
72         # the authtypecode. Then, search on $a of this tag_to_report
73         # also store main entry MARC tag, to extract it at end of search
74         my $mainentrytag;
75         ##first set the authtype search
76         $query="\@attr 1=1013 \@attr 5=100 ".$authtypecode; ##No truncation on authtype
77         my $dosearch;
78         my $and;
79         my $q2;
80         for(my $i = 0 ; $i <= $#{$value} ; $i++)
81         {
82
83         if (@$value[$i]){
84         ##If mainentry search $a tag
85                 if (@$tags[$i] eq "mainentry") {
86                 $attr =" \@attr 1=21 ";
87                 }else{
88                 $attr =" \@attr 1=47 ";
89                 }
90                 
91
92         
93                 
94                 if (@$operator[$i] eq 'phrase') {
95                          $attr.=" \@attr 4=1  \@attr 5=100 \@attr 3=1 ";##Phrase, No truncation, first in field###It seems not implemented by indexdata
96                 
97                 } else {
98                 
99                          $attr .=" \@attr 4=6  \@attr 5=1  ";## Word list, right truncated, anywhere
100                 }                
101         
102                 
103                 $and .=" \@and " ;
104                 $attr =$attr."\"".@$value[$i]."\"";
105                 $q2 .=$attr;
106         $dosearch=1;            
107         }#if value              
108                 
109         }
110 ##Add how many queries generated
111 $query= $and.$query.$q2;
112 warn $query;
113
114 $offset=0 unless $offset;
115 my $counter = $offset;
116 $length=10 unless $length;
117
118 my $oAuth=C4::Context->Zconnauth("authorityserver");
119 if ($oAuth eq "error"){
120 warn "Error/CONNECTING \n";
121   return("error",undef);
122  }
123
124 my $oAResult;
125 my $Anewq= new ZOOM::Query::PQF($query);
126 $Anewq->sortby("1=21 i< 1=47 i<");
127
128 eval {
129 $oAResult= $oAuth->search($Anewq) ; 
130 };
131 if($@){
132 warn " /CODE:", $@->code()," /MSG:",$@->message(),"\n";
133    return("error",undef);
134  }
135
136
137 my $nbresults=0;
138  $nbresults=$oAResult->size() if  ($oAResult);
139         
140         my @result = ();
141
142         
143         my @finalresult = ();
144 if ($nbresults>0){
145 ##fIND tags using authority
146
147         my $newsth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
148                 $newsth->execute($authtypecode);
149                 my $tags_using_authtype;
150                 while (my ($tagfield) = $newsth->fetchrow) {
151                         $tags_using_authtype.= "'".$tagfield."9',";
152                 }
153 ##Find authid and linkid fields
154 my ($authidfield,$authidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authid",$authtypecode);
155 my ($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$authtypecode);
156 while (($counter < $nbresults) && ($counter < ($offset + $length))) {
157
158 ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
159 my $rec=$oAResult->record($counter);
160 my $marcdata=$rec->raw();
161 my $authrecord;         
162 my $linkid;
163 my @linkids;    
164 my $separator=C4::Context->preference('authoritysep');
165 my $linksummary=" ".$separator; 
166         
167         $authrecord = MARC::File::USMARC::decode($marcdata);            
168 my $authid=$authrecord->field($authidfield)->subfield($authidsubfield); ## we could have these defined in system pref.
169         if ($authrecord->field($linkidfield)){
170 my @fields=$authrecord->field($linkidfield);
171
172         foreach my $field (@fields){
173         $linkid=$field->subfield($linkidsubfield) ;
174                 if ($linkid){ ##There is a linked record add fields to produce summary
175 my $linktype=AUTHfind_authtypecode($dbh,$linkid);
176                 my $linkrecord=AUTHgetauthority($dbh,$linkid);
177                 $linksummary.=getsummary($dbh,$linkrecord,$linkid,$linktype).$separator;
178                 }
179         }
180         }#
181
182 my $summary=getsummary($dbh,$authrecord,$authid,$authtypecode);
183 if ($linkid && $linksummary ne " ".$separator){
184 $summary="<b>".$summary."</b>".$linksummary;
185 }
186 ## Fix Async search and move Zconn to here
187         my %newline;
188         $newline{summary} = $summary;
189         $newline{authid} = $authid;
190         $newline{linkid} = $linkid;
191 #       $newline{used} =$count;
192         $newline{biblio_fields} = $tags_using_authtype;
193         $newline{even} = $counter % 2;
194         $counter++;
195         push @finalresult, \%newline;
196         }## while counter
197 $oAResult->destroy();
198 #$oAuth->destroy();
199
200 ###
201 my $oConnection=C4::Context->Zconn("biblioserver");
202         if ($oConnection eq "error"){
203         warn "Error/CONNECTING \n";
204          }
205 my $oResult;
206 for (my $z=0; $z<@finalresult; $z++){
207         my $nquery;
208                 
209                 $nquery= "\@attr GILS 1=2057 ".$finalresult[$z]{authid};
210                 $nquery="\@or ".$nquery." \@attr GILS 1=2057 ".$finalresult[$z]{linkid} if $finalresult[$z]{linkid};
211                 
212                 eval{
213                  $oResult = $oConnection->search_pqf($nquery);
214                 };
215                 if($@){
216                 warn " /CODE:", $@->code()," /MSG:",$@->message(),"\n";
217                 }
218                 my $count=$oResult->size() if  ($oResult);
219                 $finalresult[$z]{used}=$count;
220 }##for Zconn
221         $oResult->destroy();
222 #               $oConnection->destroy();
223 }## if nbresult
224         return (\@finalresult, $nbresults);
225 }
226
227 # Creates the SQL Request
228
229 sub create_request {
230         my ($dbh,$tags, $and_or, $operator, $value) = @_;
231
232         my $sql_tables; # will contain marc_subfield_table as m1,...
233         my $sql_where1; # will contain the "true" where
234         my $sql_where2 = "("; # will contain m1.authid=m2.authid
235         my $nb_active=0; # will contain the number of "active" entries. and entry is active is a value is provided.
236         my $nb_table=1; # will contain the number of table. ++ on each entry EXCEPT when an OR  is provided.
237
238
239         for(my $i=0; $i<=@$value;$i++) {
240                 if (@$value[$i]) {
241                         $nb_active++;
242                         if ($nb_active==1) {
243                                 
244                                         $sql_tables = "auth_subfield_table as m$nb_table,";
245                                         $sql_where1 .= "( m$nb_table.subfieldvalue like '@$value[$i]' ";
246                                         if (@$tags[$i]) {
247                                                 $sql_where1 .=" and concat(m$nb_table.tag,m$nb_table.subfieldcode) IN (@$tags[$i])";
248                                                         }
249                                         $sql_where1.=")";
250                                         } else {
251                                 
252                                         
253                                         
254                                         
255                                         $nb_table++;
256                                         
257                                         $sql_tables .= "auth_subfield_table as m$nb_table,";
258                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue   like '@$value[$i]' ";
259                                         if (@$tags[$i]) {
260                                                 $sql_where1 .=" and concat(m$nb_table.tag,m$nb_table.subfieldcode) IN (@$tags[$i])";
261                                                         }
262                                         $sql_where1.=")";
263                                         $sql_where2.="m1.authid=m$nb_table.authid and ";
264                                                                 
265                                 
266                                         } 
267                                 }
268                 }
269
270         if($sql_where2 ne "(")  # some datas added to sql_where2, processing
271         {
272                 $sql_where2 = substr($sql_where2, 0, (length($sql_where2)-5)); # deletes the trailing ' and '
273                 $sql_where2 .= ")";
274         }
275         else    # no sql_where2 statement, deleting '('
276         {
277                 $sql_where2 = "";
278         }
279         chop $sql_tables;       # deletes the trailing ','
280         
281         return ($sql_tables, $sql_where1, $sql_where2);
282 }
283
284
285 sub AUTHcount_usage {
286         my ($authid) = @_;
287         my $dbh = C4::Context->dbh;
288         # find MARC fields using this authtype
289         my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
290         my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
291         my $tags_used=$sth->execute($authtypecode);
292         my $tags_using_authtype;
293
294         while  (my($tagfield) = $sth->fetchrow){
295 #               warn "TAG : $tagfield";
296                 $tags_using_authtype.= "'".$tagfield."9',";
297
298         }
299
300         chop $tags_using_authtype;
301 ### try ZOOM search here
302 my $oConnection=C4::Context->Zconn("biblioserver");
303 my $query;
304
305 $query= "\@attr GILS 1=2057 ".$authid;
306
307 my $oResult = $oConnection->search_pqf($query);
308
309 my $result=$oResult->size() if  ($oResult);
310
311 ### OLD API
312 #       if ($tags_using_authtype) {
313 #               $sth = $dbh->prepare("select count(*) from marc_subfield_table where concat(tag,subfieldcode) in ($tags_using_authtype) and MATCH(subfieldvalue) AGAINST(? IN BOOLEAN MODE)");
314 #       } else {
315 #               $sth = $dbh->prepare("select count(*) from marc_subfield_table where subfieldvalue=?");
316 #       }
317 #       warn "Q : select count(*) from marc_subfield_table where concat(tag,subfieldcode) in ($tags_using_authtype) and d MATCH(subfieldvalue) AGAINST($authid IN BOOLEAN MODE) ";
318 #       $sth->execute($authid);
319 #       my ($result) = $sth->fetchrow;
320 #       warn "Authority $authid TOTAL USED : $result";
321         
322         return ($result);
323 }
324
325
326
327 sub AUTHfind_authtypecode {
328         my ($dbh,$authid) = @_;
329         my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
330         $sth->execute($authid);
331         my ($authtypecode) = $sth->fetchrow;
332         return $authtypecode;
333 }
334  
335
336 sub AUTHgettagslib {
337         my ($dbh,$forlibrarian,$authtypecode)= @_;
338         $authtypecode="" unless $authtypecode;
339         my $sth;
340         my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
341
342
343         # check that authority exists
344         $sth=$dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?");
345         $sth->execute($authtypecode);
346         my ($total) = $sth->fetchrow;
347         $authtypecode="" unless ($total >0);
348         $sth= $dbh->prepare(
349 "select tagfield,liblibrarian,libopac,mandatory,repeatable from auth_tag_structure where authtypecode=? order by tagfield"
350     );
351
352 $sth->execute($authtypecode);
353          my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
354
355     while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
356         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
357         $res->{$tab}->{tab}        = "";            # XXX
358         $res->{$tag}->{mandatory}  = $mandatory;
359         $res->{$tag}->{repeatable} = $repeatable;
360     }
361         $sth=      $dbh->prepare("select tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link from auth_subfield_structure where authtypecode=? order by tagfield,tagsubfield"
362     );
363         $sth->execute($authtypecode);
364
365          my $subfield;
366     my $authorised_value;
367     my $authtypecode;
368     my $value_builder;
369     my $kohafield;
370     my $seealso;
371     my $hidden;
372     my $isurl;
373         my $link;
374
375     while (
376         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
377         $mandatory,     $repeatable, $authorised_value, $authtypecode,
378         $value_builder, $kohafield,  $seealso,          $hidden,
379         $isurl,                 $link )
380         = $sth->fetchrow
381       )
382     {
383         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
384         $res->{$tag}->{$subfield}->{tab}              = $tab;
385         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
386         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
387         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
388         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
389         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
390         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
391         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
392         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
393         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
394         $res->{$tag}->{$subfield}->{link}            = $link;
395     }
396     return $res;
397 }
398
399 sub AUTHaddauthority {
400 # pass the MARC::Record to this function, and it will create the records in the authority table
401         my ($dbh,$record,$authid,$authtypecode) = @_;
402
403 #my $leadercode=AUTHfind_leader($dbh,$authtypecode);
404 my $leader='         a              ';##Fixme correct leader as this one just adds utf8 to MARC21
405 #substr($leader,8,1)=$leadercode;
406 #       $record->leader($leader);
407 my ($authfield,$authidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authid",$authtypecode);
408 my ($authfield2,$authtypesubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authtypecode",$authtypecode);
409 my ($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$authtypecode);
410
411 # if authid empty => true add, find a new authid number
412         if (!$authid) {
413         my      $sth=$dbh->prepare("select max(authid) from auth_header");
414                 $sth->execute;
415                 ($authid)=$sth->fetchrow;
416                 $authid=$authid+1;
417                 
418 ##Insert the recordID in MARC record 
419
420 ##Both authid and authtypecode is expected to be in the same field. Modify if other requirements arise
421         $record->add_fields($authfield,'','',$authidsubfield=>$authid,$authtypesubfield=>$authtypecode);
422
423                 $dbh->do("lock tables auth_header WRITE");
424                  $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc) values (?,now(),?,?)");
425                 $sth->execute($authid,$authtypecode,$record->as_usmarc);                
426                 $sth->finish;
427         
428         }else{
429 ##Modified record reinsertid
430 $record->delete_field($authfield);
431 $record->add_fields($authfield,'','',$authidsubfield=>$authid,$authtypesubfield=>$authtypecode);
432
433         $dbh->do("lock tables auth_header WRITE");
434         my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
435         $sth->execute($record->as_usmarc,$authid);
436         $sth->finish;
437         }
438         $dbh->do("unlock tables");
439         zebraopauth($dbh,$authid,'specialUpdate');
440
441 if ($record->field($linkidfield)){
442 my @fields=$record->field($linkidfield);
443
444         foreach my $field (@fields){
445 my      $linkid=$field->subfield($linkidsubfield) ;
446                 if ($linkid){
447         ##Modify the record of linked 
448         AUTHaddlink($dbh,$linkid,$authid);
449         }
450         }
451 }
452         return ($authid);
453 }
454
455 sub AUTHaddlink{
456 my ($dbh,$linkid,$authid)=@_;
457 my $record=AUTHgetauthority($dbh,$linkid);
458 my $authtypecode=AUTHfind_authtypecode($dbh,$linkid);
459 #warn "adding l:$linkid,a:$authid,auth:$authtypecode";
460 $record=AUTH2marcOnefieldlink($dbh,$record,"auth_header.linkid",$authid,$authtypecode);
461 $dbh->do("lock tables auth_header WRITE");
462         my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
463         $sth->execute($record->as_usmarc,$linkid);
464         $sth->finish;   
465         $dbh->do("unlock tables");
466         zebraopauth($dbh,$linkid,'specialUpdate');
467 }
468
469 sub AUTH2marcOnefieldlink {
470     my ( $dbh, $record, $kohafieldname, $newvalue,$authtypecode ) = @_;
471 my $sth =      $dbh->prepare(
472 "select tagfield,tagsubfield from auth_subfield_structure where authtypecode=? and kohafield=?"
473     );
474     $sth->execute($authtypecode,$kohafieldname);
475 my  ($tagfield,$tagsubfield)=$sth->fetchrow;
476             $record->add_fields( $tagfield, " ", " ", $tagsubfield => $newvalue );
477     return $record;
478 }
479 sub zebraopauth{
480
481 my ($dbh,$authid,$op)=@_;
482 my $Zconnauthority;
483 my $tried=0;
484 my $recon=0;
485 reconnect:
486 $Zconnauthority=C4::Context->Zconnauth("authorityserver");
487 if ($Zconnauthority ne "error"){
488 my      $record = AUTHgetauthority($dbh,$authid);
489 my $Zpackage = $Zconnauthority->package();
490 $Zpackage->option(action => $op);
491         $Zpackage->option(record => $record->as_xml_record);
492 retry:
493         eval {
494                 $Zpackage->send("update");
495         };
496         if ($@) {
497                 if($@->code()==10007 && $tried==0){ ##Timedout -retry
498                 $tried=1;
499                 goto "retry";
500                 }elsif($@->code()==10004 && $recon==0){##Lost connection -reconnect
501                 $recon=1;
502                 goto "reconnect";
503                 }else{
504                 warn "Error-authority updating $authid $op /CODE:", $@->code()," /MSG:",$@->message(),"\n";     
505                 zebrafiles($dbh,$authid,$op);
506                 return;
507                 }
508         }
509 $Zpackage->("commit") if (C4::Context->shadow); 
510 $Zpackage->destroy;
511 }else{
512 zebrafiles($dbh,$authid,$op);
513 }       
514 }
515
516 sub zebrafiles{
517
518 my ($dbh,$authid,$folder)=@_;
519 my $record=AUTHgetauthority($dbh,$authid);
520 my $zebradir = C4::Context->zebraconfig("authorityserver")->{directory}."/".$folder."/";
521         
522 #my $zebradir = C4::Context->authoritydir."/".$folder."/";
523         unless (opendir(DIR, "$zebradir")) {
524 warn "$zebradir not found";
525                         return;
526         } 
527         closedir DIR;
528         my $filename = $zebradir.$authid;
529 if ($record){
530         open (OUTPUT,">", $filename.".xml");
531         print OUTPUT $record->as_xml_record;
532
533         close OUTPUT;
534 }
535
536
537 }
538
539
540 sub AUTHfind_leader{
541 ##Hard coded for NEU auth types 
542 my($dbh,$authtypecode)=@_;
543
544 my $leadercode;
545 if ($authtypecode eq "AUTH"){
546 $leadercode="a";
547 }elsif ($authtypecode eq "ESUB"){
548 $leadercode="b";
549 }elsif ($authtypecode eq "TSUB"){
550 $leadercode="c";
551 }else{
552 $leadercode=" ";
553 }
554 return $leadercode;
555 }
556
557 sub AUTHgetauthority {
558 # Returns MARC::Record of the biblio passed in parameter.
559     my ($dbh,$authid)=@_;
560 my      $sth=$dbh->prepare("select marc from auth_header where authid=?");
561                 $sth->execute($authid);
562         my ($marc) = $sth->fetchrow; 
563 my $record=MARC::File::USMARC::decode($marc);
564
565         return ($record);
566 }
567
568 sub AUTHgetauth_type {
569         my ($authtypecode) = @_;
570         my $dbh=C4::Context->dbh;
571         my $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
572         $sth->execute($authtypecode);
573         return $sth->fetchrow_hashref;
574 }
575 sub AUTHmodauthority {
576
577         my ($dbh,$authid,$record,$authtypecode,$merge)=@_;
578         my ($oldrecord)=&AUTHgetauthority($dbh,$authid);
579         if ($oldrecord eq $record) {
580                 return;
581         }
582 my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
583 #warn find if linked records exist and delete them
584 my($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$authtypecode);
585
586 if ($oldrecord->field($linkidfield)){
587 my @fields=$oldrecord->field($linkidfield);
588         foreach my $field (@fields){
589 my      $linkid=$field->subfield($linkidsubfield) ;
590         if ($linkid){                   
591                 ##Modify the record of linked 
592                 my $linkrecord=AUTHgetauthority($dbh,$linkid);
593                 my $linktypecode=AUTHfind_authtypecode($dbh,$linkid);
594                 my ( $linkidfield2,$linkidsubfield2)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$linktypecode);
595                 my @linkfields=$linkrecord->field($linkidfield2);
596                         foreach my $linkfield (@linkfields){
597                         if ($linkfield->subfield($linkidsubfield2) eq $authid){
598                                 $linkrecord->delete_field($linkfield);
599                                 $sth->execute($linkrecord->as_usmarc,$linkid);
600                                 zebraopauth($dbh,$linkid,'specialUpdate');
601                         }
602                         }#foreach linkfield
603         }
604         }#foreach linkid
605 }
606 #Now rewrite the $record to table with an add
607 $authid=AUTHaddauthority($dbh,$record,$authid,$authtypecode);
608
609 ##Uncomment below and all biblios will get updated with modified authority-- To be used with $merge flag
610 #       &merge($dbh,$authid,$record,$authid,$record);
611 return $authid;
612 }
613
614 sub AUTHdelauthority {
615         my ($dbh,$authid,$keep_biblio) = @_;
616 # if the keep_biblio is set to 1, then authority entries in biblio are preserved.
617
618 zebraopauth($dbh,$authid,"recordDelete");
619         $dbh->do("delete from auth_header where authid=$authid") ;
620
621 # FIXME : delete or not in biblio tables (depending on $keep_biblio flag)
622 }
623
624
625
626 sub AUTHfind_authtypecode {
627         my ($dbh,$authid) = @_;
628         my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
629         $sth->execute($authid);
630         my ($authtypecode) = $sth->fetchrow;
631         return $authtypecode;
632 }
633
634
635
636 sub AUTHhtml2marc {
637         my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
638         my $prevtag = -1;
639         my $record = MARC::Record->new();
640 #---- TODO : the leader is missing
641
642 #       my %subfieldlist=();
643         my $prevvalue; # if tag <10
644         my $field; # if tag >=10
645         for (my $i=0; $i< @$rtags; $i++) {
646                 # rebuild MARC::Record
647                 if (@$rtags[$i] ne $prevtag) {
648                         if ($prevtag < 10) {
649                                 if ($prevvalue) {
650                                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
651                                 }
652                         } else {
653                                 if ($field) {
654                                         $record->add_fields($field);
655                                 }
656                         }
657                         $indicators{@$rtags[$i]}.='  ';
658                         if (@$rtags[$i] <10) {
659                                 $prevvalue= @$rvalues[$i];
660                                 undef $field;
661                         } else {
662                                 undef $prevvalue;
663                                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
664                         }
665                         $prevtag = @$rtags[$i];
666                 } else {
667                         if (@$rtags[$i] <10) {
668                                 $prevvalue=@$rvalues[$i];
669                         } else {
670                                 if (length(@$rvalues[$i])>0) {
671                                         $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
672                                 }
673                         }
674                         $prevtag= @$rtags[$i];
675                 }
676         }
677         # the last has not been included inside the loop... do it now !
678         $record->add_fields($field) if $field;
679         return $record;
680 }
681
682
683
684
685 sub FindDuplicate {
686
687         my ($record,$authtypecode)=@_;
688 #       warn "IN for ".$record->as_formatted;
689         my $dbh = C4::Context->dbh;
690 #       warn "".$record->as_formatted;
691         my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
692         $sth->execute($authtypecode);
693         my ($auth_tag_to_report) = $sth->fetchrow;
694         $sth->finish;
695         # build a request for authoritysearch
696         my (@tags, @and_or, @excluding, @operator, @value, $offset, $length);
697         if ($record->field($auth_tag_to_report)) {
698                                 push @tags, $auth_tag_to_report;
699                                 push @and_or, "";
700                                 push @excluding, "";
701                                 push @operator, "all";
702                                 push @value, $record->field($auth_tag_to_report)->as_string();
703                         }
704  
705         my ($finalresult,$nbresult) = authoritysearch($dbh,\@tags,\@and_or,\@excluding,\@operator,\@value,0,10,$authtypecode);
706         # there is at least 1 result => return the 1st one
707         if ($nbresult>0) {
708                 return @$finalresult[0]->{authid},@$finalresult[0]->{summary};
709         }
710         # no result, returns nothing
711         return;
712 }
713
714 sub getsummary{
715 ## give this a Marc record to return summary
716 my ($dbh,$record,$authid,$authtypecode)=@_;
717
718 # my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
719  my $authref = getauthtype($authtypecode);
720                 my $summary = $authref->{summary};
721                 my @fields = $record->fields();
722 #               chop $tags_using_authtype;
723                 # if the library has a summary defined, use it. Otherwise, build a standard one
724                 if ($summary) {
725                         my @fields = $record->fields();
726                         foreach my $field (@fields) {
727                                 my $tag = $field->tag();
728                                 my $tagvalue = $field->as_string();
729                                 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
730                                 if ($tag<10) {
731                                 } else {
732                                         my @subf = $field->subfields;
733                                         for my $i (0..$#subf) {
734                                                 my $subfieldcode = $subf[$i][0];
735                                                 my $subfieldvalue = $subf[$i][1];
736                                                 my $tagsubf = $tag.$subfieldcode;
737                                                 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
738                                         }
739                                 }
740                         }
741                         $summary =~ s/\[(.*?)]//g;
742                         $summary =~ s/\n/<br>/g;
743                 } else {
744                         my $heading; # = $authref->{summary};
745                         my $altheading;
746                         my $seeheading;
747                         my $see;
748                         my @fields = $record->fields();
749                         if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
750                         # construct UNIMARC summary, that is quite different from MARC21 one
751                                 # accepted form
752                                 foreach my $field ($record->field('2..')) {
753                                         $heading.= $field->as_string();
754                                 }
755                                 # rejected form(s)
756                                 foreach my $field ($record->field('4..')) {
757                                         $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
758                                         $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
759                                 }
760                                 # see :
761                                 foreach my $field ($record->field('5..')) {
762                                         $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
763                                         $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
764                                 }
765                                 # // form
766                                 foreach my $field ($record->field('7..')) {
767                                         $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";     
768                                         $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
769                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$heading."<br />";
770                                 }
771                                 $summary = "<b>".$heading."</b><br />".$seeheading.$altheading.$summary;        
772                         } else {
773                         # construct MARC21 summary
774                                 foreach my $field ($record->field('1..')) {
775                                         if ($record->field('100')) {
776                                                 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
777                                         } elsif ($record->field('110')) {
778                                                 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
779                                         } elsif ($record->field('111')) {
780                                                 $heading.= $field->as_string('acdefghklnpqstvxyz68');
781                                         } elsif ($record->field('130')) {
782                                                 $heading.= $field->as_string('adfghklmnoprstvxyz68');
783                                         } elsif ($record->field('148')) {
784                                                 $heading.= $field->as_string('abvxyz68');
785                                         } elsif ($record->field('150')) {
786                                         $heading.= $field->as_string('abvxyz68');       
787                                         } elsif ($record->field('151')) {
788                                                 $heading.= $field->as_string('avxyz68');
789                                         } elsif ($record->field('155')) {
790                                                 $heading.= $field->as_string('abvxyz68');
791                                         } elsif ($record->field('180')) {
792                                                 $heading.= $field->as_string('vxyz68');
793                                         } elsif ($record->field('181')) {
794                                                 $heading.= $field->as_string('vxyz68');
795                                         } elsif ($record->field('182')) {
796                                                 $heading.= $field->as_string('vxyz68');
797                                         } elsif ($record->field('185')) {
798                                                 $heading.= $field->as_string('vxyz68');
799                                         } else {
800                                                 $heading.= $field->as_string();
801                                         }
802                                 } #See From
803                                 foreach my $field ($record->field('4..')) {
804                                         $seeheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
805                                         $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$seeheading."<br />";  
806                                 } #See Also
807                                 foreach my $field ($record->field('5..')) {
808                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";     
809                                         $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
810                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$altheading."<br />";
811                                 }
812                                 $summary.=$heading.$seeheading.$altheading;
813                         }
814                 }
815 return $summary;
816 }
817 sub merge {
818         my ($dbh,$mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
819         my $authtypecodefrom = AUTHfind_authtypecode($dbh,$mergefrom);
820         my $authtypecodeto = AUTHfind_authtypecode($dbh,$mergeto);
821         # return if authority does not exist
822         my @X = $MARCfrom->fields();
823         return if $#X == -1;
824         my @X = $MARCto->fields();
825         return if $#X == -1;
826         
827         
828         # search the tag to report
829         my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
830         $sth->execute($authtypecodefrom);
831         my ($auth_tag_to_report) = $sth->fetchrow;
832
833         my @record_to;
834         @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
835         my @record_from;
836         @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
837         
838         # search all biblio tags using this authority.
839         $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
840         $sth->execute($authtypecodefrom);
841 my @tags_using_authtype;
842         while (my ($tagfield) = $sth->fetchrow) {
843                 push @tags_using_authtype,$tagfield."9" ;
844         }
845
846         # now, find every biblio using this authority
847 ### try ZOOM search here
848 my $oConnection=C4::Context->Zconn("biblioserver");
849
850
851 my $query;
852
853 $query= "\@attr GILS 1=2057 ".$mergefrom;
854
855 my $oResult = $oConnection->search_pqf($query);
856
857 my $count=$oResult->size() if  ($oResult);
858 my @reccache;
859 my $z=0;
860 while ( $z<$count ) {
861
862 my $rec;
863  
864                  $rec=$oResult->record($z);
865
866         
867         my $marcdata = $rec->raw();
868 push @reccache, $marcdata;
869 $z++;
870 }
871 $oResult->destroy();
872 foreach my $marc(@reccache){
873
874 my $update;
875         my $marcrecord;                                 
876         $marcrecord = MARC::File::USMARC::decode($marc);
877         foreach my $tagfield (@tags_using_authtype){
878         $tagfield=substr($tagfield,0,3);
879                 my @tags = $marcrecord->field($tagfield);
880                 foreach my $tag (@tags){
881                         my $tagsubs=$tag->subfield("9");
882 #warn "$tagfield:$tagsubs:$mergefrom";
883                         if ($tagsubs== $mergefrom) {
884                
885                         $tag->update("9" =>$mergeto);
886         foreach my $subfield (@record_to) {
887 #               warn "$subfield,$subfield->[0],$subfield->[1]";
888                         $tag->update($subfield->[0] =>$subfield->[1]);
889                         }#for $subfield
890                 }
891                 $marcrecord->delete_field($tag);
892                 $marcrecord->add_fields($tag);
893                 $update=1;
894                 }#for each tag
895         }#foreach tagfield
896 my $oldbiblio = MARCmarc2koha($dbh,$marcrecord,"") ;
897                 if ($update==1){
898                 &NEWmodbiblio($dbh,$marcrecord,$oldbiblio->{'biblionumber'},undef,"0000") ;
899                 }
900                 
901 }#foreach $marc
902 }#sub
903 END { }       # module clean-up code here (global destructor)
904
905 =back
906
907 =head1 AUTHOR
908
909 Koha Developement team <info@koha.org>
910
911 Paul POULAIN paul.poulain@free.fr
912
913 =cut
914
915 # $Id$
916 # $Log$
917 # Revision 1.25  2006/05/19 18:09:39  tgarip1957
918 # All support for auth_subfield_tables is removed. All search is now with zebra authorities. New authority structure allows multiple linking of authorities of differnet types to one another.
919 # Authority tables are modified to be compatible with new MARC frameworks. This change is part of Authority Linking & Zebra authorities. Requires change in Mysql database. It will break head unless all changes regarding this is implemented. This warning will take place on all commits regarding this
920 #
921 # Revision 1.9.2.6  2005/06/07 10:02:00  tipaul
922 # porting dictionnary search from head to 2.2. there is now a ... facing titles, author & subject, to search in biblio & authorities existing values.
923 #
924 # Revision 1.9.2.5  2005/05/31 14:50:46  tipaul
925 # fix for authority merging. There was a bug on official installs
926 #
927 # Revision 1.9.2.4  2005/05/30 11:24:15  tipaul
928 # fixing a bug : when a field was repeated, the last field was also repeated. (Was due to the "empty" field in html between fields : to separate fields, in html, an empty field is automatically added. in AUTHhtml2marc, this empty field was not discarded correctly)
929 #
930 # Revision 1.9.2.3  2005/04/28 08:45:33  tipaul
931 # porting FindDuplicate feature for authorities from HEAD to rel_2_2, works correctly now.
932 #
933 # Revision 1.9.2.2  2005/02/28 14:03:13  tipaul
934 # * adding search on "main entry" (ie $a subfield) on a given authority (the "search everywhere" field is still here).
935 # * adding a select box to requet "contain" or "begin with" search.
936 # * fixing some bug in authority search (related to "main entry" search)
937 #
938 # Revision 1.9.2.1  2005/02/24 13:12:13  tipaul
939 # saving authority modif in a text file. This will be used soon with another script (in crontab). The script in crontab will retrieve every authorityid in the directory localfile/authorities and modify every biblio using this authority. Those modifs may be long. So they can't be done through http, because we may encounter a webserver timeout, and kill the process before end of the job.
940 # So, it will be done through a cron job.
941 # (/me agree we need some doc for command line scripts)
942 #
943 # Revision 1.9  2004/12/23 09:48:11  tipaul
944 # Minor changes in summary "exploding" (the 3 digits AFTER the subfield were not on the right place).
945 #
946 # Revision 1.8  2004/11/05 10:11:39  tipaul
947 # export auth_count_usage (bugfix)
948 #
949 # Revision 1.7  2004/09/23 16:13:00  tipaul
950 # Bugfix in modification
951 #
952 # Revision 1.6  2004/08/18 16:00:24  tipaul
953 # fixes for authorities management
954 #
955 # Revision 1.5  2004/07/05 13:37:22  doxulting
956 # First step for working authorities
957 #
958 # Revision 1.4  2004/06/22 11:35:37  tipaul
959 # removing % at the beginning of a string to avoid loooonnnngggg searchs
960 #
961 # Revision 1.3  2004/06/17 08:02:13  tipaul
962 # merging tag & subfield in auth_word for better perfs
963 #
964 # Revision 1.2  2004/06/10 08:29:01  tipaul
965 # MARC authority management (continued)
966 #
967 # Revision 1.1  2004/06/07 07:35:01  tipaul
968 # MARC authority management package
969 #