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