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