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