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