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