add call to doc-head-open.inc and doc-head-close.inc
[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->authorityservershadow);  
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
610 ### 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
611 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
612 ### the $merge flag is now depreceated and will be removed at code cleaning
613
614 if (C4::Context->preference('dontmerge')){
615 # save the file in localfile/modified_authorities
616         my $cgidir = C4::Context->intranetdir ."/cgi-bin";
617         unless (opendir(DIR, "$cgidir")) {
618                         $cgidir = C4::Context->intranetdir."/";
619         } 
620
621         my $filename = $cgidir."/localfile/modified_authorities/$authid.authid";
622         open AUTH, "> $filename";
623         print AUTH $authid;
624         close AUTH;
625 }else{
626         &merge($dbh,$authid,$record,$authid,$record);
627 }
628 return $authid;
629 }
630
631 sub AUTHdelauthority {
632         my ($dbh,$authid,$keep_biblio) = @_;
633 # if the keep_biblio is set to 1, then authority entries in biblio are preserved.
634
635 zebraopauth($dbh,$authid,"recordDelete");
636         $dbh->do("delete from auth_header where authid=$authid") ;
637
638 # FIXME : delete or not in biblio tables (depending on $keep_biblio flag)
639 }
640
641
642
643 sub AUTHfind_authtypecode {
644         my ($dbh,$authid) = @_;
645         my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
646         $sth->execute($authid);
647         my ($authtypecode) = $sth->fetchrow;
648         return $authtypecode;
649 }
650
651
652
653 sub AUTHhtml2marc {
654         my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
655         my $prevtag = -1;
656         my $record = MARC::Record->new();
657 #---- TODO : the leader is missing
658
659 #       my %subfieldlist=();
660         my $prevvalue; # if tag <10
661         my $field; # if tag >=10
662         for (my $i=0; $i< @$rtags; $i++) {
663                 # rebuild MARC::Record
664                 if (@$rtags[$i] ne $prevtag) {
665                         if ($prevtag < 10) {
666                                 if ($prevvalue) {
667                                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
668                                 }
669                         } else {
670                                 if ($field) {
671                                         $record->add_fields($field);
672                                 }
673                         }
674                         $indicators{@$rtags[$i]}.='  ';
675                         if (@$rtags[$i] <10) {
676                                 $prevvalue= @$rvalues[$i];
677                                 undef $field;
678                         } else {
679                                 undef $prevvalue;
680                                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
681                         }
682                         $prevtag = @$rtags[$i];
683                 } else {
684                         if (@$rtags[$i] <10) {
685                                 $prevvalue=@$rvalues[$i];
686                         } else {
687                                 if (length(@$rvalues[$i])>0) {
688                                         $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
689                                 }
690                         }
691                         $prevtag= @$rtags[$i];
692                 }
693         }
694         # the last has not been included inside the loop... do it now !
695         $record->add_fields($field) if $field;
696         return $record;
697 }
698
699
700
701
702 sub FindDuplicate {
703
704         my ($record,$authtypecode)=@_;
705 #       warn "IN for ".$record->as_formatted;
706         my $dbh = C4::Context->dbh;
707 #       warn "".$record->as_formatted;
708         my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
709         $sth->execute($authtypecode);
710         my ($auth_tag_to_report) = $sth->fetchrow;
711         $sth->finish;
712         # build a request for authoritysearch
713         my (@tags, @and_or, @excluding, @operator, @value, $offset, $length);
714         if ($record->field($auth_tag_to_report)) {
715                                 push @tags, $auth_tag_to_report;
716                                 push @and_or, "";
717                                 push @excluding, "";
718                                 push @operator, "all";
719                                 push @value, $record->field($auth_tag_to_report)->as_string();
720                         }
721  
722         my ($finalresult,$nbresult) = authoritysearch($dbh,\@tags,\@and_or,\@excluding,\@operator,\@value,0,10,$authtypecode);
723         # there is at least 1 result => return the 1st one
724         if ($nbresult>0) {
725                 return @$finalresult[0]->{authid},@$finalresult[0]->{summary};
726         }
727         # no result, returns nothing
728         return;
729 }
730
731 sub getsummary{
732 ## give this a Marc record to return summary
733 my ($dbh,$record,$authid,$authtypecode)=@_;
734
735 # my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
736  my $authref = getauthtype($authtypecode);
737                 my $summary = $authref->{summary};
738                 my @fields = $record->fields();
739 #               chop $tags_using_authtype;
740                 # if the library has a summary defined, use it. Otherwise, build a standard one
741                 if ($summary) {
742                         my @fields = $record->fields();
743                         foreach my $field (@fields) {
744                                 my $tag = $field->tag();
745                                 my $tagvalue = $field->as_string();
746                                 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
747                                 if ($tag<10) {
748                                 } else {
749                                         my @subf = $field->subfields;
750                                         for my $i (0..$#subf) {
751                                                 my $subfieldcode = $subf[$i][0];
752                                                 my $subfieldvalue = $subf[$i][1];
753                                                 my $tagsubf = $tag.$subfieldcode;
754                                                 $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
755                                         }
756                                 }
757                         }
758                         $summary =~ s/\[(.*?)]//g;
759                         $summary =~ s/\n/<br>/g;
760                 } else {
761                         my $heading; # = $authref->{summary};
762                         my $altheading;
763                         my $seeheading;
764                         my $see;
765                         my @fields = $record->fields();
766                         if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
767                         # construct UNIMARC summary, that is quite different from MARC21 one
768                                 # accepted form
769                                 foreach my $field ($record->field('2..')) {
770                                         $heading.= $field->as_string();
771                                 }
772                                 # rejected form(s)
773                                 foreach my $field ($record->field('4..')) {
774                                         $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
775                                         $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
776                                 }
777                                 # see :
778                                 foreach my $field ($record->field('5..')) {
779                                         $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
780                                         $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
781                                 }
782                                 # // form
783                                 foreach my $field ($record->field('7..')) {
784                                         $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";     
785                                         $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
786                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$heading."<br />";
787                                 }
788                                 $summary = "<b>".$heading."</b><br />".$seeheading.$altheading.$summary;        
789                         } else {
790                         # construct MARC21 summary
791                                 foreach my $field ($record->field('1..')) {
792                                         if ($record->field('100')) {
793                                                 $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
794                                         } elsif ($record->field('110')) {
795                                                 $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
796                                         } elsif ($record->field('111')) {
797                                                 $heading.= $field->as_string('acdefghklnpqstvxyz68');
798                                         } elsif ($record->field('130')) {
799                                                 $heading.= $field->as_string('adfghklmnoprstvxyz68');
800                                         } elsif ($record->field('148')) {
801                                                 $heading.= $field->as_string('abvxyz68');
802                                         } elsif ($record->field('150')) {
803                                         $heading.= $field->as_string('abvxyz68');       
804                                         } elsif ($record->field('151')) {
805                                                 $heading.= $field->as_string('avxyz68');
806                                         } elsif ($record->field('155')) {
807                                                 $heading.= $field->as_string('abvxyz68');
808                                         } elsif ($record->field('180')) {
809                                                 $heading.= $field->as_string('vxyz68');
810                                         } elsif ($record->field('181')) {
811                                                 $heading.= $field->as_string('vxyz68');
812                                         } elsif ($record->field('182')) {
813                                                 $heading.= $field->as_string('vxyz68');
814                                         } elsif ($record->field('185')) {
815                                                 $heading.= $field->as_string('vxyz68');
816                                         } else {
817                                                 $heading.= $field->as_string();
818                                         }
819                                 } #See From
820                                 foreach my $field ($record->field('4..')) {
821                                         $seeheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
822                                         $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$seeheading."<br />";  
823                                 } #See Also
824                                 foreach my $field ($record->field('5..')) {
825                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";     
826                                         $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
827                                         $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$altheading."<br />";
828                                 }
829                                 $summary.=$heading.$seeheading.$altheading;
830                         }
831                 }
832 return $summary;
833 }
834 sub merge {
835         my ($dbh,$mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
836         my $authtypecodefrom = AUTHfind_authtypecode($dbh,$mergefrom);
837         my $authtypecodeto = AUTHfind_authtypecode($dbh,$mergeto);
838         # return if authority does not exist
839         my @X = $MARCfrom->fields();
840         return if $#X == -1;
841         my @X = $MARCto->fields();
842         return if $#X == -1;
843         
844         
845         # search the tag to report
846         my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
847         $sth->execute($authtypecodefrom);
848         my ($auth_tag_to_report) = $sth->fetchrow;
849
850         my @record_to;
851         @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
852         my @record_from;
853         @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
854         
855         # search all biblio tags using this authority.
856         $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
857         $sth->execute($authtypecodefrom);
858 my @tags_using_authtype;
859         while (my ($tagfield) = $sth->fetchrow) {
860                 push @tags_using_authtype,$tagfield."9" ;
861         }
862
863         # now, find every biblio using this authority
864 ### try ZOOM search here
865 my $oConnection=C4::Context->Zconn("biblioserver");
866
867
868 my $query;
869
870 $query= "\@attr GILS 1=2057 ".$mergefrom;
871
872 my $oResult = $oConnection->search_pqf($query);
873
874 my $count=$oResult->size() if  ($oResult);
875 my @reccache;
876 my $z=0;
877 while ( $z<$count ) {
878
879 my $rec;
880  
881                  $rec=$oResult->record($z);
882
883         
884         my $marcdata = $rec->raw();
885 push @reccache, $marcdata;
886 $z++;
887 }
888 $oResult->destroy();
889 foreach my $marc(@reccache){
890
891 my $update;
892         my $marcrecord;                                 
893         $marcrecord = MARC::File::USMARC::decode($marc);
894         foreach my $tagfield (@tags_using_authtype){
895         $tagfield=substr($tagfield,0,3);
896                 my @tags = $marcrecord->field($tagfield);
897                 foreach my $tag (@tags){
898                         my $tagsubs=$tag->subfield("9");
899 #warn "$tagfield:$tagsubs:$mergefrom";
900                         if ($tagsubs== $mergefrom) {
901                
902                         $tag->update("9" =>$mergeto);
903         foreach my $subfield (@record_to) {
904 #               warn "$subfield,$subfield->[0],$subfield->[1]";
905                         $tag->update($subfield->[0] =>$subfield->[1]);
906                         }#for $subfield
907                 }
908                 $marcrecord->delete_field($tag);
909                 $marcrecord->add_fields($tag);
910                 $update=1;
911                 }#for each tag
912         }#foreach tagfield
913 my $oldbiblio = MARCmarc2koha($dbh,$marcrecord,"") ;
914                 if ($update==1){
915                 &NEWmodbiblio($dbh,$marcrecord,$oldbiblio->{'biblionumber'},undef,"0000") ;
916                 }
917                 
918 }#foreach $marc
919 }#sub
920 END { }       # module clean-up code here (global destructor)
921
922 =back
923
924 =head1 AUTHOR
925
926 Koha Developement team <info@koha.org>
927
928 Paul POULAIN paul.poulain@free.fr
929
930 =cut
931
932 # $Id$
933 # $Log$
934 # Revision 1.26  2006/05/20 14:32:54  tgarip1957
935 # If an authority is modified biblios related to this authority were not updated but a list of modified authorities was written to disk. Now by defult they get modified as well unless a system preference 'dontmerge' is defined. dontmerge=1 will keep the previous behaviour.
936 #
937 # Authority zebra server may have different shadow settings. Support is added
938 #
939 # Revision 1.25  2006/05/19 18:09:39  tgarip1957
940 # 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.
941 # 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
942 #
943 # Revision 1.9.2.6  2005/06/07 10:02:00  tipaul
944 # porting dictionnary search from head to 2.2. there is now a ... facing titles, author & subject, to search in biblio & authorities existing values.
945 #
946 # Revision 1.9.2.5  2005/05/31 14:50:46  tipaul
947 # fix for authority merging. There was a bug on official installs
948 #
949 # Revision 1.9.2.4  2005/05/30 11:24:15  tipaul
950 # 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)
951 #
952 # Revision 1.9.2.3  2005/04/28 08:45:33  tipaul
953 # porting FindDuplicate feature for authorities from HEAD to rel_2_2, works correctly now.
954 #
955 # Revision 1.9.2.2  2005/02/28 14:03:13  tipaul
956 # * adding search on "main entry" (ie $a subfield) on a given authority (the "search everywhere" field is still here).
957 # * adding a select box to requet "contain" or "begin with" search.
958 # * fixing some bug in authority search (related to "main entry" search)
959 #
960 # Revision 1.9.2.1  2005/02/24 13:12:13  tipaul
961 # 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.
962 # So, it will be done through a cron job.
963 # (/me agree we need some doc for command line scripts)
964 #
965 # Revision 1.9  2004/12/23 09:48:11  tipaul
966 # Minor changes in summary "exploding" (the 3 digits AFTER the subfield were not on the right place).
967 #
968 # Revision 1.8  2004/11/05 10:11:39  tipaul
969 # export auth_count_usage (bugfix)
970 #
971 # Revision 1.7  2004/09/23 16:13:00  tipaul
972 # Bugfix in modification
973 #
974 # Revision 1.6  2004/08/18 16:00:24  tipaul
975 # fixes for authorities management
976 #
977 # Revision 1.5  2004/07/05 13:37:22  doxulting
978 # First step for working authorities
979 #
980 # Revision 1.4  2004/06/22 11:35:37  tipaul
981 # removing % at the beginning of a string to avoid loooonnnngggg searchs
982 #
983 # Revision 1.3  2004/06/17 08:02:13  tipaul
984 # merging tag & subfield in auth_word for better perfs
985 #
986 # Revision 1.2  2004/06/10 08:29:01  tipaul
987 # MARC authority management (continued)
988 #
989 # Revision 1.1  2004/06/07 07:35:01  tipaul
990 # MARC authority management package
991 #