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