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