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