removing $dbh as a parameter in AuthoritiesMarc functions
[koha.git] / C4 / AuthoritiesMarc.pm
1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
3 #
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19 use strict;
20 require Exporter;
21 use C4::Context;
22 use C4::Koha;
23 use MARC::Record;
24 use C4::Biblio;
25 use C4::Search;
26 #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     &BuildUnimarcHierarchies
52     &BuildUnimarcHierarchy
53     &merge
54     &FindDuplicate
55  );
56
57 sub AUTHfind_marc_from_kohafield {
58   my ( $kohafield,$authtypecode ) = @_;
59   my $dbh=C4::Context->dbh;
60   return 0, 0 unless $kohafield;
61   $authtypecode="" unless $authtypecode;
62   my $marcfromkohafield;
63   my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? ");
64   $sth->execute($kohafield,$authtypecode);
65   my ($tagfield,$tagsubfield) = $sth->fetchrow;
66     
67   return  ($tagfield,$tagsubfield);
68 }
69 sub authoritysearch {
70   my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby) = @_;
71   my $dbh=C4::Context->dbh;
72   my $query;
73   my $attr;
74     # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
75     # the authtypecode. Then, search on $a of this tag_to_report
76     # also store main entry MARC tag, to extract it at end of search
77   my $mainentrytag;
78   ##first set the authtype search and may be multiple authorities
79   my $n=0;
80   my @authtypecode;
81   my @auths=split / /,$authtypecode ;
82   foreach my  $auth (@auths){
83     $query .=" \@attr 1=Authority/format-id \@attr 5=100 ".$auth; ##No truncation on authtype
84     push @authtypecode ,$auth;
85     $n++;
86   }
87   if ($n>1){
88     $query= "\@or ".$query;
89   }
90   
91   my $dosearch;
92   my $and;
93   my $q2;
94   for(my $i = 0 ; $i <= $#{$value} ; $i++)
95   {
96     if (@$value[$i]){
97     ##If mainentry search $a tag
98         if (@$tags[$i] eq "mainmainentry") {
99           $attr =" \@attr 1=Heading ";
100         }elsif (@$tags[$i] eq "mainentry") {
101           $attr =" \@attr 1=Heading-Entity ";
102         }else{
103           $attr =" \@attr 1=Any ";
104         }
105         if (@$operator[$i] eq 'is') {
106             $attr.=" \@attr 4=1  \@attr 5=100 ";##Phrase, No truncation,all of subfield field must match
107         }elsif (@$operator[$i] eq "="){
108             $attr.=" \@attr 4=107 ";           #Number Exact match
109         }elsif (@$operator[$i] eq "start"){
110             $attr.=" \@attr 4=1 \@attr 5=1 ";#Phrase, Right truncated
111         } else {
112             $attr .=" \@attr 5=1  ";## Word list, right truncated, anywhere
113         }
114         $and .=" \@and " ;
115         $attr =$attr."\"".@$value[$i]."\"";
116         $q2 .=$attr;
117     $dosearch=1;
118     }#if value
119   }
120   ##Add how many queries generated
121   $query= $and.$query.$q2;
122   $query=' @or  @attr 7=1 @attr 1=Heading 0 '.$query if ($sortby eq "HeadingAsc");
123   $query=' @or  @attr 7=2 @attr 1=Heading 0 '.$query if ($sortby eq "HeadingDsc");
124   warn $query;
125   
126   $offset=0 unless $offset;
127   my $counter = $offset;
128   $length=10 unless $length;
129   my @oAuth;
130   my $i;
131   $oAuth[0]=C4::Context->Zconn("authorityserver" , 1);
132   my $Anewq= new ZOOM::Query::PQF($query,$oAuth[0]);
133   # $Anewq->sortby("1=Heading i< 1=Heading-Entity i< ");
134   # $Anewq->sortby("1=Heading i< 1=Heading-Entity i< ");
135   my $oAResult;
136   $oAResult= $oAuth[0]->search($Anewq) ; 
137   while (($i = ZOOM::event(\@oAuth)) != 0) {
138       my $ev = $oAuth[$i-1]->last_event();
139   #    warn("Authority ", $i-1, ": event $ev (", ZOOM::event_str($ev), ")\n");
140       last if $ev == ZOOM::Event::ZEND;
141   }
142   my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x();
143   if ($error) {
144     warn  "oAuth error: $errmsg ($error) $addinfo $diagset\n";
145     goto NOLUCK;
146   }
147
148   my $nbresults;
149   $nbresults=$oAResult->size();
150   my $nremains=$nbresults;    
151   my @result = ();
152   my @finalresult = ();
153
154   if ($nbresults>0){
155
156   ##Find authid and linkid fields
157   ##we may be searching multiple authoritytypes.
158   ## FIXME this assumes that all authid and linkid fields are the same for all authority types
159   # my ($authidfield,$authidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authid",$authtypecode[0]);
160   # my ($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$authtypecode[0]);
161     while (($counter < $nbresults) && ($counter < ($offset + $length))) {
162     
163       ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES
164       my $rec=$oAResult->record($counter);
165       my $marcdata=$rec->raw();
166       my $authrecord;    
167       my $linkid;
168       my @linkids;    
169       my $separator=C4::Context->preference('authoritysep');
170       my $linksummary=" ".$separator;    
171           
172           $authrecord = MARC::File::USMARC::decode($marcdata);
173               
174       my $authid=$authrecord->field('001')->data(); 
175       #     if ($authrecord->field($linkidfield)){
176       # my @fields=$authrecord->field($linkidfield);
177       # 
178       # #     foreach my $field (@fields){
179       # # #     $linkid=$field->subfield($linkidsubfield) ;
180       # # #         if ($linkid){ ##There is a linked record add fields to produce summary
181       # # # my $linktype=AUTHfind_authtypecode($dbh,$linkid);
182       # # #         my $linkrecord=AUTHgetauthority($dbh,$linkid);
183       # # #         $linksummary.="<br>&nbsp;&nbsp;&nbsp;&nbsp;<a href='detail.pl?authid=$linkid'>".getsummary($dbh,$linkrecord,$linkid,$linktype).".</a>".$separator;
184       # # #         }
185       # #      }
186       #     }#
187       
188           my $summary=getsummary($authrecord,$authid,$authtypecode);
189   #         $summary="<a href='detail.pl?authid=$authid'>".$summary.".</a>" if ($intranet);
190   #         $summary="<a href='detail.pl?authid=$authid'>".$summary.".</a>" if ($intranet);
191       #     if ($linkid && $linksummary ne " ".$separator){
192       #         $summary="<b>".$summary."</b>".$linksummary;
193       #     }
194           my $query_auth_tag = "SELECT auth_tag_to_report FROM auth_types WHERE authtypecode=?";
195           my $sth = $dbh->prepare($query_auth_tag);
196           $sth->execute($authtypecode);
197           my $auth_tag_to_report = $sth->fetchrow;
198           my %newline;
199           $newline{summary} = $summary;
200           $newline{authid} = $authid;
201       #     $newline{linkid} = $linkid;
202       #      $newline{reported_tag} = $reported_tag;
203       #     $newline{used} =0;
204       #     $newline{biblio_fields} = $tags_using_authtype;
205           $newline{even} = $counter % 2;
206           $counter++;
207           push @finalresult, \%newline;
208     }## while counter
209   ###
210    for (my $z=0; $z<@finalresult; $z++){
211         my  $count=AUTHcount_usage($finalresult[$z]{authid});
212         $finalresult[$z]{used}=$count;
213    }# all $z's
214
215   }## if nbresult
216 NOLUCK:
217 # $oAResult->destroy();
218 # $oAuth[0]->destroy();
219
220     return (\@finalresult, $nbresults);
221 }
222
223 # Creates the SQL Request
224
225 sub create_request {
226     my ($tags, $and_or, $operator, $value) = @_;
227     my $dbh=C4::Context->dbh;
228
229     my $sql_tables; # will contain marc_subfield_table as m1,...
230     my $sql_where1; # will contain the "true" where
231     my $sql_where2 = "("; # will contain m1.authid=m2.authid
232     my $nb_active=0; # will contain the number of "active" entries. and entry is active is a value is provided.
233     my $nb_table=1; # will contain the number of table. ++ on each entry EXCEPT when an OR  is provided.
234
235     for(my $i=0; $i<=@$value;$i++) {
236       if (@$value[$i]) {
237         $nb_active++;
238         if ($nb_active==1) {
239           $sql_tables = "auth_subfield_table as m$nb_table,";
240           $sql_where1 .= "( m$nb_table.subfieldvalue like '@$value[$i]' ";
241           if (@$tags[$i]) {
242             $sql_where1 .=" and concat(m$nb_table.tag,m$nb_table.subfieldcode) IN (@$tags[$i])";
243           }
244           $sql_where1.=")";
245         } else {
246           $nb_table++;
247           $sql_tables .= "auth_subfield_table as m$nb_table,";
248           $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue   like '@$value[$i]' ";
249           if (@$tags[$i]) {
250               $sql_where1 .=" and concat(m$nb_table.tag,m$nb_table.subfieldcode) IN (@$tags[$i])";
251           }
252           $sql_where1.=")";
253           $sql_where2.="m1.authid=m$nb_table.authid and ";
254         }
255       }
256     }
257
258     if($sql_where2 ne "(")    # some datas added to sql_where2, processing
259     {
260         $sql_where2 = substr($sql_where2, 0, (length($sql_where2)-5)); # deletes the trailing ' and '
261         $sql_where2 .= ")";
262     }
263     else    # no sql_where2 statement, deleting '('
264     {
265         $sql_where2 = "";
266     }
267     chop $sql_tables;    # deletes the trailing ','
268     
269     return ($sql_tables, $sql_where1, $sql_where2);
270 }
271
272
273 sub AUTHcount_usage {
274   my ($authid) = @_;
275   ### try ZOOM search here
276   my $oConnection=C4::Context->Zconn("biblioserver",1);
277   my $query;
278   $query= "an=".$authid;
279   
280   my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
281   my $result;
282   while ((my $i = ZOOM::event([ $oConnection ])) != 0) {
283       my $ev = $oConnection->last_event();
284       if ($ev == ZOOM::Event::ZEND) {
285           $result = $oResult->size();
286       }
287   }
288   return ($result);
289 }
290
291
292
293 sub AUTHfind_authtypecode {
294   my ($authid) = @_;
295   my $dbh=C4::Context->dbh;
296   my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
297   $sth->execute($authid);
298   my ($authtypecode) = $sth->fetchrow;
299   return $authtypecode;
300 }
301  
302
303 sub AUTHgettagslib {
304   my ($forlibrarian,$authtypecode)= @_;
305   my $dbh=C4::Context->dbh;
306   $authtypecode="" unless $authtypecode;
307   my $sth;
308   my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
309
310
311   # check that authority exists
312   $sth=$dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?");
313   $sth->execute($authtypecode);
314   my ($total) = $sth->fetchrow;
315   $authtypecode="" unless ($total >0);
316   $sth= $dbh->prepare(
317 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable 
318  FROM auth_tag_structure 
319  WHERE authtypecode=? 
320  ORDER BY tagfield"
321     );
322
323   $sth->execute($authtypecode);
324   my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
325
326   while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
327         $res->{$tag}->{lib}        = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
328         $res->{$tag}->{tab}        = " ";            # XXX
329         $res->{$tag}->{mandatory}  = $mandatory;
330         $res->{$tag}->{repeatable} = $repeatable;
331   }
332   $sth=      $dbh->prepare(
333 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl 
334 FROM auth_subfield_structure 
335 WHERE authtypecode=? 
336 ORDER BY tagfield,tagsubfield"
337     );
338     $sth->execute($authtypecode);
339
340     my $subfield;
341     my $authorised_value;
342     my $value_builder;
343     my $kohafield;
344     my $seealso;
345     my $hidden;
346     my $isurl;
347     my $link;
348
349     while (
350         ( $tag,         $subfield,   $liblibrarian,   , $libopac,      $tab,
351         $mandatory,     $repeatable, $authorised_value, $authtypecode,
352         $value_builder, $kohafield,  $seealso,          $hidden,
353         $isurl,            $link )
354         = $sth->fetchrow
355       )
356     {
357         $res->{$tag}->{$subfield}->{lib}              = ($forlibrarian or !$libopac)?$liblibrarian:$libopac;
358         $res->{$tag}->{$subfield}->{tab}              = $tab;
359         $res->{$tag}->{$subfield}->{mandatory}        = $mandatory;
360         $res->{$tag}->{$subfield}->{repeatable}       = $repeatable;
361         $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
362         $res->{$tag}->{$subfield}->{authtypecode}     = $authtypecode;
363         $res->{$tag}->{$subfield}->{value_builder}    = $value_builder;
364         $res->{$tag}->{$subfield}->{kohafield}        = $kohafield;
365         $res->{$tag}->{$subfield}->{seealso}          = $seealso;
366         $res->{$tag}->{$subfield}->{hidden}           = $hidden;
367         $res->{$tag}->{$subfield}->{isurl}            = $isurl;
368         $res->{$tag}->{$subfield}->{link}            = $link;
369     }
370     return $res;
371 }
372
373 sub AUTHaddauthority {
374 # pass the MARC::Record to this function, and it will create the records in the authority table
375   my ($record,$authid,$authtypecode) = @_;
376   my $dbh=C4::Context->dbh;
377 #my $leadercode=AUTHfind_leader($dbh,$authtypecode);
378   my $leader='         a              ';##Fixme correct leader as this one just adds utf8 to MARC21
379 #substr($leader,8,1)=$leadercode;
380 #    $record->leader($leader);
381 # my ($authfield,$authidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authid",$authtypecode);
382 # my ($authfield2,$authtypesubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.authtypecode",$authtypecode);
383 # my ($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield($dbh,"auth_header.linkid",$authtypecode);
384
385 # if authid empty => true add, find a new authid number
386   if (!$authid) {
387     my $sth=$dbh->prepare("select max(authid) from auth_header");
388     $sth->execute;
389     ($authid)=$sth->fetchrow;
390     $authid=$authid+1;
391   ##Insert the recordID in MARC record 
392   ##Both authid and authtypecode is expected to be in the same field. Modify if other requirements arise
393     $record->add_fields('001',$authid) unless $record->field('001');
394     $record->add_fields('152','','','b'=>$authtypecode) unless $record->field('152');
395     #           $record->add_fields('100','','','b'=>$authtypecode);
396     warn $record->as_formatted;
397     $dbh->do("lock tables auth_header WRITE");
398     $sth=$dbh->prepare("insert into auth_header (authid,datecreated,authtypecode,marc) values (?,now(),?,?)");
399     $sth->execute($authid,$authtypecode,$record->as_usmarc);    
400     $sth->finish;
401     
402   }else{
403       ##Modified record reinsertid
404 #       my $idfield=$record->field('001');
405 #       $record->delete_field($idfield);
406       $record->add_fields('001',$authid) unless ($record->field('001'));
407       $record->add_fields('152','','','b'=>$authtypecode) unless ($record->field('152'));
408 #       $record->add_fields($authfield,$authid);
409 #       $record->add_fields($authfield2,'','',$authtypesubfield=>$authtypecode);
410       warn $record->as_formatted;
411       $dbh->do("lock tables auth_header WRITE");
412       my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
413       $sth->execute($record->as_usmarc,$authid);
414       $sth->finish;
415     }
416     $dbh->do("unlock tables");
417     zebraop($authid,'specialUpdate',"authorityserver");
418
419 # if ($record->field($linkidfield)){
420 # my @fields=$record->field($linkidfield);
421
422 #     foreach my $field (@fields){
423 #      my $linkid=$field->subfield($linkidsubfield) ;
424 #        if ($linkid){
425 #     ##Modify the record of linked
426 #          AUTHaddlink($dbh,$linkid,$authid);
427 #        }
428 #     }
429 # }
430     return ($authid);
431 }
432
433 sub AUTHaddlink{
434   my ($linkid,$authid)=@_;
435   my $dbh=C4::Context->dbh;
436   my $record=AUTHgetauthority($linkid);
437   my $authtypecode=AUTHfind_authtypecode($linkid);
438 #warn "adding l:$linkid,a:$authid,auth:$authtypecode";
439   $record=AUTH2marcOnefieldlink($record,"auth_header.linkid",$authid,$authtypecode);
440   $dbh->do("lock tables auth_header WRITE");
441   my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
442   $sth->execute($record->as_usmarc,$linkid);
443   $sth->finish;
444   $dbh->do("unlock tables");
445   zebraop($linkid,'specialUpdate',"authorityserver");
446 }
447
448 sub AUTH2marcOnefieldlink {
449   my ( $record, $kohafieldname, $newvalue,$authtypecode ) = @_;
450   my $dbh=C4::Context->dbh;
451   my $sth =      $dbh->prepare(
452 "select tagfield,tagsubfield from auth_subfield_structure where authtypecode=? and kohafield=?"
453     );
454   $sth->execute($authtypecode,$kohafieldname);
455   my  ($tagfield,$tagsubfield)=$sth->fetchrow;
456   $record->add_fields( $tagfield, " ", " ", $tagsubfield => $newvalue );
457   return $record;
458 }
459
460 sub XMLgetauthority {
461
462     # Returns MARC::XML of the authority passed in parameter.
463   my ( $authid ) = @_;
464   my $dbh=C4::Context->dbh;
465   my $sth =
466       $dbh->prepare("select marc from auth_header where authid=? "  );
467   $sth->execute($authid);
468   my ($marc)=$sth->fetchrow;
469   $marc=MARC::File::USMARC::decode($marc);
470   my $marcxml=$marc->as_xml_record();
471   return $marcxml;
472
473 }
474
475
476 sub AUTHfind_leader{
477 ##Hard coded for NEU auth types 
478 my($authtypecode)=@_;
479
480 my $leadercode;
481 if ($authtypecode eq "AUTH"){
482 $leadercode="a";
483 }elsif ($authtypecode eq "ESUB"){
484 $leadercode="b";
485 }elsif ($authtypecode eq "TSUB"){
486 $leadercode="c";
487 }else{
488 $leadercode=" ";
489 }
490 return $leadercode;
491 }
492
493 sub AUTHgetauthority {
494 # Returns MARC::Record of the biblio passed in parameter.
495   my ($authid)=@_;
496   my $dbh=C4::Context->dbh;
497   my $sth=$dbh->prepare("select marc from auth_header where authid=?");
498   $sth->execute($authid);
499   my ($marc) = $sth->fetchrow;
500   my $record=MARC::File::USMARC::decode($marc);
501
502   return ($record);
503 }
504
505 sub AUTHgetauth_type {
506     my ($authtypecode) = @_;
507     my $dbh=C4::Context->dbh;
508     my $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
509     $sth->execute($authtypecode);
510     return $sth->fetchrow_hashref;
511 }
512 sub AUTHmodauthority {
513
514     my ($authid,$record,$authtypecode,$merge)=@_;
515     my $dbh=C4::Context->dbh;
516     my ($oldrecord)=&AUTHgetauthority($authid);
517     if ($oldrecord eq $record) {
518         return;
519     }
520 my $sth=$dbh->prepare("update auth_header set marc=? where authid=?");
521 #warn find if linked records exist and delete them
522 my($linkidfield,$linkidsubfield)=AUTHfind_marc_from_kohafield("auth_header.linkid",$authtypecode);
523
524 if ($oldrecord->field($linkidfield)){
525 my @fields=$oldrecord->field($linkidfield);
526     foreach my $field (@fields){
527 my    $linkid=$field->subfield($linkidsubfield) ;
528     if ($linkid){
529         ##Modify the record of linked
530         my $linkrecord=AUTHgetauthority($linkid);
531         my $linktypecode=AUTHfind_authtypecode($linkid);
532         my ( $linkidfield2,$linkidsubfield2)=AUTHfind_marc_from_kohafield("auth_header.linkid",$linktypecode);
533         my @linkfields=$linkrecord->field($linkidfield2);
534             foreach my $linkfield (@linkfields){
535             if ($linkfield->subfield($linkidsubfield2) eq $authid){
536                 $linkrecord->delete_field($linkfield);
537                 $sth->execute($linkrecord->as_usmarc,$linkid);
538                 zebraop($linkid,'specialUpdate',"authorityserver");
539             }
540             }#foreach linkfield
541     }
542     }#foreach linkid
543 }
544 #Now rewrite the $record to table with an add
545 $authid=AUTHaddauthority($record,$authid,$authtypecode);
546
547
548 ### 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
549 ### they should have a system preference "dontmerge=1" otherwise by default biblios will be updated
550 ### the $merge flag is now depreceated and will be removed at code cleaning
551
552 if (C4::Context->preference('dontmerge') ){
553 # save the file in localfile/modified_authorities
554     my $cgidir = C4::Context->intranetdir ."/cgi-bin";
555     unless (opendir(DIR,"$cgidir")) {
556             $cgidir = C4::Context->intranetdir."/";
557     }
558
559     my $filename = $cgidir."/localfile/modified_authorities/$authid.authid";
560     open AUTH, "> $filename";
561     print AUTH $authid;
562     close AUTH;
563 } else {
564     &merge($authid,$record,$authid,$record);
565 }
566 return $authid;
567 }
568
569 sub AUTHdelauthority {
570     my ($authid,$keep_biblio) = @_;
571     my $dbh=C4::Context->dbh;
572 # if the keep_biblio is set to 1, then authority entries in biblio are preserved.
573
574 zebraop($authid,"recordDelete","authorityserver");
575     $dbh->do("delete from auth_header where authid=$authid") ;
576
577 # FIXME : delete or not in biblio tables (depending on $keep_biblio flag)
578 }
579
580 sub AUTHhtml2marc {
581     my ($rtags,$rsubfields,$rvalues,%indicators) = @_;
582     my $dbh=C4::Context->dbh;
583     my $prevtag = -1;
584     my $record = MARC::Record->new();
585 #---- TODO : the leader is missing
586
587 #     my %subfieldlist=();
588     my $prevvalue; # if tag <10
589     my $field; # if tag >=10
590     for (my $i=0; $i< @$rtags; $i++) {
591         # rebuild MARC::Record
592         if (@$rtags[$i] ne $prevtag) {
593             if ($prevtag < 10) {
594                 if ($prevvalue) {
595                     $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
596                 }
597             } else {
598                 if ($field) {
599                     $record->add_fields($field);
600                 }
601             }
602             $indicators{@$rtags[$i]}.='  ';
603             if (@$rtags[$i] <10) {
604                 $prevvalue= @$rvalues[$i];
605                 undef $field;
606             } else {
607                 undef $prevvalue;
608                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
609             }
610             $prevtag = @$rtags[$i];
611         } else {
612             if (@$rtags[$i] <10) {
613                 $prevvalue=@$rvalues[$i];
614             } else {
615                 if (length(@$rvalues[$i])>0) {
616                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
617                 }
618             }
619             $prevtag= @$rtags[$i];
620         }
621     }
622     # the last has not been included inside the loop... do it now !
623     $record->add_fields($field) if $field;
624     return $record;
625 }
626
627
628
629 sub FindDuplicate {
630
631     my ($record,$authtypecode)=@_;
632 #    warn "IN for ".$record->as_formatted;
633     my $dbh = C4::Context->dbh;
634 #    warn "".$record->as_formatted;
635     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
636     $sth->execute($authtypecode);
637     my ($auth_tag_to_report) = $sth->fetchrow;
638     $sth->finish;
639 #     warn "record :".$record->as_formatted." authtattoreport :$auth_tag_to_report";
640     # build a request for authoritysearch
641     my $query='at='.$authtypecode.' ';
642     map {$query.= " and he=\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/)}  $record->field($auth_tag_to_report)->subfields() if $record->field($auth_tag_to_report);
643     my ($error,$results)=SimpleSearch($query,"authorityserver");
644     # there is at least 1 result => return the 1st one
645     if (@$results>0) {
646       my $marcrecord = MARC::File::USMARC::decode($results->[0]);
647       return $marcrecord->field('001')->data,getsummary($marcrecord,$marcrecord->field('001')->data,$authtypecode);
648     }
649     # no result, returns nothing
650     return;
651 }
652
653 sub getsummary{
654 ## give this a Marc record to return summary
655 my ($record,$authid,$authtypecode)=@_;
656
657 my $dbh=C4::Context->dbh;
658 # my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
659  my $authref = getauthtype($authtypecode);
660         my $summary = $authref->{summary};
661         my @fields = $record->fields();
662 #        chop $tags_using_authtype; # FIXME: why commented out?
663         my $reported_tag;
664
665         # if the library has a summary defined, use it. Otherwise, build a standard one
666         if ($summary) {
667             my @fields = $record->fields();
668 #             $reported_tag = '$9'.$result[$counter];
669             foreach my $field (@fields) {
670                 my $tag = $field->tag();
671                 my $tagvalue = $field->as_string();
672                 $summary =~ s/\[(.?.?.?.?)$tag\*(.*?)]/$1$tagvalue$2\[$1$tag$2]/g;
673                 if ($tag<10) {
674                 if ($tag eq '001') {
675                     $reported_tag.='$3'.$field->data();
676                 }
677
678                 } else {
679                     my @subf = $field->subfields;
680                     for my $i (0..$#subf) {
681                         my $subfieldcode = $subf[$i][0];
682                         my $subfieldvalue = $subf[$i][1];
683                         my $tagsubf = $tag.$subfieldcode;
684                         $summary =~ s/\[(.?.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
685 #                         if ($tag eq $auth_tag_to_report) {
686 #                             $reported_tag.='$'.$subfieldcode.$subfieldvalue;
687 #                         }
688                     }
689                 }
690             }
691             $summary =~ s/\[(.*?)]//g;
692             $summary =~ s/\n/<br>/g;
693         } else {
694             my $heading; # = $authref->{summary};
695             my $altheading;
696             my $seeheading;
697             my $see;
698             my @fields = $record->fields();
699             if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
700             # construct UNIMARC summary, that is quite different from MARC21 one
701                 # accepted form
702                 foreach my $field ($record->field('2..')) {
703                     $heading.= $field->as_string();
704                 }
705                 # rejected form(s)
706                 foreach my $field ($record->field('4..')) {
707                     $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
708                     $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
709                 }
710                 # see :
711                 foreach my $field ($record->field('5..')) {
712                     $summary.= "&nbsp;&nbsp;&nbsp;<i>".$field->as_string()."</i><br/>";
713                     $summary.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$heading."<br/>";
714                 }
715                 # // form
716                 foreach my $field ($record->field('7..')) {
717                     $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";
718                     $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
719                     $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$heading."<br />";
720                 }
721                 $summary = "<b>".$heading."</b><br />".$seeheading.$altheading.$summary;
722             } else {
723             # construct MARC21 summary
724                 foreach my $field ($record->field('1..')) {
725                     if ($record->field('100')) {
726                         $heading.= $field->as_string('abcdefghjklmnopqrstvxyz68');
727                     } elsif ($record->field('110')) {
728                                             $heading.= $field->as_string('abcdefghklmnoprstvxyz68');
729                     } elsif ($record->field('111')) {
730                                             $heading.= $field->as_string('acdefghklnpqstvxyz68');
731                     } elsif ($record->field('130')) {
732                                             $heading.= $field->as_string('adfghklmnoprstvxyz68');
733                     } elsif ($record->field('148')) {
734                                             $heading.= $field->as_string('abvxyz68');
735                     } elsif ($record->field('150')) {
736                 #    $heading.= $field->as_string('abvxyz68');
737                 $heading.= $field->as_formatted();
738                     my $tag=$field->tag();
739                     $heading=~s /^$tag//g;
740                     $heading =~s /\_/\$/g;
741                     } elsif ($record->field('151')) {
742                                             $heading.= $field->as_string('avxyz68');
743                     } elsif ($record->field('155')) {
744                                             $heading.= $field->as_string('abvxyz68');
745                     } elsif ($record->field('180')) {
746                                             $heading.= $field->as_string('vxyz68');
747                     } elsif ($record->field('181')) {
748                                             $heading.= $field->as_string('vxyz68');
749                     } elsif ($record->field('182')) {
750                                             $heading.= $field->as_string('vxyz68');
751                     } elsif ($record->field('185')) {
752                                             $heading.= $field->as_string('vxyz68');
753                     } else {
754                         $heading.= $field->as_string();
755                     }
756                 } #See From
757                 foreach my $field ($record->field('4..')) {
758                     $seeheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
759                     $seeheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see:</i> ".$seeheading."<br />";
760                 } #See Also
761                 foreach my $field ($record->field('5..')) {
762                     $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$field->as_string()."<br />";
763                     $altheading.= "&nbsp;&nbsp;&nbsp;".$field->as_string()."<br />";
764                     $altheading.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>see also:</i> ".$altheading."<br />";
765                 }
766                 $summary.=$heading.$seeheading.$altheading;
767             }
768         }
769 return $summary;
770 }
771 sub BuildUnimarcHierarchies{
772   my $authid = shift @_;
773 #   warn "authid : $authid";
774   my $force = shift @_;
775   my @globalresult;
776   my $dbh=C4::Context->dbh;
777   my $hierarchies;
778   my $data = AUTHgetheader($authid);
779   
780   if ($data->{'authtrees'} and not $force){
781     return $data->{'authtrees'};
782   } elsif ($data->{'authtrees'}){
783     $hierarchies=$data->{'authtrees'};
784   } else {
785     my $record = AUTHgetauthority($authid);
786     my $found;
787     foreach my $field ($record->field('550')){
788       if ($field->subfield('5') && $field->subfield('5') eq 'g'){
789         my $parentrecord = AUTHgetauthority($field->subfield('3'));
790         my $localresult=$hierarchies;
791         my $trees;
792         $trees = BuildUnimarcHierarchies($field->subfield('3'));
793         my @trees;
794         if ($trees=~/;/){
795            @trees = split(/;/,$trees);
796         } else {
797            push @trees, $trees;
798         }
799         foreach (@trees){
800           $_.= ",$authid";
801         }
802         @globalresult = (@globalresult,@trees);
803         $found=1;
804       }
805       $hierarchies=join(";",@globalresult);
806     }
807     #Unless there is no ancestor, I am alone.
808     $hierarchies="$authid" unless ($hierarchies);
809   }
810   AUTHsavetrees($authid,$hierarchies);
811   return $hierarchies;
812 }
813
814 sub BuildUnimarcHierarchy{
815         my $record = shift @_;
816     my $class = shift @_;
817     my $authid_constructed = shift @_;
818         my $authid=$record->subfield('250','3');
819     my %cell;
820         my $parents=""; my $children="";
821     my (@loopparents,@loopchildren);
822         foreach my $field ($record->field('550')){
823                 if ($field->subfield('5') && $field->subfield('a')){
824                   if ($field->subfield('5') eq 'h'){
825             push @loopchildren, { "childauthid"=>$field->subfield('3'),"childvalue"=>$field->subfield('a')};
826                   }elsif ($field->subfield('5') eq 'g'){
827             push @loopparents, { "parentauthid"=>$field->subfield('3'),"parentvalue"=>$field->subfield('a')};
828                   }
829                 # brothers could get in there with an else
830                 }
831         }
832     $cell{"ifparents"}=1 if (scalar(@loopparents)>0);
833     $cell{"ifchildren"}=1 if (scalar(@loopchildren)>0);
834     $cell{"loopparents"}=\@loopparents if (scalar(@loopparents)>0);
835     $cell{"loopchildren"}=\@loopchildren if (scalar(@loopchildren)>0);
836     $cell{"class"}=$class;
837     $cell{"loopauthid"}=$authid;
838     $cell{"current_value"} =1 if $authid eq $authid_constructed;
839     $cell{"value"}=$record->subfield('250',"a");
840         return \%cell;
841 }
842
843 sub AUTHgetheader{
844         my $authid = shift @_;
845         my $sql= "SELECT * from auth_header WHERE authid = ?";
846         my $dbh=C4::Context->dbh;
847         my $rq= $dbh->prepare($sql);
848     $rq->execute($authid);
849         my $data= $rq->fetchrow_hashref;
850         return $data;
851 }
852
853 sub AUTHsavetrees{
854         my $authid = shift @_;
855         my $trees = shift @_;
856         my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?";
857         my $dbh=C4::Context->dbh;
858         my $rq= $dbh->prepare($sql);
859     $rq->execute($trees,$authid);
860 }
861
862
863 sub merge {
864     my ($mergefrom,$MARCfrom,$mergeto,$MARCto) = @_;
865     my $dbh=C4::Context->dbh;
866     my $authtypecodefrom = AUTHfind_authtypecode($mergefrom);
867     my $authtypecodeto = AUTHfind_authtypecode($mergeto);
868     # return if authority does not exist
869     my @X = $MARCfrom->fields();
870     return if $#X == -1;
871     @X = $MARCto->fields();
872     return if $#X == -1;
873     
874     
875     # search the tag to report
876     my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
877     $sth->execute($authtypecodefrom);
878     my ($auth_tag_to_report) = $sth->fetchrow;
879
880     my @record_to;
881     @record_to = $MARCto->field($auth_tag_to_report)->subfields() if $MARCto->field($auth_tag_to_report);
882     my @record_from;
883     @record_from = $MARCfrom->field($auth_tag_to_report)->subfields() if $MARCfrom->field($auth_tag_to_report);
884     
885     # search all biblio tags using this authority.
886     $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
887     $sth->execute($authtypecodefrom);
888 my @tags_using_authtype;
889     while (my ($tagfield) = $sth->fetchrow) {
890         push @tags_using_authtype,$tagfield."9" ;
891     }
892
893     # now, find every biblio using this authority
894 ### try ZOOM search here
895 my $oConnection=C4::Context->Zconn("biblioserver");
896 my $query;
897 $query= "an= ".$mergefrom;
898 my $oResult = $oConnection->search(new ZOOM::Query::CCL2RPN( $query, $oConnection ));
899 my $count=$oResult->size() if  ($oResult);
900 my @reccache;
901 my $z=0;
902 while ( $z<$count ) {
903 my $rec;
904          $rec=$oResult->record($z);
905     my $marcdata = $rec->raw();
906 push @reccache, $marcdata;
907 $z++;
908 }
909 $oResult->destroy();
910 foreach my $marc(@reccache){
911
912 my $update;
913     my $marcrecord;
914     $marcrecord = MARC::File::USMARC::decode($marc);
915     foreach my $tagfield (@tags_using_authtype){
916     $tagfield=substr($tagfield,0,3);
917         my @tags = $marcrecord->field($tagfield);
918         foreach my $tag (@tags){
919                 my $tagsubs=$tag->subfield("9");
920 #warn "$tagfield:$tagsubs:$mergefrom";
921                     if ($tagsubs== $mergefrom) {
922                
923             $tag->update("9" =>$mergeto);
924     foreach my $subfield (@record_to) {
925 #        warn "$subfield,$subfield->[0],$subfield->[1]";
926             $tag->update($subfield->[0] =>$subfield->[1]);
927             }#for $subfield
928         }
929              $marcrecord->delete_field($tag);
930                 $marcrecord->add_fields($tag);
931         $update=1;
932         }#for each tag
933     }#foreach tagfield
934         my $oldbiblio = MARCmarc2koha($dbh,$marcrecord,"") ;
935         if ($update==1){
936         # FIXME : this NEWmodbiblio does not exist anymore...
937         &ModBiblio($marcrecord,$oldbiblio->{'biblionumber'},MARCfind_frameworkcode($oldbiblio->{'biblionumber'})) ;
938         }
939     
940 }#foreach $marc
941 }#sub
942 END { }       # module clean-up code here (global destructor)
943
944 =back
945
946 =head1 AUTHOR
947
948 Koha Developement team <info@koha.org>
949
950 Paul POULAIN paul.poulain@free.fr
951
952 =cut
953
954 # $Id$
955 # $Log$
956 # Revision 1.40  2007/03/28 10:39:16  hdl
957 # removing $dbh as a parameter in AuthoritiesMarc functions
958 # And reporting all differences into the scripts taht relies on those functions.
959 #
960 # Revision 1.39  2007/03/16 01:25:08  kados
961 # Using my precrash CVS copy I did the following:
962 #
963 # cvs -z3 -d:ext:kados@cvs.savannah.nongnu.org:/sources/koha co -P koha
964 # find koha.precrash -type d -name "CVS" -exec rm -v {} \;
965 # cp -r koha.precrash/* koha/
966 # cd koha/
967 # cvs commit
968 #
969 # This should in theory put us right back where we were before the crash
970 #
971 # Revision 1.39  2007/03/12 22:16:31  kados
972 # chcking for field before calling subfields
973 #
974 # Revision 1.38  2007/03/09 14:31:47  tipaul
975 # rel_3_0 moved to HEAD
976 #
977 # Revision 1.28.2.17  2007/02/05 13:16:08  hdl
978 # Removing Link from AuthoritiesMARC summary (caused a problem owed to the API differences between opac and intranet)
979 # + removing $dbh in authoritysearch
980 # + adding links in templates on summaries to go to full view.
981 # (no more links in popup authorities. or should we add it ?)
982 #
983 # Revision 1.28.2.16  2007/02/02 18:07:42  hdl
984 # Sorting and searching for exact term now works.
985 #
986 # Revision 1.28.2.15  2007/01/24 10:17:47  hdl
987 # FindDuplicate Now works.
988 # Be AWARE that it needs a change ccl.properties.
989 #
990 # Revision 1.28.2.14  2007/01/10 14:40:11  hdl
991 # Adding Authorities tree.
992 #
993 # Revision 1.28.2.13  2007/01/09 15:18:09  hdl
994 # Adding an to ccl.properties to allow ccl search for authority-numbers.
995 # Fixing Some problems with the previous modification to allow pqf search to work for more than one page.
996 # Using search for an= for an authority-Number.
997 #
998 # Revision 1.28.2.12  2007/01/09 13:51:31  hdl
999 # Bug Fixing : AUTHcount_usage used *synchronous* connection where biblio used ****asynchronous**** one.
1000 # First try to get it work.
1001 #
1002 # Revision 1.28.2.11  2007/01/05 14:37:26  btoumi
1003 # bug fix : remove wrong field in sql syntaxe from auth_subfield_structure table
1004 #
1005 # Revision 1.28.2.10  2007/01/04 13:11:08  tipaul
1006 # commenting 2 zconn destroy
1007 #
1008 # Revision 1.28.2.9  2006/12/22 15:09:53  toins
1009 # removing C4::Database;
1010 #
1011 # Revision 1.28.2.8  2006/12/20 17:13:19  hdl
1012 # modifying use of GILS into use of @attr 1=Koha-Auth-Number
1013 #
1014 # Revision 1.28.2.7  2006/12/18 16:45:38  tipaul
1015 # FIXME upcased
1016 #
1017 # Revision 1.28.2.6  2006/12/07 16:45:43  toins
1018 # removing warn compilation. (perl -wc)
1019 #
1020 # Revision 1.28.2.5  2006/12/06 14:19:59  hdl
1021 # ABugFixing : Authority count  Management.
1022 #
1023 # Revision 1.28.2.4  2006/11/17 13:18:58  tipaul
1024 # code cleaning : removing use of "bib", and replacing with "biblionumber"
1025 #
1026 # WARNING : I tried to do carefully, but there are probably some mistakes.
1027 # So if you encounter a problem you didn't have before, look for this change !!!
1028 # anyway, I urge everybody to use only "biblionumber", instead of "bib", "bi", "biblio" or anything else. will be easier to maintain !!!
1029 #
1030 # Revision 1.28.2.3  2006/11/17 11:17:30  tipaul
1031 # code cleaning : removing use of "bib", and replacing with "biblionumber"
1032 #
1033 # WARNING : I tried to do carefully, but there are probably some mistakes.
1034 # So if you encounter a problem you didn't have before, look for this change !!!
1035 # anyway, I urge everybody to use only "biblionumber", instead of "bib", "bi", "biblio" or anything else. will be easier to maintain !!!
1036 #
1037 # Revision 1.28.2.2  2006/10/12 22:04:47  hdl
1038 # Authorities working with zebra.
1039 # zebra Configuration files are comitted next.
1040 #
1041 # Revision 1.9.2.17.2.2  2006/07/27 16:34:56  kados
1042 # syncing with rel_2_2 .. .untested.
1043 #
1044 # Revision 1.9.2.17.2.1  2006/05/28 18:49:12  tgarip1957
1045 # This is an unusual commit. The main purpose is a working model of Zebra on a modified rel2_2.
1046 # Any questions regarding these commits should be asked to Joshua Ferraro unless you are Joshua whom I'll report to
1047 #
1048 # Revision 1.9.2.6  2005/06/07 10:02:00  tipaul
1049 # porting dictionnary search from head to 2.2. there is now a ... facing titles, author & subject, to search in biblio & authorities existing values.
1050 #
1051 # Revision 1.9.2.5  2005/05/31 14:50:46  tipaul
1052 # fix for authority merging. There was a bug on official installs
1053 #
1054 # Revision 1.9.2.4  2005/05/30 11:24:15  tipaul
1055 # 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)
1056 #
1057 # Revision 1.9.2.3  2005/04/28 08:45:33  tipaul
1058 # porting FindDuplicate feature for authorities from HEAD to rel_2_2, works correctly now.
1059 #
1060 # Revision 1.9.2.2  2005/02/28 14:03:13  tipaul
1061 # * adding search on "main entry" (ie $a subfield) on a given authority (the "search everywhere" field is still here).
1062 # * adding a select box to requet "contain" or "begin with" search.
1063 # * fixing some bug in authority search (related to "main entry" search)
1064 #
1065 # Revision 1.9.2.1  2005/02/24 13:12:13  tipaul
1066 # 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.
1067 # So, it will be done through a cron job.
1068 # (/me agree we need some doc for command line scripts)
1069 #
1070 # Revision 1.9  2004/12/23 09:48:11  tipaul
1071 # Minor changes in summary "exploding" (the 3 digits AFTER the subfield were not on the right place).
1072 #
1073 # Revision 1.8  2004/11/05 10:11:39  tipaul
1074 # export auth_count_usage (bugfix)
1075 #
1076 # Revision 1.7  2004/09/23 16:13:00  tipaul
1077 # Bugfix in modification
1078 #
1079 # Revision 1.6  2004/08/18 16:00:24  tipaul
1080 # fixes for authorities management
1081 #
1082 # Revision 1.5  2004/07/05 13:37:22  doxulting
1083 # First step for working authorities
1084 #
1085 # Revision 1.4  2004/06/22 11:35:37  tipaul
1086 # removing % at the beginning of a string to avoid loooonnnngggg searchs
1087 #
1088 # Revision 1.3  2004/06/17 08:02:13  tipaul
1089 # merging tag & subfield in auth_word for better perfs
1090 #
1091 # Revision 1.2  2004/06/10 08:29:01  tipaul
1092 # MARC authority management (continued)
1093 #
1094 # Revision 1.1  2004/06/07 07:35:01  tipaul
1095 # MARC authority management package
1096 #