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