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