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