synch'ing 2.2 and head
[koha.git] / C4 / AuthoritiesMarc.pm
1 package C4::AuthoritiesMarc;
2 # Copyright 2000-2002 Katipo Communications
3 #
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19 use strict;
20 require Exporter;
21 use C4::Context;
22 use C4::Database;
23 use C4::Koha;
24 use MARC::Record;
25 use C4::Biblio;
26
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         
44         &AUTHgetauth_type
45         &AUTHcount_usage
46         
47         &authoritysearch
48         
49         &MARCmodsubfield
50         &AUTHhtml2marc
51         &AUTHaddword
52         &MARCaddword &MARCdelword
53         &char_decode
54         &FindDuplicate
55  );
56
57 sub authoritysearch {
58         my ($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode) = @_;
59         # build the sql request. She will look like :
60         # select m1.bibid
61         #               from auth_subfield_table as m1, auth_subfield_table as m2
62         #               where m1.authid=m2.authid and
63         #               (m1.subfieldvalue like "Des%" and m2.subfieldvalue like "27%")
64
65         # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on
66         # the authtypecode. Then, search on $a of this tag_to_report
67         # also store main entry MARC tag, to extract it at end of search
68         my $mainentrytag;
69         my $sth = $dbh->prepare("select auth_tag_to_report from auth_types where authtypecode=?");
70         $sth->execute($authtypecode);
71         my ($tag_to_report) = $sth->fetchrow;
72         $mainentrytag = $tag_to_report;
73         for (my $i=0;$i<$#{$tags};$i++) {
74                 if (@$tags[$i] eq "mainentry") {
75                         @$tags[$i] = $tag_to_report."a";
76                 }
77         }
78
79         # "Normal" statements
80         # quote marc fields/subfields
81         for (my $i=0;$i<=$#{$tags};$i++) {
82                 if (@$tags[$i]) {
83                         @$tags[$i] = $dbh->quote(@$tags[$i]);
84                 }
85         }
86         my @normal_tags = ();
87         my @normal_and_or = ();
88         my @normal_operator = ();
89         my @normal_value = ();
90         # Extracts the NOT statements from the list of statements
91         for(my $i = 0 ; $i <= $#{$value} ; $i++)
92         {
93                 # replace * by %
94                 @$value[$i] =~ s/\*/%/g;
95                 # remove % at the beginning
96                 @$value[$i] =~ s/^%//g;
97             @$value[$i] =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\}|\/)/ /g if @$operator[$i] eq "contains";
98                 if(@$operator[$i] eq "contains") # if operator is contains, splits the words in separate requests
99                 {
100                         foreach my $word (split(/ /, @$value[$i]))
101                         {
102                                 unless (C4::Context->stopwords->{uc($word)}) {  #it's NOT a stopword => use it. Otherwise, ignore
103                                         my $tag = substr(@$tags[$i],0,3);
104                                         my $subf = substr(@$tags[$i],3,1);
105                                         push @normal_tags, @$tags[$i];
106                                         push @normal_and_or, "and";     # assumes "foo" and "bar" if "foo bar" is entered
107                                         push @normal_operator, @$operator[$i];
108                                         push @normal_value, $word;
109                                 }
110                         }
111                 }
112                 else
113                 {
114                         push @normal_tags, @$tags[$i];
115                         push @normal_and_or, @$and_or[$i];
116                         push @normal_operator, @$operator[$i];
117                         push @normal_value, @$value[$i];
118                 }
119         }
120
121         # Finds the basic results without the NOT requests
122         my ($sql_tables, $sql_where1, $sql_where2) = create_request($dbh,\@normal_tags, \@normal_and_or, \@normal_operator, \@normal_value);
123
124         my $sth;
125
126         if ($sql_where2) {
127                 $sth = $dbh->prepare("select distinct m1.authid from auth_header,$sql_tables where  m1.authid=auth_header.authid and auth_header.authtypecode=? and $sql_where2 and ($sql_where1)");
128                 warn "Q2 : select distinct m1.authid from auth_header,$sql_tables where  m1.authid=auth_header.authid and auth_header.authtypecode=? and $sql_where2 and ($sql_where1)";
129         } else {
130                 $sth = $dbh->prepare("select distinct m1.authid from auth_header,$sql_tables where  m1.authid=auth_header.authid and auth_header.authtypecode=? and $sql_where1");
131                 warn "Q : select distinct m1.authid from auth_header,$sql_tables where  m1.authid=auth_header.authid and auth_header.authtypecode=? and $sql_where1";
132         }
133         $sth->execute($authtypecode);
134         my @result = ();
135         while (my ($authid) = $sth->fetchrow) {
136                         push @result,$authid;
137                 }
138
139         # we have authid list. Now, loads summary from [offset] to [offset]+[length]
140         my $counter = $offset;
141         my @finalresult = ();
142         my $oldline;
143         while (($counter <= $#result) && ($counter <= ($offset + $length))) {
144 #               warn " HERE : $counter, $#result, $offset, $length";
145                 # get MARC::Record of the authority
146                 my $record = AUTHgetauthority($dbh,$result[$counter]);
147                 # then build the summary
148                 my $authtypecode = AUTHfind_authtypecode($dbh,$result[$counter]);
149                 my $authref = getauthtype($authtypecode);
150                 my $summary = $authref->{summary};
151                 my @fields = $record->fields();
152                 foreach my $field (@fields) {
153                         my $tag = $field->tag();
154                         if ($tag<10) {
155                         } else {
156                                 my @subf = $field->subfields;
157                                 for my $i (0..$#subf) {
158                                         my $subfieldcode = $subf[$i][0];
159                                         my $subfieldvalue = $subf[$i][1];
160                                         my $tagsubf = $tag.$subfieldcode;
161                                         $summary =~ s/\[(.?.?.?)$tagsubf(.*?)]/$1$subfieldvalue$2\[$1$tagsubf$2]/g;
162                                 }
163                         }
164                 }
165                 $summary =~ s/\[(.*?)]//g;
166                 $summary =~ s/\n/<br>/g;
167
168                 # find biblio MARC field using this authtypecode (to jump to biblio)
169                 my $authtypecode = AUTHfind_authtypecode($dbh,$result[$counter]);
170                 my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
171                 $sth->execute($authtypecode);
172                 my $tags_using_authtype;
173                 while (my ($tagfield) = $sth->fetchrow) {
174 #                       warn "TAG : $tagfield";
175                         $tags_using_authtype.= $tagfield."9,";
176                 }
177                 chop $tags_using_authtype;
178                 
179                 # then add a line for the template loop
180                 my %newline;
181                 $newline{summary} = $summary;
182                 $newline{authid} = $result[$counter];
183                 $newline{used} = &AUTHcount_usage($result[$counter]);
184                 $newline{biblio_fields} = $tags_using_authtype;
185                 $newline{even} = $counter % 2;
186                 $newline{mainentry} = $record->field($mainentrytag)->subfield('a')." ".$record->field($mainentrytag)->subfield('b') if $record->field($mainentrytag);
187                 $counter++;
188                 push @finalresult, \%newline;
189         }
190         my $nbresults = $#result + 1;
191         return (\@finalresult, $nbresults);
192 }
193
194 # Creates the SQL Request
195
196 sub create_request {
197         my ($dbh,$tags, $and_or, $operator, $value) = @_;
198
199         my $sql_tables; # will contain marc_subfield_table as m1,...
200         my $sql_where1; # will contain the "true" where
201         my $sql_where2 = "("; # will contain m1.authid=m2.authid
202         my $nb_active=0; # will contain the number of "active" entries. and entry is active is a value is provided.
203         my $nb_table=1; # will contain the number of table. ++ on each entry EXCEPT when an OR  is provided.
204
205
206         for(my $i=0; $i<=@$value;$i++) {
207                 if (@$value[$i]) {
208                         $nb_active++;
209 #                       warn " @$tags[$i]";
210                         if ($nb_active==1) {
211                                 if (@$operator[$i] eq "start") {
212                                         $sql_tables .= "auth_subfield_table as m$nb_table,";
213                                         $sql_where1 .= "(m1.subfieldvalue like ".$dbh->quote("@$value[$i]%");
214                                         if (@$tags[$i]) {
215                                                 $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
216                                         }
217                                         $sql_where1.=")";
218                                 } elsif (@$operator[$i] eq "contains") {        
219                                 $sql_tables .= "auth_word as m$nb_table,";
220                                         $sql_where1 .= "(m1.word  like ".$dbh->quote("@$value[$i]%");
221                                         if (@$tags[$i]) {
222                                                  $sql_where1 .=" and m1.tagsubfield in (@$tags[$i])";
223                                         }
224                                         $sql_where1.=")";
225                                 } else {
226
227                                         $sql_tables .= "auth_subfield_table as m$nb_table,";
228                                         $sql_where1 .= "(m1.subfieldvalue @$operator[$i] ".$dbh->quote("@$value[$i]");
229                                         if (@$tags[$i]) {
230                                                  $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
231                                         }
232                                         $sql_where1.=")";
233                                 }
234                         } else {
235                                 if (@$operator[$i] eq "start") {
236                                         $nb_table++;
237                                         $sql_tables .= "auth_subfield_table as m$nb_table,";
238                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue like ".$dbh->quote("@$value[$i]%");
239                                         if (@$tags[$i]) {
240                                                 $sql_where1 .=" and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
241                                         }
242                                         $sql_where1.=")";
243                                         $sql_where2 .= "m1.authid=m$nb_table.authid and ";
244                                 } elsif (@$operator[$i] eq "contains") {
245                                         if (@$and_or[$i] eq 'and') {
246                                                 $nb_table++;
247                                                 $sql_tables .= "auth_word as m$nb_table,";
248                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]%");
249                                                 if (@$tags[$i]) {
250                                                         $sql_where1 .=" and m$nb_table.tagsubfield in(@$tags[$i])";
251                                                 }
252                                                 $sql_where1.=")";
253                                                 $sql_where2 .= "m1.authid=m$nb_table.authid and ";
254                                         } else {
255                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]%");
256                                                 if (@$tags[$i]) {
257                                                         $sql_where1 .="  and m$nb_table.tag+m$nb_table.subfieldid in (@$tags[$i])";
258                                                 }
259                                                 $sql_where1.=")";
260                                                 $sql_where2 .= "m1.authid=m$nb_table.authid and ";
261                                         }
262                                 } else {
263                                         $nb_table++;
264                                         $sql_tables .= "auth_subfield_table as m$nb_table,";
265                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue @$operator[$i] ".$dbh->quote(@$value[$i]);
266                                         if (@$tags[$i]) {
267                                                 $sql_where1 .="  and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
268                                         }
269                                         $sql_where2 .= "m1.authid=m$nb_table.authid and ";
270                                         $sql_where1.=")";
271                                 }
272                         }
273                 }
274         }
275
276         if($sql_where2 ne "(")  # some datas added to sql_where2, processing
277         {
278                 $sql_where2 = substr($sql_where2, 0, (length($sql_where2)-5)); # deletes the trailing ' and '
279                 $sql_where2 .= ")";
280         }
281         else    # no sql_where2 statement, deleting '('
282         {
283                 $sql_where2 = "";
284         }
285         chop $sql_tables;       # deletes the trailing ','
286         
287         return ($sql_tables, $sql_where1, $sql_where2);
288 }
289
290
291 sub AUTHcount_usage {
292         my ($authid) = @_;
293         my $dbh = C4::Context->dbh;
294         # find MARC fields using this authtype
295         my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
296         my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
297         $sth->execute($authtypecode);
298         my $tags_using_authtype;
299         while (my ($tagfield) = $sth->fetchrow) {
300 #               warn "TAG : $tagfield";
301                 $tags_using_authtype.= "'".$tagfield."9',";
302         }
303         chop $tags_using_authtype;
304         if ($tags_using_authtype) {
305                 $sth = $dbh->prepare("select count(*) from marc_subfield_table where concat(tag,subfieldcode) in ($tags_using_authtype) and subfieldvalue=?");
306         } else {
307                 $sth = $dbh->prepare("select count(*) from marc_subfield_table where subfieldvalue=?");
308         }
309 #       warn "Q : select count(*) from marc_subfield_table where concat(tag,subfieldcode) in ($tags_using_authtype) and subfieldvalue=$authid";
310         $sth->execute($authid);
311         my ($result) = $sth->fetchrow;
312 #       warn "Authority $authid TOTAL USED : $result";
313         return $result;
314 }
315
316 # merging 2 authority entries. After a merge, the "from" can be deleted.
317 # sub AUTHmerge {
318 #       my ($auth_merge_from,$auth_merge_to) = @_;
319 #       my $dbh = C4::Context->dbh;
320 #       # find MARC fields using this authtype
321 #       my $authtypecode = AUTHfind_authtypecode($dbh,$authid);
322 #       # retrieve records
323 #       my $record_from = AUTHgetauthority($dbh,$auth_merge_from);
324 #       my $record_to = AUTHgetauthority($dbh,$auth_merge_to);
325 #       my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?");
326 #       $sth->execute($authtypecode);
327 #       my $tags_using_authtype;
328 #       while (my ($tagfield) = $sth->fetchrow) {
329 #               warn "TAG : $tagfield";
330 #               $tags_using_authtype.= "'".$tagfield."9',";
331 #       }
332 #       chop $tags_using_authtype;
333 #       # now, find every biblio using this authority
334 #       $sth = $dbh->prepare("select bibid,tag,tag_indicator,tagorder from marc_subfield_table where tag+subfieldid in ($tags_using_authtype) and subfieldvalue=?");
335 #       $sth->execute($authid);
336 #       # and delete entries before recreating them
337 #       while (my ($bibid,$tag,$tag_indicator,$tagorder) = $sth->fetchrow) {
338 #               &MARCdelsubfield($dbh,$bibid,$tag);
339 #               
340 #       }
341
342 # }
343
344 sub AUTHfind_authtypecode {
345         my ($dbh,$authid) = @_;
346         my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
347         $sth->execute($authid);
348         my ($authtypecode) = $sth->fetchrow;
349         return $authtypecode;
350 }
351  
352
353 sub AUTHgettagslib {
354         my ($dbh,$forlibrarian,$authtypecode)= @_;
355         $authtypecode="" unless $authtypecode;
356         my $sth;
357         my $libfield = ($forlibrarian eq 1)? 'liblibrarian' : 'libopac';
358         # check that framework exists
359         $sth=$dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?");
360         $sth->execute($authtypecode);
361         my ($total) = $sth->fetchrow;
362         $authtypecode="" unless ($total >0);
363         $sth=$dbh->prepare("select tagfield,$libfield as lib,mandatory,repeatable from auth_tag_structure where authtypecode=? order by tagfield");
364         $sth->execute($authtypecode);
365         my ($lib,$tag,$res,$tab,$mandatory,$repeatable);
366         while ( ($tag,$lib,$mandatory,$repeatable) = $sth->fetchrow) {
367                 $res->{$tag}->{lib}=$lib;
368                 $res->{$tab}->{tab}=""; # XXX
369                 $res->{$tag}->{mandatory}=$mandatory;
370                 $res->{$tag}->{repeatable}=$repeatable;
371         }
372
373         $sth=$dbh->prepare("select tagfield,tagsubfield,$libfield as lib,tab, mandatory, repeatable,authorised_value,value_builder,seealso from auth_subfield_structure where authtypecode=? order by tagfield,tagsubfield");
374         $sth->execute($authtypecode);
375
376         my $subfield;
377         my $authorised_value;
378         my $thesaurus_category;
379         my $value_builder;
380         my $kohafield;
381         my $seealso;
382         my $hidden;
383         my $isurl;
384         while ( ($tag, $subfield, $lib, $tab, $mandatory, $repeatable,$authorised_value,$value_builder,$seealso) = $sth->fetchrow) {
385                 $res->{$tag}->{$subfield}->{lib}=$lib;
386                 $res->{$tag}->{$subfield}->{tab}=$tab;
387                 $res->{$tag}->{$subfield}->{mandatory}=$mandatory;
388                 $res->{$tag}->{$subfield}->{repeatable}=$repeatable;
389                 $res->{$tag}->{$subfield}->{authorised_value}=$authorised_value;
390                 $res->{$tag}->{$subfield}->{thesaurus_category}=$thesaurus_category;
391                 $res->{$tag}->{$subfield}->{value_builder}=$value_builder;
392                 $res->{$tag}->{$subfield}->{seealso}=$seealso;
393                 $res->{$tag}->{$subfield}->{hidden}=$hidden;
394                 $res->{$tag}->{$subfield}->{isurl}=$isurl;
395         }
396         return $res;
397 }
398
399 sub AUTHaddauthority {
400 # pass the MARC::Record to this function, and it will create the records in the marc tables
401         my ($dbh,$record,$authid,$authtypecode) = @_;
402         my @fields=$record->fields();
403 #       warn "IN AUTHaddauthority $authid => ".$record->as_formatted;
404 # adding main table, and retrieving authid
405 # if authid is sent, then it's not a true add, it's only a re-add, after a delete (ie, a mod)
406 # if authid empty => true add, find a new authid number
407         unless ($authid) {
408                 $dbh->do("lock tables auth_header WRITE,auth_subfield_table WRITE, auth_word WRITE, stopwords READ");
409                 my $sth=$dbh->prepare("insert into auth_header (datecreated,authtypecode) values (now(),?)");
410                 $sth->execute($authtypecode);
411                 $sth=$dbh->prepare("select max(authid) from auth_header");
412                 $sth->execute;
413                 ($authid)=$sth->fetchrow;
414                 $sth->finish;
415         }
416         my $fieldcount=0;
417         # now, add subfields...
418         foreach my $field (@fields) {
419                 $fieldcount++;
420                 if ($field->tag() <10) {
421                                 &AUTHaddsubfield($dbh,$authid,
422                                                 $field->tag(),
423                                                 '',
424                                                 $fieldcount,
425                                                 '',
426                                                 1,
427                                                 $field->data()
428                                                 );
429                 } else {
430                         my @subfields=$field->subfields();
431                         foreach my $subfieldcount (0..$#subfields) {
432                                 &AUTHaddsubfield($dbh,$authid,
433                                                 $field->tag(),
434                                                 $field->indicator(1).$field->indicator(2),
435                                                 $fieldcount,
436                                                 $subfields[$subfieldcount][0],
437                                                 $subfieldcount+1,
438                                                 $subfields[$subfieldcount][1]
439                                                 );
440                         }
441                 }
442         }
443         $dbh->do("unlock tables");
444         return $authid;
445 }
446
447
448 sub AUTHaddsubfield {
449 # Add a new subfield to a tag into the DB.
450         my ($dbh,$authid,$tagid,$tag_indicator,$tagorder,$subfieldcode,$subfieldorder,$subfieldvalues) = @_;
451         # if not value, end of job, we do nothing
452         if (length($subfieldvalues) ==0) {
453                 return;
454         }
455         if (not($subfieldcode)) {
456                 $subfieldcode=' ';
457         }
458         my @subfieldvalues = split /\|/,$subfieldvalues;
459         foreach my $subfieldvalue (@subfieldvalues) {
460                 my $sth=$dbh->prepare("insert into auth_subfield_table (authid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue) values (?,?,?,?,?,?,?)");
461                 $sth->execute($authid,(sprintf "%03s",$tagid),$tagorder,$tag_indicator,$subfieldcode,$subfieldorder,$subfieldvalue);
462                 if ($sth->errstr) {
463                         warn "ERROR ==> insert into auth_subfield_table (authid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue) values ($authid,$tagid,$tagorder,$tag_indicator,$subfieldcode,$subfieldorder,$subfieldvalue)\n";
464                 }
465                 &AUTHaddword($dbh,$authid,$tagid,$tagorder,$subfieldcode,$subfieldorder,$subfieldvalue);
466         }
467 }
468
469 sub AUTHgetauthority {
470 # Returns MARC::Record of the biblio passed in parameter.
471     my ($dbh,$authid)=@_;
472     my $record = MARC::Record->new();
473 #---- TODO : the leader is missing
474         $record->leader('                        ');
475     my $sth=$dbh->prepare("select authid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue
476                                  from auth_subfield_table
477                                  where authid=? order by tag,tagorder,subfieldcode
478                          ");
479         $sth->execute($authid);
480         my $prevtagorder=1;
481         my $prevtag='XXX';
482         my $previndicator;
483         my $field; # for >=10 tags
484         my $prevvalue; # for <10 tags
485         while (my $row=$sth->fetchrow_hashref) {
486                 if ($row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag) {
487                         $previndicator.="  ";
488                         if ($prevtag <10) {
489                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue) unless $prevtag eq "XXX"; # ignore the 1st loop
490                         } else {
491                                 $record->add_fields($field) unless $prevtag eq "XXX";
492                         }
493                         undef $field;
494                         $prevtagorder=$row->{tagorder};
495                         $prevtag = $row->{tag};
496                         $previndicator=$row->{tag_indicator};
497                         if ($row->{tag}<10) {
498                                 $prevvalue = $row->{subfieldvalue};
499                         } else {
500                                 $field = MARC::Field->new((sprintf "%03s",$prevtag), substr($row->{tag_indicator}.'  ',0,1), substr($row->{tag_indicator}.'  ',1,1), $row->{'subfieldcode'}, $row->{'subfieldvalue'} );
501                         }
502                 } else {
503                         if ($row->{tag} <10) {
504                                 $record->add_fields((sprintf "%03s",$row->{tag}), $row->{'subfieldvalue'});
505                         } else {
506                                 $field->add_subfields($row->{'subfieldcode'}, $row->{'subfieldvalue'} );
507                         }
508                         $prevtag= $row->{tag};
509                         $previndicator=$row->{tag_indicator};
510                 }
511         }
512         # the last has not been included inside the loop... do it now !
513         if ($prevtag ne "XXX") { # check that we have found something. Otherwise, prevtag is still XXX and we
514                                                 # must return an empty record, not make MARC::Record fail because we try to
515                                                 # create a record with XXX as field :-(
516                 if ($prevtag <10) {
517                         $record->add_fields($prevtag,$prevvalue);
518                 } else {
519         #               my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
520                         $record->add_fields($field);
521                 }
522         }
523         return $record;
524 }
525
526 sub AUTHgetauth_type {
527         my ($authtypecode) = @_;
528         my $dbh=C4::Context->dbh;
529         my $sth=$dbh->prepare("select * from auth_types where authtypecode=?");
530         $sth->execute($authtypecode);
531         return $sth->fetchrow_hashref;
532 }
533 sub AUTHmodauthority {
534         my ($dbh,$authid,$record,$delete)=@_;
535         my $oldrecord=&AUTHgetauthority($dbh,$authid);
536         if ($oldrecord eq $record) {
537                 return;
538         }
539 # 1st delete the authority,
540 # 2nd recreate it
541         &AUTHdelauthority($dbh,$authid,1);
542         &AUTHaddauthority($dbh,$record,$authid,AUTHfind_authtypecode($dbh,$authid));
543         # save the file in localfile/modified_authorities
544         my $filename = C4::Context->config("intranetdir")."/localfile/modified_authorities/$authid.authid";
545         open AUTH, "> $filename";
546         print AUTH $authid;
547         close AUTH;
548 }
549
550 sub AUTHdelauthority {
551         my ($dbh,$authid,$keep_biblio) = @_;
552 # if the keep_biblio is set to 1, then authority entries in biblio are preserved.
553 # This flag is set when the delauthority is called by modauthority
554 # due to a too complex structure of MARC (repeatable fields and subfields),
555 # the best solution for a modif is to delete / recreate the record.
556
557         my $record = AUTHgetauthority($dbh,$authid);
558         $dbh->do("delete from auth_header where authid=$authid") unless $keep_biblio;
559         $dbh->do("delete from auth_subfield_table where authid=$authid");
560         $dbh->do("delete from auth_word where authid=$authid");
561 # FIXME : delete or not in biblio tables (depending on $keep_biblio flag)
562 }
563
564 sub AUTHmodsubfield {
565 # Subroutine changes a subfield value given a subfieldid.
566         my ($dbh, $subfieldid, $subfieldvalue )=@_;
567         $dbh->do("lock tables auth_subfield_table WRITE");
568         my $sth=$dbh->prepare("update auth_subfield_table set subfieldvalue=? where subfieldid=?");
569         $sth->execute($subfieldvalue, $subfieldid);
570         $dbh->do("unlock tables");
571         $sth->finish;
572         $sth=$dbh->prepare("select authid,tag,tagorder,subfieldcode,subfieldid,subfieldorder from auth_subfield_table where subfieldid=?");
573         $sth->execute($subfieldid);
574         my ($authid,$tagid,$tagorder,$subfieldcode,$x,$subfieldorder) = $sth->fetchrow;
575         $subfieldid=$x;
576         &AUTHdelword($dbh,$authid,$tagid,$tagorder,$subfieldcode,$subfieldorder);
577         &AUTHaddword($dbh,$authid,$tagid,$tagorder,$subfieldcode,$subfieldorder,$subfieldvalue);
578         return($subfieldid, $subfieldvalue);
579 }
580
581 sub AUTHfindsubfield {
582     my ($dbh,$authid,$tag,$subfieldcode,$subfieldorder,$subfieldvalue) = @_;
583     my $resultcounter=0;
584     my $subfieldid;
585     my $lastsubfieldid;
586     my $query="select subfieldid from auth_subfield_table where authid=? and tag=? and subfieldcode=?";
587     my @bind_values = ($authid,$tag, $subfieldcode);
588     if ($subfieldvalue) {
589         $query .= " and subfieldvalue=?";
590         push(@bind_values,$subfieldvalue);
591     } else {
592         if ($subfieldorder<1) {
593             $subfieldorder=1;
594         }
595         $query .= " and subfieldorder=?";
596         push(@bind_values,$subfieldorder);
597     }
598     my $sti=$dbh->prepare($query);
599     $sti->execute(@bind_values);
600     while (($subfieldid) = $sti->fetchrow) {
601         $resultcounter++;
602         $lastsubfieldid=$subfieldid;
603     }
604     if ($resultcounter>1) {
605                 # Error condition.  Values given did not resolve into a unique record.  Don't know what to edit
606                 # should rarely occur (only if we use subfieldvalue with a value that exists twice, which is strange)
607                 return -1;
608     } else {
609                 return $lastsubfieldid;
610     }
611 }
612
613 sub AUTHfindsubfieldid {
614         my ($dbh,$authid,$tag,$tagorder,$subfield,$subfieldorder) = @_;
615         my $sth=$dbh->prepare("select subfieldid from auth_subfield_table
616                                 where authid=? and tag=? and tagorder=?
617                                         and subfieldcode=? and subfieldorder=?");
618         $sth->execute($authid,$tag,$tagorder,$subfield,$subfieldorder);
619         my ($res) = $sth->fetchrow;
620         unless ($res) {
621                 $sth=$dbh->prepare("select subfieldid from auth_subfield_table
622                                 where authid=? and tag=? and tagorder=?
623                                         and subfieldcode=?");
624                 $sth->execute($authid,$tag,$tagorder,$subfield);
625                 ($res) = $sth->fetchrow;
626         }
627     return $res;
628 }
629
630 sub AUTHfind_authtypecode {
631         my ($dbh,$authid) = @_;
632         my $sth = $dbh->prepare("select authtypecode from auth_header where authid=?");
633         $sth->execute($authid);
634         my ($authtypecode) = $sth->fetchrow;
635         return $authtypecode;
636 }
637
638 sub AUTHdelsubfield {
639 # delete a subfield for $authid / tag / tagorder / subfield / subfieldorder
640     my ($dbh,$authid,$tag,$tagorder,$subfield,$subfieldorder) = @_;
641     $dbh->do("delete from auth_subfield_table where authid='$authid' and
642                         tag='$tag' and tagorder='$tagorder'
643                         and subfieldcode='$subfield' and subfieldorder='$subfieldorder'
644                         ");
645 }
646
647 sub AUTHhtml2marc {
648         my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
649         my $prevtag = -1;
650         my $record = MARC::Record->new();
651 #       my %subfieldlist=();
652         my $prevvalue; # if tag <10
653         my $field; # if tag >=10
654         for (my $i=0; $i< @$rtags; $i++) {
655                 # rebuild MARC::Record
656                 if (@$rtags[$i] ne $prevtag) {
657                         if ($prevtag < 10) {
658                                 if ($prevvalue) {
659                                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
660                                 }
661                         } else {
662                                 if ($field) {
663                                         $record->add_fields($field);
664                                 }
665                         }
666                         $indicators{@$rtags[$i]}.='  ';
667                         if (@$rtags[$i] <10) {
668                                 $prevvalue= @$rvalues[$i];
669                                 undef $field;
670                         } else {
671                                 undef $prevvalue;
672                                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
673                         }
674                         $prevtag = @$rtags[$i];
675                 } else {
676                         if (@$rtags[$i] <10) {
677                                 $prevvalue=@$rvalues[$i];
678                         } else {
679                                 if (length(@$rvalues[$i])>0) {
680                                         $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
681                                 }
682                         }
683                         $prevtag= @$rtags[$i];
684                 }
685         }
686         # the last has not been included inside the loop... do it now !
687         $record->add_fields($field) if $field;
688         return $record;
689 }
690
691 sub AUTHaddword {
692 # split a subfield string and adds it into the word table.
693 # removes stopwords
694     my ($dbh,$authid,$tag,$tagorder,$subfieldid,$subfieldorder,$sentence) =@_;
695     $sentence =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
696     my @words = split / /,$sentence;
697     my $stopwords= C4::Context->stopwords;
698     my $sth=$dbh->prepare("insert into auth_word (authid, tagsubfield, tagorder, subfieldorder, word, sndx_word)
699                         values (?,concat(?,?),?,?,?,soundex(?))");
700     foreach my $word (@words) {
701 # we record only words longer than 2 car and not in stopwords hash
702         if (length($word)>2 and !($stopwords->{uc($word)})) {
703             $sth->execute($authid,$tag,$subfieldid,$tagorder,$subfieldorder,$word,$word);
704             if ($sth->err()) {
705                 warn "ERROR ==> insert into auth_word (authid, tagsubfield, tagorder, subfieldorder, word, sndx_word) values ($authid,concat($tag,$subfieldid),$tagorder,$subfieldorder,$word,soundex($word))\n";
706             }
707         }
708     }
709 }
710
711 sub AUTHdelword {
712 # delete words. this sub deletes all the words from a sentence. a subfield modif is done by a delete then a add
713     my ($dbh,$authid,$tag,$tagorder,$subfield,$subfieldorder) = @_;
714     my $sth=$dbh->prepare("delete from auth_word where authid=? and tagsubfield=concat(?,?) and tagorder=? and subfieldorder=?");
715     $sth->execute($authid,$tag,$subfield,$tagorder,$subfieldorder);
716 }
717
718 sub char_decode {
719         # converts ISO 5426 coded string to ISO 8859-1
720         # sloppy code : should be improved in next issue
721         my ($string,$encoding) = @_ ;
722         $_ = $string ;
723 #       $encoding = C4::Context->preference("marcflavour") unless $encoding;
724         if ($encoding eq "UNIMARC") {
725                 s/\xe1/Æ/gm ;
726                 s/\xe2/Ð/gm ;
727                 s/\xe9/Ø/gm ;
728                 s/\xec/þ/gm ;
729                 s/\xf1/æ/gm ;
730                 s/\xf3/ð/gm ;
731                 s/\xf9/ø/gm ;
732                 s/\xfb/ß/gm ;
733                 s/\xc1\x61/à/gm ;
734                 s/\xc1\x65/è/gm ;
735                 s/\xc1\x69/ì/gm ;
736                 s/\xc1\x6f/ò/gm ;
737                 s/\xc1\x75/ù/gm ;
738                 s/\xc1\x41/À/gm ;
739                 s/\xc1\x45/È/gm ;
740                 s/\xc1\x49/Ì/gm ;
741                 s/\xc1\x4f/Ò/gm ;
742                 s/\xc1\x55/Ù/gm ;
743                 s/\xc2\x41/Á/gm ;
744                 s/\xc2\x45/É/gm ;
745                 s/\xc2\x49/Í/gm ;
746                 s/\xc2\x4f/Ó/gm ;
747                 s/\xc2\x55/Ú/gm ;
748                 s/\xc2\x59/Ý/gm ;
749                 s/\xc2\x61/á/gm ;
750                 s/\xc2\x65/é/gm ;
751                 s/\xc2\x69/í/gm ;
752                 s/\xc2\x6f/ó/gm ;
753                 s/\xc2\x75/ú/gm ;
754                 s/\xc2\x79/ý/gm ;
755                 s/\xc3\x41/Â/gm ;
756                 s/\xc3\x45/Ê/gm ;
757                 s/\xc3\x49/Î/gm ;
758                 s/\xc3\x4f/Ô/gm ;
759                 s/\xc3\x55/Û/gm ;
760                 s/\xc3\x61/â/gm ;
761                 s/\xc3\x65/ê/gm ;
762                 s/\xc3\x69/î/gm ;
763                 s/\xc3\x6f/ô/gm ;
764                 s/\xc3\x75/û/gm ;
765                 s/\xc4\x41/Ã/gm ;
766                 s/\xc4\x4e/Ñ/gm ;
767                 s/\xc4\x4f/Õ/gm ;
768                 s/\xc4\x61/ã/gm ;
769                 s/\xc4\x6e/ñ/gm ;
770                 s/\xc4\x6f/õ/gm ;
771                 s/\xc8\x45/Ë/gm ;
772                 s/\xc8\x49/Ï/gm ;
773                 s/\xc8\x65/ë/gm ;
774                 s/\xc8\x69/ï/gm ;
775                 s/\xc8\x76/ÿ/gm ;
776                 s/\xc9\x41/Ä/gm ;
777                 s/\xc9\x4f/Ö/gm ;
778                 s/\xc9\x55/Ü/gm ;
779                 s/\xc9\x61/ä/gm ;
780                 s/\xc9\x6f/ö/gm ;
781                 s/\xc9\x75/ü/gm ;
782                 s/\xca\x41/Å/gm ;
783                 s/\xca\x61/å/gm ;
784                 s/\xd0\x43/Ç/gm ;
785                 s/\xd0\x63/ç/gm ;
786                 # this handles non-sorting blocks (if implementation requires this)
787                 $string = nsb_clean($_) ;
788         } elsif ($encoding eq "USMARC" || $encoding eq "MARC21") {
789                 if(/[\xc1-\xff]/) {
790                         s/\xe1\x61/à/gm ;
791                         s/\xe1\x65/è/gm ;
792                         s/\xe1\x69/ì/gm ;
793                         s/\xe1\x6f/ò/gm ;
794                         s/\xe1\x75/ù/gm ;
795                         s/\xe1\x41/À/gm ;
796                         s/\xe1\x45/È/gm ;
797                         s/\xe1\x49/Ì/gm ;
798                         s/\xe1\x4f/Ò/gm ;
799                         s/\xe1\x55/Ù/gm ;
800                         s/\xe2\x41/Á/gm ;
801                         s/\xe2\x45/É/gm ;
802                         s/\xe2\x49/Í/gm ;
803                         s/\xe2\x4f/Ó/gm ;
804                         s/\xe2\x55/Ú/gm ;
805                         s/\xe2\x59/Ý/gm ;
806                         s/\xe2\x61/á/gm ;
807                         s/\xe2\x65/é/gm ;
808                         s/\xe2\x69/í/gm ;
809                         s/\xe2\x6f/ó/gm ;
810                         s/\xe2\x75/ú/gm ;
811                         s/\xe2\x79/ý/gm ;
812                         s/\xe3\x41/Â/gm ;
813                         s/\xe3\x45/Ê/gm ;
814                         s/\xe3\x49/Î/gm ;
815                         s/\xe3\x4f/Ô/gm ;
816                         s/\xe3\x55/Û/gm ;
817                         s/\xe3\x61/â/gm ;
818                         s/\xe3\x65/ê/gm ;
819                         s/\xe3\x69/î/gm ;
820                         s/\xe3\x6f/ô/gm ;
821                         s/\xe3\x75/û/gm ;
822                         s/\xe4\x41/Ã/gm ;
823                         s/\xe4\x4e/Ñ/gm ;
824                         s/\xe4\x4f/Õ/gm ;
825                         s/\xe4\x61/ã/gm ;
826                         s/\xe4\x6e/ñ/gm ;
827                         s/\xe4\x6f/õ/gm ;
828                         s/\xe8\x45/Ë/gm ;
829                         s/\xe8\x49/Ï/gm ;
830                         s/\xe8\x65/ë/gm ;
831                         s/\xe8\x69/ï/gm ;
832                         s/\xe8\x76/ÿ/gm ;
833                         s/\xe9\x41/Ä/gm ;
834                         s/\xe9\x4f/Ö/gm ;
835                         s/\xe9\x55/Ü/gm ;
836                         s/\xe9\x61/ä/gm ;
837                         s/\xe9\x6f/ö/gm ;
838                         s/\xe9\x75/ü/gm ;
839                         s/\xea\x41/Å/gm ;
840                         s/\xea\x61/å/gm ;
841                         # this handles non-sorting blocks (if implementation requires this)
842                         $string = nsb_clean($_) ;
843                 }
844         }
845         return($string) ;
846 }
847
848 sub nsb_clean {
849         my $NSB = '\x88' ;              # NSB : begin Non Sorting Block
850         my $NSE = '\x89' ;              # NSE : Non Sorting Block end
851         # handles non sorting blocks
852         my ($string) = @_ ;
853         $_ = $string ;
854         s/$NSB/(/gm ;
855         s/[ ]{0,1}$NSE/) /gm ;
856         $string = $_ ;
857         return($string) ;
858 }
859
860 sub FindDuplicate {
861         my ($record,$authtypecode)=@_;
862         warn "IN for ".$record->as_formatted;
863         my $dbh = C4::Context->dbh;
864
865 #       warn "".$record->as_formatted;
866         my $sth = $dbh->prepare("select auth_tag_to_report,summary from auth_types where authtypecode=?");
867         $sth->execute($authtypecode);
868         my ($auth_tag_to_report,$taglist) = $sth->fetchrow;
869         $sth->finish;
870         # build a request for authoritysearch
871         my (@tags, @and_or, @excluding, @operator, @value, $offset, $length);
872         # search on biblio.title
873 #       warn " tag a reporter : $auth_tag_to_report";
874 #       warn "taglist ".$taglist;
875         my @subfield = split /\[/,  $taglist;
876         my $max = @subfield;
877         for (my $i=1; $i<$max;$i++){
878                 warn " ".$subfield[$i];
879                 $subfield[$i]=substr($subfield[$i],3,1);
880 #               warn " ".$subfield[$i];
881         }
882         
883         if ($record->fields($auth_tag_to_report)) {
884                 my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where tagfield=? and authtypecode=? ");
885                 $sth->execute($auth_tag_to_report,$authtypecode);
886 #               warn " field $auth_tag_to_report exists";
887                 while (my ($tag,$subfield) = $sth->fetchrow){
888                         if ($record->field($tag)->subfield($subfield)) {
889                                 warn "tag :".$tag." subfield: $subfield value : ".$record->field($tag)->subfield($subfield);
890                                 push @tags, $tag.$subfield;
891 #                               warn "'".$tag.$subfield."' value :". $record->field($tag)->subfield($subfield);
892                                 push @and_or, "and";
893                                 push @excluding, "";
894                                 push @operator, "=";
895                                 push @value, $record->field($tag)->subfield($subfield);
896                         }
897                 }
898         }
899  
900         my ($finalresult,$nbresult) = authoritysearch($dbh,\@tags,\@and_or,\@excluding,\@operator,\@value,0,10,$authtypecode);
901         # there is at least 1 result => return the 1st one
902         if ($nbresult) {
903                 warn "XXXXX $nbresult => ".@$finalresult[0]->{authid},@$finalresult[0]->{summary};
904                 return @$finalresult[0]->{authid},@$finalresult[0]->{summary};
905         }
906         # no result, returns nothing
907         return;
908 }
909
910
911 END { }       # module clean-up code here (global destructor)
912
913 =back
914
915 =head1 AUTHOR
916
917 Koha Developement team <info@koha.org>
918
919 Paul POULAIN paul.poulain@free.fr
920
921 =cut
922
923 # $Id$
924 # $Log$
925 # Revision 1.19  2005/06/20 14:10:00  tipaul
926 # synch'ing 2.2 and head
927 #
928 # Revision 1.18  2005/06/07 10:00:47  tipaul
929 # adding $b to mainentry (in UNIMARC, for personal names, $a is the surname, $b is the firstname)
930 #
931 # Revision 1.17  2005/06/01 12:51:02  tipaul
932 # some fixes & improvements for dictionnary search in librarian interface
933 #
934 # Revision 1.16  2005/05/04 15:43:43  tipaul
935 # synch'ing 2.2 and head
936 #
937 # Revision 1.9.2.3  2005/04/28 08:45:33  tipaul
938 # porting FindDuplicate feature for authorities from HEAD to rel_2_2, works correctly now.
939 #
940 # Revision 1.9.2.2  2005/02/28 14:03:13  tipaul
941 # * adding search on "main entry" (ie $a subfield) on a given authority (the "search everywhere" field is still here).
942 # * adding a select box to requet "contain" or "begin with" search.
943 # * fixing some bug in authority search (related to "main entry" search)
944 #
945 # Revision 1.9.2.1  2005/02/24 13:12:13  tipaul
946 # 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.
947 # So, it will be done through a cron job.
948 # (/me agree we need some doc for command line scripts)
949 #
950 # Revision 1.9  2004/12/23 09:48:11  tipaul
951 # Minor changes in summary "exploding" (the 3 digits AFTER the subfield were not on the right place).
952 #
953 # Revision 1.8  2004/11/05 10:11:39  tipaul
954 # export auth_count_usage (bugfix)
955 #
956 # Revision 1.7  2004/09/23 16:13:00  tipaul
957 # Bugfix in modification
958 #
959 # Revision 1.6  2004/08/18 16:00:24  tipaul
960 # fixes for authorities management
961 #
962 # Revision 1.5  2004/07/05 13:37:22  doxulting
963 # First step for working authorities
964 #
965 # Revision 1.4  2004/06/22 11:35:37  tipaul
966 # removing % at the beginning of a string to avoid loooonnnngggg searchs
967 #
968 # Revision 1.3  2004/06/17 08:02:13  tipaul
969 # merging tag & subfield in auth_word for better perfs
970 #
971 # Revision 1.2  2004/06/10 08:29:01  tipaul
972 # MARC authority management (continued)
973 #
974 # Revision 1.1  2004/06/07 07:35:01  tipaul
975 # MARC authority management package
976 #