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