change ILIKE into LOWER() for compatibility with non-Pg and Pg before 7.1
[freeside.git] / FS / FS / Record.pm
1 package FS::Record;
2
3 use strict;
4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5              $me %dbdef_cache );
6 use subs qw(reload_dbdef);
7 use Exporter;
8 use Carp qw(carp cluck croak confess);
9 use File::CounterFile;
10 use Locale::Country;
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.19;
13 use FS::UID qw(dbh checkruid getotaker datasrc driver_name);
14 use FS::SearchCache;
15 use FS::Msgcat qw(gettext);
16
17 @ISA = qw(Exporter);
18 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
19
20 $DEBUG = 0;
21 $me = '[FS::Record]';
22
23 #ask FS::UID to run this stuff for us later
24 $FS::UID::callback{'FS::Record'} = sub { 
25   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
26   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
27   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
28 };
29
30 =head1 NAME
31
32 FS::Record - Database record objects
33
34 =head1 SYNOPSIS
35
36     use FS::Record;
37     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
38
39     $record = new FS::Record 'table', \%hash;
40     $record = new FS::Record 'table', { 'column' => 'value', ... };
41
42     $record  = qsearchs FS::Record 'table', \%hash;
43     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
44     @records = qsearch  FS::Record 'table', \%hash; 
45     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
46
47     $table = $record->table;
48     $dbdef_table = $record->dbdef_table;
49
50     $value = $record->get('column');
51     $value = $record->getfield('column');
52     $value = $record->column;
53
54     $record->set( 'column' => 'value' );
55     $record->setfield( 'column' => 'value' );
56     $record->column('value');
57
58     %hash = $record->hash;
59
60     $hashref = $record->hashref;
61
62     $error = $record->insert;
63     #$error = $record->add; #deprecated
64
65     $error = $record->delete;
66     #$error = $record->del; #deprecated
67
68     $error = $new_record->replace($old_record);
69     #$error = $new_record->rep($old_record); #deprecated
70
71     $value = $record->unique('column');
72
73     $error = $record->ut_float('column');
74     $error = $record->ut_number('column');
75     $error = $record->ut_numbern('column');
76     $error = $record->ut_money('column');
77     $error = $record->ut_text('column');
78     $error = $record->ut_textn('column');
79     $error = $record->ut_alpha('column');
80     $error = $record->ut_alphan('column');
81     $error = $record->ut_phonen('column');
82     $error = $record->ut_anything('column');
83     $error = $record->ut_name('column');
84
85     $dbdef = reload_dbdef;
86     $dbdef = reload_dbdef "/non/standard/filename";
87     $dbdef = dbdef;
88
89     $quoted_value = _quote($value,'table','field');
90
91     #depriciated
92     $fields = hfields('table');
93     if ( $fields->{Field} ) { # etc.
94
95     @fields = fields 'table'; #as a subroutine
96     @fields = $record->fields; #as a method call
97
98
99 =head1 DESCRIPTION
100
101 (Mostly) object-oriented interface to database records.  Records are currently
102 implemented on top of DBI.  FS::Record is intended as a base class for
103 table-specific classes to inherit from, i.e. FS::cust_main.
104
105 =head1 CONSTRUCTORS
106
107 =over 4
108
109 =item new [ TABLE, ] HASHREF
110
111 Creates a new record.  It doesn't store it in the database, though.  See
112 L<"insert"> for that.
113
114 Note that the object stores this hash reference, not a distinct copy of the
115 hash it points to.  You can ask the object for a copy with the I<hash> 
116 method.
117
118 TABLE can only be omitted when a dervived class overrides the table method.
119
120 =cut
121
122 sub new { 
123   my $proto = shift;
124   my $class = ref($proto) || $proto;
125   my $self = {};
126   bless ($self, $class);
127
128   unless ( defined ( $self->table ) ) {
129     $self->{'Table'} = shift;
130     carp "warning: FS::Record::new called with table name ". $self->{'Table'};
131   }
132
133   my $hashref = $self->{'Hash'} = shift;
134
135   foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) { 
136     $hashref->{$field}='';
137   }
138
139   $self->_cache($hashref, shift) if $self->can('_cache') && @_;
140
141   $self;
142 }
143
144 sub new_or_cached {
145   my $proto = shift;
146   my $class = ref($proto) || $proto;
147   my $self = {};
148   bless ($self, $class);
149
150   $self->{'Table'} = shift unless defined ( $self->table );
151
152   my $hashref = $self->{'Hash'} = shift;
153   my $cache = shift;
154   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
155     my $obj = $cache->cache->{$hashref->{$cache->key}};
156     $obj->_cache($hashref, $cache) if $obj->can('_cache');
157     $obj;
158   } else {
159     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
160   }
161
162 }
163
164 sub create {
165   my $proto = shift;
166   my $class = ref($proto) || $proto;
167   my $self = {};
168   bless ($self, $class);
169   if ( defined $self->table ) {
170     cluck "create constructor is depriciated, use new!";
171     $self->new(@_);
172   } else {
173     croak "FS::Record::create called (not from a subclass)!";
174   }
175 }
176
177 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
178
179 Searches the database for all records matching (at least) the key/value pairs
180 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
181 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
182 objects.
183
184 ###oops, argh, FS::Record::new only lets us create database fields.
185 #Normal behaviour if SELECT is not specified is `*', as in
186 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
187 #feature where you can specify SELECT - remember, the objects returned,
188 #although blessed into the appropriate `FS::TABLE' package, will only have the
189 #fields you specify.  This might have unwanted results if you then go calling
190 #regular FS::TABLE methods
191 #on it.
192
193 =cut
194
195 sub qsearch {
196   my($stable, $record, $select, $extra_sql, $cache ) = @_;
197   #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
198   #for jsearch
199   $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
200   $stable = $1;
201   $select ||= '*';
202   my $dbh = dbh;
203
204   my $table = $cache ? $cache->table : $stable;
205
206   my @fields = grep exists($record->{$_}), fields($table);
207
208   my $statement = "SELECT $select FROM $stable";
209   if ( @fields ) {
210     $statement .= ' WHERE '. join(' AND ', map {
211
212       my $op = '=';
213       my $column = $_;
214       if ( ref($record->{$_}) ) {
215         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
216         #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name !~ /^Pg$/i;
217         if ( uc($op) eq 'ILIKE' ) {
218           $op = 'LIKE';
219           $record->{$_}{'value'} = lc($record->{$_}{'value'});
220           $column = "LOWER($_)";
221         }
222         $record->{$_} = $record->{$_}{'value'}
223       }
224
225       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
226         if ( $op eq '=' ) {
227           if ( driver_name =~ /^Pg$/i ) {
228             qq-( $column IS NULL OR $column = '' )-;
229           } else {
230             qq-( $column IS NULL OR $column = "" )-;
231           }
232         } elsif ( $op eq '!=' ) {
233           if ( driver_name =~ /^Pg$/i ) {
234             qq-( $column IS NOT NULL AND $column != '' )-;
235           } else {
236             qq-( $column IS NOT NULL AND $column != "" )-;
237           }
238         } else {
239           if ( driver_name =~ /^Pg$/i ) {
240             qq-( $column $op '' )-;
241           } else {
242             qq-( $column $op "" )-;
243           }
244         }
245       } else {
246         "$column $op ?";
247       }
248     } @fields );
249   }
250   $statement .= " $extra_sql" if defined($extra_sql);
251
252   warn "[debug]$me $statement\n" if $DEBUG > 1;
253   my $sth = $dbh->prepare($statement)
254     or croak "$dbh->errstr doing $statement";
255
256   my $bind = 1;
257
258   foreach my $field (
259     grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
260   ) {
261     if ( $record->{$field} =~ /^\d+(\.\d+)?$/
262          && $dbdef->table($table)->column($field)->type =~ /(int)/i
263     ) {
264       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
265     } else {
266       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
267     }
268   }
269
270 #  $sth->execute( map $record->{$_},
271 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
272 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
273
274   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
275
276   $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
277
278   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
279     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
280       #derivied class didn't override new method, so this optimization is safe
281       if ( $cache ) {
282         map {
283           new_or_cached( "FS::$table", { %{$_} }, $cache )
284         } @{$sth->fetchall_arrayref( {} )};
285       } else {
286         map {
287           new( "FS::$table", { %{$_} } )
288         } @{$sth->fetchall_arrayref( {} )};
289       }
290     } else {
291       warn "untested code (class FS::$table uses custom new method)";
292       map {
293         eval 'FS::'. $table. '->new( { %{$_} } )';
294       } @{$sth->fetchall_arrayref( {} )};
295     }
296   } else {
297     cluck "warning: FS::$table not loaded; returning FS::Record objects";
298     map {
299       FS::Record->new( $table, { %{$_} } );
300     } @{$sth->fetchall_arrayref( {} )};
301   }
302
303 }
304
305 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
306
307 Experimental JOINed search method.  Using this method, you can execute a
308 single SELECT spanning multiple tables, and cache the results for subsequent
309 method calls.  Interface will almost definately change in an incompatible
310 fashion.
311
312 Arguments: 
313
314 =cut
315
316 sub jsearch {
317   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
318   my $cache = FS::SearchCache->new( $ptable, $pkey );
319   my %saw;
320   ( $cache,
321     grep { !$saw{$_->getfield($pkey)}++ }
322       qsearch($table, $record, $select, $extra_sql, $cache )
323   );
324 }
325
326 =item qsearchs TABLE, HASHREF
327
328 Same as qsearch, except that if more than one record matches, it B<carp>s but
329 returns the first.  If this happens, you either made a logic error in asking
330 for a single item, or your data is corrupted.
331
332 =cut
333
334 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
335   my(@result) = qsearch(@_);
336   carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
337     #should warn more vehemently if the search was on a primary key?
338   scalar(@result) ? ($result[0]) : ();
339 }
340
341 =back
342
343 =head1 METHODS
344
345 =over 4
346
347 =item table
348
349 Returns the table name.
350
351 =cut
352
353 sub table {
354 #  cluck "warning: FS::Record::table depriciated; supply one in subclass!";
355   my $self = shift;
356   $self -> {'Table'};
357 }
358
359 =item dbdef_table
360
361 Returns the DBIx::DBSchema::Table object for the table.
362
363 =cut
364
365 sub dbdef_table {
366   my($self)=@_;
367   my($table)=$self->table;
368   $dbdef->table($table);
369 }
370
371 =item get, getfield COLUMN
372
373 Returns the value of the column/field/key COLUMN.
374
375 =cut
376
377 sub get {
378   my($self,$field) = @_;
379   # to avoid "Use of unitialized value" errors
380   if ( defined ( $self->{Hash}->{$field} ) ) {
381     $self->{Hash}->{$field};
382   } else { 
383     '';
384   }
385 }
386 sub getfield {
387   my $self = shift;
388   $self->get(@_);
389 }
390
391 =item set, setfield COLUMN, VALUE
392
393 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
394
395 =cut
396
397 sub set { 
398   my($self,$field,$value) = @_;
399   $self->{'Hash'}->{$field} = $value;
400 }
401 sub setfield {
402   my $self = shift;
403   $self->set(@_);
404 }
405
406 =item AUTLOADED METHODS
407
408 $record->column is a synonym for $record->get('column');
409
410 $record->column('value') is a synonym for $record->set('column','value');
411
412 =cut
413
414 # readable/safe
415 sub AUTOLOAD {
416   my($self,$value)=@_;
417   my($field)=$AUTOLOAD;
418   $field =~ s/.*://;
419   if ( defined($value) ) {
420     confess "errant AUTOLOAD $field for $self (arg $value)"
421       unless $self->can('setfield');
422     $self->setfield($field,$value);
423   } else {
424     confess "errant AUTOLOAD $field for $self (no args)"
425       unless $self->can('getfield');
426     $self->getfield($field);
427   }    
428 }
429
430 # efficient
431 #sub AUTOLOAD {
432 #  my $field = $AUTOLOAD;
433 #  $field =~ s/.*://;
434 #  if ( defined($_[1]) ) {
435 #    $_[0]->setfield($field, $_[1]);
436 #  } else {
437 #    $_[0]->getfield($field);
438 #  }    
439 #}
440
441 =item hash
442
443 Returns a list of the column/value pairs, usually for assigning to a new hash.
444
445 To make a distinct duplicate of an FS::Record object, you can do:
446
447     $new = new FS::Record ( $old->table, { $old->hash } );
448
449 =cut
450
451 sub hash {
452   my($self) = @_;
453   %{ $self->{'Hash'} }; 
454 }
455
456 =item hashref
457
458 Returns a reference to the column/value hash.
459
460 =cut
461
462 sub hashref {
463   my($self) = @_;
464   $self->{'Hash'};
465 }
466
467 =item insert
468
469 Inserts this record to the database.  If there is an error, returns the error,
470 otherwise returns false.
471
472 =cut
473
474 sub insert {
475   my $self = shift;
476
477   my $error = $self->check;
478   return $error if $error;
479
480   #single-field unique keys are given a value if false
481   #(like MySQL's AUTO_INCREMENT)
482   foreach ( $self->dbdef_table->unique->singles ) {
483     $self->unique($_) unless $self->getfield($_);
484   }
485   #and also the primary key
486   my $primary_key = $self->dbdef_table->primary_key;
487   $self->unique($primary_key) 
488     if $primary_key && ! $self->getfield($primary_key);
489
490   #false laziness w/delete
491   my @fields =
492     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
493     $self->fields
494   ;
495   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
496   #eslaf
497
498   my $statement = "INSERT INTO ". $self->table. " ( ".
499       join( ', ', @fields ).
500     ") VALUES (".
501       join( ', ', @values ).
502     ")"
503   ;
504   warn "[debug]$me $statement\n" if $DEBUG > 1;
505   my $sth = dbh->prepare($statement) or return dbh->errstr;
506
507   my $h_sth;
508   if ( defined $dbdef->table('h_'. $self->table) ) {
509     my $h_statement = $self->_h_statement('insert');
510     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
511     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
512   } else {
513     $h_sth = '';
514   }
515
516   local $SIG{HUP} = 'IGNORE';
517   local $SIG{INT} = 'IGNORE';
518   local $SIG{QUIT} = 'IGNORE'; 
519   local $SIG{TERM} = 'IGNORE';
520   local $SIG{TSTP} = 'IGNORE';
521   local $SIG{PIPE} = 'IGNORE';
522
523   $sth->execute or return $sth->errstr;
524   $h_sth->execute or return $h_sth->errstr if $h_sth;
525   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
526
527   '';
528 }
529
530 =item add
531
532 Depriciated (use insert instead).
533
534 =cut
535
536 sub add {
537   cluck "warning: FS::Record::add depriciated!";
538   insert @_; #call method in this scope
539 }
540
541 =item delete
542
543 Delete this record from the database.  If there is an error, returns the error,
544 otherwise returns false.
545
546 =cut
547
548 sub delete {
549   my $self = shift;
550
551   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
552     map {
553       $self->getfield($_) eq ''
554         #? "( $_ IS NULL OR $_ = \"\" )"
555         ? ( driver_name =~ /^Pg$/i
556               ? "$_ IS NULL"
557               : "( $_ IS NULL OR $_ = \"\" )"
558           )
559         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
560     } ( $self->dbdef_table->primary_key )
561           ? ( $self->dbdef_table->primary_key)
562           : $self->fields
563   );
564   warn "[debug]$me $statement\n" if $DEBUG > 1;
565   my $sth = dbh->prepare($statement) or return dbh->errstr;
566
567   my $h_sth;
568   if ( defined $dbdef->table('h_'. $self->table) ) {
569     my $h_statement = $self->_h_statement('delete');
570     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
571     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
572   } else {
573     $h_sth = '';
574   }
575
576   local $SIG{HUP} = 'IGNORE';
577   local $SIG{INT} = 'IGNORE';
578   local $SIG{QUIT} = 'IGNORE'; 
579   local $SIG{TERM} = 'IGNORE';
580   local $SIG{TSTP} = 'IGNORE';
581   local $SIG{PIPE} = 'IGNORE';
582
583   my $rc = $sth->execute or return $sth->errstr;
584   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
585   $h_sth->execute or return $h_sth->errstr if $h_sth;
586   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
587
588   #no need to needlessly destoy the data either (causes problems actually)
589   #undef $self; #no need to keep object!
590
591   '';
592 }
593
594 =item del
595
596 Depriciated (use delete instead).
597
598 =cut
599
600 sub del {
601   cluck "warning: FS::Record::del depriciated!";
602   &delete(@_); #call method in this scope
603 }
604
605 =item replace OLD_RECORD
606
607 Replace the OLD_RECORD with this one in the database.  If there is an error,
608 returns the error, otherwise returns false.
609
610 =cut
611
612 sub replace {
613   my ( $new, $old ) = ( shift, shift );
614   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
615
616   return "Records not in same table!" unless $new->table eq $old->table;
617
618   my $primary_key = $old->dbdef_table->primary_key;
619   return "Can't change $primary_key"
620     if $primary_key
621        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
622
623   my $error = $new->check;
624   return $error if $error;
625
626   my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
627   unless ( @diff ) {
628     carp "[warning]$me $new -> replace $old: records identical";
629     return '';
630   }
631
632   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
633     map {
634       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
635     } @diff
636   ). ' WHERE '.
637     join(' AND ',
638       map {
639         $old->getfield($_) eq ''
640           #? "( $_ IS NULL OR $_ = \"\" )"
641           ? ( driver_name =~ /^Pg$/i
642                 ? "$_ IS NULL"
643                 : "( $_ IS NULL OR $_ = \"\" )"
644             )
645           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
646       } ( $primary_key ? ( $primary_key ) : $old->fields )
647     )
648   ;
649   warn "[debug]$me $statement\n" if $DEBUG > 1;
650   my $sth = dbh->prepare($statement) or return dbh->errstr;
651
652   my $h_old_sth;
653   if ( defined $dbdef->table('h_'. $old->table) ) {
654     my $h_old_statement = $old->_h_statement('replace_old');
655     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
656     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
657   } else {
658     $h_old_sth = '';
659   }
660
661   my $h_new_sth;
662   if ( defined $dbdef->table('h_'. $new->table) ) {
663     my $h_new_statement = $new->_h_statement('replace_new');
664     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
665     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
666   } else {
667     $h_new_sth = '';
668   }
669
670   local $SIG{HUP} = 'IGNORE';
671   local $SIG{INT} = 'IGNORE';
672   local $SIG{QUIT} = 'IGNORE'; 
673   local $SIG{TERM} = 'IGNORE';
674   local $SIG{TSTP} = 'IGNORE';
675   local $SIG{PIPE} = 'IGNORE';
676
677   my $rc = $sth->execute or return $sth->errstr;
678   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
679   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
680   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
681   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
682
683   '';
684
685 }
686
687 =item rep
688
689 Depriciated (use replace instead).
690
691 =cut
692
693 sub rep {
694   cluck "warning: FS::Record::rep depriciated!";
695   replace @_; #call method in this scope
696 }
697
698 =item check
699
700 Not yet implemented, croaks.  Derived classes should provide a check method.
701
702 =cut
703
704 sub check {
705   confess "FS::Record::check not implemented; supply one in subclass!";
706 }
707
708 sub _h_statement {
709   my( $self, $action ) = @_;
710
711   my @fields =
712     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
713     $self->fields
714   ;
715   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
716
717   "INSERT INTO h_". $self->table. " ( ".
718       join(', ', qw(history_date history_user history_action), @fields ).
719     ") VALUES (".
720       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
721     ")"
722   ;
723 }
724
725 =item unique COLUMN
726
727 Replaces COLUMN in record with a unique number.  Called by the B<add> method
728 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
729 Returns the new value.
730
731 =cut
732
733 sub unique {
734   my($self,$field) = @_;
735   my($table)=$self->table;
736
737   #croak("&FS::UID::checkruid failed") unless &checkruid;
738
739   croak "Unique called on field $field, but it is ",
740         $self->getfield($field),
741         ", not null!"
742     if $self->getfield($field);
743
744   #warn "table $table is tainted" if is_tainted($table);
745   #warn "field $field is tainted" if is_tainted($field);
746
747   my($counter) = new File::CounterFile "$table.$field",0;
748 # hack for web demo
749 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
750 #  my($user)=$1;
751 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
752 # endhack
753
754   my($index)=$counter->inc;
755   $index=$counter->inc
756     while qsearchs($table,{$field=>$index}); #just in case
757
758   $index =~ /^(\d*)$/;
759   $index=$1;
760
761   $self->setfield($field,$index);
762
763 }
764
765 =item ut_float COLUMN
766
767 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
768 null.  If there is an error, returns the error, otherwise returns false.
769
770 =cut
771
772 sub ut_float {
773   my($self,$field)=@_ ;
774   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
775    $self->getfield($field) =~ /^(\d+)$/ ||
776    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
777    $self->getfield($field) =~ /^(\d+e\d+)$/)
778     or return "Illegal or empty (float) $field: ". $self->getfield($field);
779   $self->setfield($field,$1);
780   '';
781 }
782
783 =item ut_number COLUMN
784
785 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
786 is an error, returns the error, otherwise returns false.
787
788 =cut
789
790 sub ut_number {
791   my($self,$field)=@_;
792   $self->getfield($field) =~ /^(\d+)$/
793     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
794   $self->setfield($field,$1);
795   '';
796 }
797
798 =item ut_numbern COLUMN
799
800 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
801 an error, returns the error, otherwise returns false.
802
803 =cut
804
805 sub ut_numbern {
806   my($self,$field)=@_;
807   $self->getfield($field) =~ /^(\d*)$/
808     or return "Illegal (numeric) $field: ". $self->getfield($field);
809   $self->setfield($field,$1);
810   '';
811 }
812
813 =item ut_money COLUMN
814
815 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
816 is an error, returns the error, otherwise returns false.
817
818 =cut
819
820 sub ut_money {
821   my($self,$field)=@_;
822   $self->setfield($field, 0) if $self->getfield($field) eq '';
823   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
824     or return "Illegal (money) $field: ". $self->getfield($field);
825   #$self->setfield($field, "$1$2$3" || 0);
826   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
827   '';
828 }
829
830 =item ut_text COLUMN
831
832 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
833 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
834 May not be null.  If there is an error, returns the error, otherwise returns
835 false.
836
837 =cut
838
839 sub ut_text {
840   my($self,$field)=@_;
841   #warn "msgcat ". \&msgcat. "\n";
842   #warn "notexist ". \&notexist. "\n";
843   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
844   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
845     or return gettext('illegal_or_empty_text'). " $field: ".
846                $self->getfield($field);
847   $self->setfield($field,$1);
848   '';
849 }
850
851 =item ut_textn COLUMN
852
853 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
854 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
855 May be null.  If there is an error, returns the error, otherwise returns false.
856
857 =cut
858
859 sub ut_textn {
860   my($self,$field)=@_;
861   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
862     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
863   $self->setfield($field,$1);
864   '';
865 }
866
867 =item ut_alpha COLUMN
868
869 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
870 an error, returns the error, otherwise returns false.
871
872 =cut
873
874 sub ut_alpha {
875   my($self,$field)=@_;
876   $self->getfield($field) =~ /^(\w+)$/
877     or return "Illegal or empty (alphanumeric) $field: ".
878               $self->getfield($field);
879   $self->setfield($field,$1);
880   '';
881 }
882
883 =item ut_alpha COLUMN
884
885 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
886 error, returns the error, otherwise returns false.
887
888 =cut
889
890 sub ut_alphan {
891   my($self,$field)=@_;
892   $self->getfield($field) =~ /^(\w*)$/ 
893     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
894   $self->setfield($field,$1);
895   '';
896 }
897
898 =item ut_phonen COLUMN [ COUNTRY ]
899
900 Check/untaint phone numbers.  May be null.  If there is an error, returns
901 the error, otherwise returns false.
902
903 Takes an optional two-letter ISO country code; without it or with unsupported
904 countries, ut_phonen simply calls ut_alphan.
905
906 =cut
907
908 sub ut_phonen {
909   my( $self, $field, $country ) = @_;
910   return $self->ut_alphan($field) unless defined $country;
911   my $phonen = $self->getfield($field);
912   if ( $phonen eq '' ) {
913     $self->setfield($field,'');
914   } elsif ( $country eq 'US' || $country eq 'CA' ) {
915     $phonen =~ s/\D//g;
916     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
917       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
918     $phonen = "$1-$2-$3";
919     $phonen .= " x$4" if $4;
920     $self->setfield($field,$phonen);
921   } else {
922     warn "warning: don't know how to check phone numbers for country $country";
923     return $self->ut_textn($field);
924   }
925   '';
926 }
927
928 =item ut_ip COLUMN
929
930 Check/untaint ip addresses.  IPv4 only for now.
931
932 =cut
933
934 sub ut_ip {
935   my( $self, $field ) = @_;
936   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
937     or return "Illegal (IP address) $field: ". $self->getfield($field);
938   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
939   $self->setfield($field, "$1.$2.$3.$4");
940   '';
941 }
942
943 =item ut_ipn COLUMN
944
945 Check/untaint ip addresses.  IPv4 only for now.  May be null.
946
947 =cut
948
949 sub ut_ipn {
950   my( $self, $field ) = @_;
951   if ( $self->getfield($field) =~ /^()$/ ) {
952     $self->setfield($field,'');
953     '';
954   } else {
955     $self->ut_ip($field);
956   }
957 }
958
959 =item ut_domain COLUMN
960
961 Check/untaint host and domain names.
962
963 =cut
964
965 sub ut_domain {
966   my( $self, $field ) = @_;
967   #$self->getfield($field) =~/^(\w+\.)*\w+$/
968   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
969     or return "Illegal (domain) $field: ". $self->getfield($field);
970   $self->setfield($field,$1);
971   '';
972 }
973
974 =item ut_name COLUMN
975
976 Check/untaint proper names; allows alphanumerics, spaces and the following
977 punctuation: , . - '
978
979 May not be null.
980
981 =cut
982
983 sub ut_name {
984   my( $self, $field ) = @_;
985   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
986     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
987   $self->setfield($field,$1);
988   '';
989 }
990
991 =item ut_zip COLUMN
992
993 Check/untaint zip codes.
994
995 =cut
996
997 sub ut_zip {
998   my( $self, $field, $country ) = @_;
999   if ( $country eq 'US' ) {
1000     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1001       or return gettext('illegal_zip'). " $field for country $country: ".
1002                 $self->getfield($field);
1003     $self->setfield($field,$1);
1004   } else {
1005     $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1006       or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1007     $self->setfield($field,$1);
1008   }
1009   '';
1010 }
1011
1012 =item ut_country COLUMN
1013
1014 Check/untaint country codes.  Country names are changed to codes, if possible -
1015 see L<Locale::Country>.
1016
1017 =cut
1018
1019 sub ut_country {
1020   my( $self, $field ) = @_;
1021   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1022     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1023          && country2code($1) ) {
1024       $self->setfield($field,uc(country2code($1)));
1025     }
1026   }
1027   $self->getfield($field) =~ /^(\w\w)$/
1028     or return "Illegal (country) $field: ". $self->getfield($field);
1029   $self->setfield($field,uc($1));
1030   '';
1031 }
1032
1033 =item ut_anything COLUMN
1034
1035 Untaints arbitrary data.  Be careful.
1036
1037 =cut
1038
1039 sub ut_anything {
1040   my( $self, $field ) = @_;
1041   $self->getfield($field) =~ /^(.*)$/s
1042     or return "Illegal $field: ". $self->getfield($field);
1043   $self->setfield($field,$1);
1044   '';
1045 }
1046
1047 =item ut_enum COLUMN CHOICES_ARRAYREF
1048
1049 Check/untaint a column, supplying all possible choices, like the "enum" type.
1050
1051 =cut
1052
1053 sub ut_enum {
1054   my( $self, $field, $choices ) = @_;
1055   foreach my $choice ( @$choices ) {
1056     if ( $self->getfield($field) eq $choice ) {
1057       $self->setfield($choice);
1058       return '';
1059     }
1060   }
1061   return "Illegal (enum) field $field: ". $self->getfield($field);
1062 }
1063
1064 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1065
1066 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1067 on the column first.
1068
1069 =cut
1070
1071 sub ut_foreign_key {
1072   my( $self, $field, $table, $foreign ) = @_;
1073   qsearchs($table, { $foreign => $self->getfield($field) })
1074     or return "Can't find $field ". $self->getfield($field).
1075               " in $table.$foreign";
1076   '';
1077 }
1078
1079 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1080
1081 Like ut_foreign_key, except the null value is also allowed.
1082
1083 =cut
1084
1085 sub ut_foreign_keyn {
1086   my( $self, $field, $table, $foreign ) = @_;
1087   $self->getfield($field)
1088     ? $self->ut_foreign_key($field, $table, $foreign)
1089     : '';
1090 }
1091
1092 =item fields [ TABLE ]
1093
1094 This can be used as both a subroutine and a method call.  It returns a list
1095 of the columns in this record's table, or an explicitly specified table.
1096 (See L<DBIx::DBSchema::Table>).
1097
1098 =cut
1099
1100 # Usage: @fields = fields($table);
1101 #        @fields = $record->fields;
1102 sub fields {
1103   my $something = shift;
1104   my $table;
1105   if ( ref($something) ) {
1106     $table = $something->table;
1107   } else {
1108     $table = $something;
1109   }
1110   #croak "Usage: \@fields = fields(\$table)\n   or: \@fields = \$record->fields" unless $table;
1111   my($table_obj) = $dbdef->table($table);
1112   confess "Unknown table $table" unless $table_obj;
1113   $table_obj->columns;
1114 }
1115
1116 =back
1117
1118 =head1 SUBROUTINES
1119
1120 =over 4
1121
1122 =item reload_dbdef([FILENAME])
1123
1124 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1125 non-default filename.  This command is executed at startup unless
1126 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1127
1128 =cut
1129
1130 sub reload_dbdef {
1131   my $file = shift || $dbdef_file;
1132
1133   unless ( exists $dbdef_cache{$file} ) {
1134     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1135     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1136                             or die "can't load database schema from $file";
1137   } else {
1138     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1139   }
1140   $dbdef = $dbdef_cache{$file};
1141 }
1142
1143 =item dbdef
1144
1145 Returns the current database definition.  See L<DBIx::DBSchema>.
1146
1147 =cut
1148
1149 sub dbdef { $dbdef; }
1150
1151 =item _quote VALUE, TABLE, COLUMN
1152
1153 This is an internal function used to construct SQL statements.  It returns
1154 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1155 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1156
1157 =cut
1158
1159 sub _quote {
1160   my($value,$table,$field)=@_;
1161   my($dbh)=dbh;
1162   if ( $value =~ /^\d+(\.\d+)?$/ && 
1163 #       ! ( datatype($table,$field) =~ /^char/ ) 
1164        ! $dbdef->table($table)->column($field)->type =~ /(char|binary|text)$/i 
1165   ) {
1166     $value;
1167   } else {
1168     $dbh->quote($value);
1169   }
1170 }
1171
1172 =item hfields TABLE
1173
1174 This is depriciated.  Don't use it.
1175
1176 It returns a hash-type list with the fields of this record's table set true.
1177
1178 =cut
1179
1180 sub hfields {
1181   carp "warning: hfields is depriciated";
1182   my($table)=@_;
1183   my(%hash);
1184   foreach (fields($table)) {
1185     $hash{$_}=1;
1186   }
1187   \%hash;
1188 }
1189
1190 sub _dump {
1191   my($self)=@_;
1192   join("\n", map {
1193     "$_: ". $self->getfield($_). "|"
1194   } (fields($self->table)) );
1195 }
1196
1197 sub DESTROY { return; }
1198
1199 #sub DESTROY {
1200 #  my $self = shift;
1201 #  #use Carp qw(cluck);
1202 #  #cluck "DESTROYING $self";
1203 #  warn "DESTROYING $self";
1204 #}
1205
1206 #sub is_tainted {
1207 #             return ! eval { join('',@_), kill 0; 1; };
1208 #         }
1209
1210 =back
1211
1212 =head1 BUGS
1213
1214 This module should probably be renamed, since much of the functionality is
1215 of general use.  It is not completely unlike Adapter::DBI (see below).
1216
1217 Exported qsearch and qsearchs should be depriciated in favor of method calls
1218 (against an FS::Record object like the old search and searchs that qsearch
1219 and qsearchs were on top of.)
1220
1221 The whole fields / hfields mess should be removed.
1222
1223 The various WHERE clauses should be subroutined.
1224
1225 table string should be depriciated in favor of DBIx::DBSchema::Table.
1226
1227 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1228 true maps to the database (and WHERE clauses) would also help.
1229
1230 The ut_ methods should ask the dbdef for a default length.
1231
1232 ut_sqltype (like ut_varchar) should all be defined
1233
1234 A fallback check method should be provided which uses the dbdef.
1235
1236 The ut_money method assumes money has two decimal digits.
1237
1238 The Pg money kludge in the new method only strips `$'.
1239
1240 The ut_phonen method only checks US-style phone numbers.
1241
1242 The _quote function should probably use ut_float instead of a regex.
1243
1244 All the subroutines probably should be methods, here or elsewhere.
1245
1246 Probably should borrow/use some dbdef methods where appropriate (like sub
1247 fields)
1248
1249 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1250 or allow it to be set.  Working around it is ugly any way around - DBI should
1251 be fixed.  (only affects RDBMS which return uppercase column names)
1252
1253 ut_zip should take an optional country like ut_phone.
1254
1255 =head1 SEE ALSO
1256
1257 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1258
1259 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1260
1261 =cut
1262
1263 1;
1264