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