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