add pkey to batch payments and fix a doc typo
[freeside.git] / FS / FS / Record.pm
1 package FS::Record;
2
3 use strict;
4 use vars qw($dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG);
5 use subs qw(reload_dbdef);
6 use Exporter;
7 use Carp qw(carp cluck croak confess);
8 use File::CounterFile;
9 use Locale::Country;
10 use DBIx::DBSchema;
11 use FS::UID qw(dbh checkruid getotaker datasrc driver_name);
12
13 @ISA = qw(Exporter);
14 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef);
15
16 $DEBUG = 0;
17
18 #ask FS::UID to run this stuff for us later
19 $FS::UID::callback{'FS::Record'} = sub { 
20   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
21   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
22   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
23 };
24
25 =head1 NAME
26
27 FS::Record - Database record objects
28
29 =head1 SYNOPSIS
30
31     use FS::Record;
32     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
33
34     $record = new FS::Record 'table', \%hash;
35     $record = new FS::Record 'table', { 'column' => 'value', ... };
36
37     $record  = qsearchs FS::Record 'table', \%hash;
38     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
39     @records = qsearch  FS::Record 'table', \%hash; 
40     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
41
42     $table = $record->table;
43     $dbdef_table = $record->dbdef_table;
44
45     $value = $record->get('column');
46     $value = $record->getfield('column');
47     $value = $record->column;
48
49     $record->set( 'column' => 'value' );
50     $record->setfield( 'column' => 'value' );
51     $record->column('value');
52
53     %hash = $record->hash;
54
55     $hashref = $record->hashref;
56
57     $error = $record->insert;
58     #$error = $record->add; #depriciated
59
60     $error = $record->delete;
61     #$error = $record->del; #depriciated
62
63     $error = $new_record->replace($old_record);
64     #$error = $new_record->rep($old_record); #depriciated
65
66     $value = $record->unique('column');
67
68     $value = $record->ut_float('column');
69     $value = $record->ut_number('column');
70     $value = $record->ut_numbern('column');
71     $value = $record->ut_money('column');
72     $value = $record->ut_text('column');
73     $value = $record->ut_textn('column');
74     $value = $record->ut_alpha('column');
75     $value = $record->ut_alphan('column');
76     $value = $record->ut_phonen('column');
77     $value = $record->ut_anything('column');
78     $value = $record->ut_name('column');
79
80     $dbdef = reload_dbdef;
81     $dbdef = reload_dbdef "/non/standard/filename";
82     $dbdef = dbdef;
83
84     $quoted_value = _quote($value,'table','field');
85
86     #depriciated
87     $fields = hfields('table');
88     if ( $fields->{Field} ) { # etc.
89
90     @fields = fields 'table'; #as a subroutine
91     @fields = $record->fields; #as a method call
92
93
94 =head1 DESCRIPTION
95
96 (Mostly) object-oriented interface to database records.  Records are currently
97 implemented on top of DBI.  FS::Record is intended as a base class for
98 table-specific classes to inherit from, i.e. FS::cust_main.
99
100 =head1 CONSTRUCTORS
101
102 =over 4
103
104 =item new [ TABLE, ] HASHREF
105
106 Creates a new record.  It doesn't store it in the database, though.  See
107 L<"insert"> for that.
108
109 Note that the object stores this hash reference, not a distinct copy of the
110 hash it points to.  You can ask the object for a copy with the I<hash> 
111 method.
112
113 TABLE can only be omitted when a dervived class overrides the table method.
114
115 =cut
116
117 sub new { 
118   my $proto = shift;
119   my $class = ref($proto) || $proto;
120   my $self = {};
121   bless ($self, $class);
122
123   $self->{'Table'} = shift unless defined ( $self->table );
124
125   my $hashref = $self->{'Hash'} = shift;
126
127   foreach my $field ( $self->fields ) { 
128     $hashref->{$field}='' unless defined $hashref->{$field};
129     #trim the '$' and ',' from money fields for Pg (belong HERE?)
130     #(what about Pg i18n?)
131     if ( driver_name =~ /^Pg$/i
132          && $self->dbdef_table->column($field)->type eq 'money' ) {
133       ${$hashref}{$field} =~ s/^\$//;
134       ${$hashref}{$field} =~ s/\,//;
135     }
136   }
137
138   $self;
139 }
140
141 sub create {
142   my $proto = shift;
143   my $class = ref($proto) || $proto;
144   my $self = {};
145   bless ($self, $class);
146   if ( defined $self->table ) {
147     cluck "create constructor is depriciated, use new!";
148     $self->new(@_);
149   } else {
150     croak "FS::Record::create called (not from a subclass)!";
151   }
152 }
153
154 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL
155
156 Searches the database for all records matching (at least) the key/value pairs
157 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
158 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
159 objects.
160
161 ###oops, argh, FS::Record::new only lets us create database fields.
162 #Normal behaviour if SELECT is not specified is `*', as in
163 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
164 #feature where you can specify SELECT - remember, the objects returned,
165 #although blessed into the appropriate `FS::TABLE' package, will only have the
166 #fields you specify.  This might have unwanted results if you then go calling
167 #regular FS::TABLE methods
168 #on it.
169
170 =cut
171
172 sub qsearch {
173   my($table, $record, $select, $extra_sql ) = @_;
174   $table =~ /^([\w\_]+)$/ or die "Illegal table: $table";
175   $table = $1;
176   $select ||= '*';
177   my $dbh = dbh;
178
179   my @fields = grep exists($record->{$_}), fields($table);
180
181   my $statement = "SELECT $select FROM $table";
182   if ( @fields ) {
183     $statement .= ' WHERE '. join(' AND ', map {
184       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
185         if ( driver_name =~ /^Pg$/i ) {
186           "$_ IS NULL";
187         } else {
188           qq-( $_ IS NULL OR $_ = "" )-;
189         }
190       } else {
191         "$_ = ?";
192       }
193     } @fields );
194   }
195   $statement .= " $extra_sql" if defined($extra_sql);
196
197   warn $statement if $DEBUG;
198   my $sth = $dbh->prepare($statement)
199     or croak "$dbh->errstr doing $statement";
200
201   $sth->execute( map $record->{$_},
202     grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
203   ) or croak "Error executing \"$statement\": ". $dbh->errstr;
204   $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
205
206   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
207     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
208       #derivied class didn't override new method, so this optimization is safe
209       map {
210         new( "FS::$table", { %{$_} } )
211       } @{$sth->fetchall_arrayref( {} )};
212     } else {
213       warn "untested code (class FS::$table uses custom new method)";
214       map {
215         eval 'FS::'. $table. '->new( { %{$_} } )';
216       } @{$sth->fetchall_arrayref( {} )};
217     }
218   } else {
219     cluck "warning: FS::$table not loaded; returning FS::Record objects";
220     map {
221       FS::Record->new( $table, { %{$_} } );
222     } @{$sth->fetchall_arrayref( {} )};
223   }
224
225 }
226
227 =item qsearchs TABLE, HASHREF
228
229 Same as qsearch, except that if more than one record matches, it B<carp>s but
230 returns the first.  If this happens, you either made a logic error in asking
231 for a single item, or your data is corrupted.
232
233 =cut
234
235 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
236   my(@result) = qsearch(@_);
237   carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
238     #should warn more vehemently if the search was on a primary key?
239   scalar(@result) ? ($result[0]) : ();
240 }
241
242 =back
243
244 =head1 METHODS
245
246 =over 4
247
248 =item table
249
250 Returns the table name.
251
252 =cut
253
254 sub table {
255 #  cluck "warning: FS::Record::table depriciated; supply one in subclass!";
256   my $self = shift;
257   $self -> {'Table'};
258 }
259
260 =item dbdef_table
261
262 Returns the FS::dbdef_table object for the table.
263
264 =cut
265
266 sub dbdef_table {
267   my($self)=@_;
268   my($table)=$self->table;
269   $dbdef->table($table);
270 }
271
272 =item get, getfield COLUMN
273
274 Returns the value of the column/field/key COLUMN.
275
276 =cut
277
278 sub get {
279   my($self,$field) = @_;
280   # to avoid "Use of unitialized value" errors
281   if ( defined ( $self->{Hash}->{$field} ) ) {
282     $self->{Hash}->{$field};
283   } else { 
284     '';
285   }
286 }
287 sub getfield {
288   my $self = shift;
289   $self->get(@_);
290 }
291
292 =item set, setfield COLUMN, VALUE
293
294 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
295
296 =cut
297
298 sub set { 
299   my($self,$field,$value) = @_;
300   $self->{'Hash'}->{$field} = $value;
301 }
302 sub setfield {
303   my $self = shift;
304   $self->set(@_);
305 }
306
307 =item AUTLOADED METHODS
308
309 $record->column is a synonym for $record->get('column');
310
311 $record->column('value') is a synonym for $record->set('column','value');
312
313 =cut
314
315 sub AUTOLOAD {
316   my($self,$value)=@_;
317   my($field)=$AUTOLOAD;
318   $field =~ s/.*://;
319   if ( defined($value) ) {
320     confess "errant AUTOLOAD $field for $self (arg $value)"
321       unless $self->can('setfield');
322     $self->setfield($field,$value);
323   } else {
324     $self->getfield($field);
325   }    
326 }
327
328 =item hash
329
330 Returns a list of the column/value pairs, usually for assigning to a new hash.
331
332 To make a distinct duplicate of an FS::Record object, you can do:
333
334     $new = new FS::Record ( $old->table, { $old->hash } );
335
336 =cut
337
338 sub hash {
339   my($self) = @_;
340   %{ $self->{'Hash'} }; 
341 }
342
343 =item hashref
344
345 Returns a reference to the column/value hash.
346
347 =cut
348
349 sub hashref {
350   my($self) = @_;
351   $self->{'Hash'};
352 }
353
354 =item insert
355
356 Inserts this record to the database.  If there is an error, returns the error,
357 otherwise returns false.
358
359 =cut
360
361 sub insert {
362   my $self = shift;
363
364   my $error = $self->check;
365   return $error if $error;
366
367   #single-field unique keys are given a value if false
368   #(like MySQL's AUTO_INCREMENT)
369   foreach ( $self->dbdef_table->unique->singles ) {
370     $self->unique($_) unless $self->getfield($_);
371   }
372   #and also the primary key
373   my $primary_key = $self->dbdef_table->primary_key;
374   $self->unique($primary_key) 
375     if $primary_key && ! $self->getfield($primary_key);
376
377   my @fields =
378     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
379     $self->fields
380   ;
381
382   my $statement = "INSERT INTO ". $self->table. " ( ".
383       join(', ',@fields ).
384     ") VALUES (".
385       join(', ',map(_quote($self->getfield($_),$self->table,$_), @fields)).
386     ")"
387   ;
388   my $sth = dbh->prepare($statement) or return dbh->errstr;
389
390   local $SIG{HUP} = 'IGNORE';
391   local $SIG{INT} = 'IGNORE';
392   local $SIG{QUIT} = 'IGNORE'; 
393   local $SIG{TERM} = 'IGNORE';
394   local $SIG{TSTP} = 'IGNORE';
395   local $SIG{PIPE} = 'IGNORE';
396
397   $sth->execute or return $sth->errstr;
398   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
399
400   '';
401 }
402
403 =item add
404
405 Depriciated (use insert instead).
406
407 =cut
408
409 sub add {
410   cluck "warning: FS::Record::add depriciated!";
411   insert @_; #call method in this scope
412 }
413
414 =item delete
415
416 Delete this record from the database.  If there is an error, returns the error,
417 otherwise returns false.
418
419 =cut
420
421 sub delete {
422   my $self = shift;
423
424   my($statement)="DELETE FROM ". $self->table. " WHERE ". join(' AND ',
425     map {
426       $self->getfield($_) eq ''
427         #? "( $_ IS NULL OR $_ = \"\" )"
428         ? ( driver_name =~ /^Pg$/i
429               ? "$_ IS NULL"
430               : "( $_ IS NULL OR $_ = \"\" )"
431           )
432         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
433     } ( $self->dbdef_table->primary_key )
434           ? ( $self->dbdef_table->primary_key)
435           : $self->fields
436   );
437   my $sth = dbh->prepare($statement) or return dbh->errstr;
438
439   local $SIG{HUP} = 'IGNORE';
440   local $SIG{INT} = 'IGNORE';
441   local $SIG{QUIT} = 'IGNORE'; 
442   local $SIG{TERM} = 'IGNORE';
443   local $SIG{TSTP} = 'IGNORE';
444   local $SIG{PIPE} = 'IGNORE';
445
446   my $rc = $sth->execute or return $sth->errstr;
447   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
448   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
449
450   undef $self; #no need to keep object!
451
452   '';
453 }
454
455 =item del
456
457 Depriciated (use delete instead).
458
459 =cut
460
461 sub del {
462   cluck "warning: FS::Record::del depriciated!";
463   &delete(@_); #call method in this scope
464 }
465
466 =item replace OLD_RECORD
467
468 Replace the OLD_RECORD with this one in the database.  If there is an error,
469 returns the error, otherwise returns false.
470
471 =cut
472
473 sub replace {
474   my ( $new, $old ) = ( shift, shift );
475   warn "[debug][FS::Record] $new ->replace $old\n" if $DEBUG;
476
477   my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
478   unless ( @diff ) {
479     carp "[warning][FS::Record] $new -> replace $old: records identical";
480     return '';
481   }
482
483   return "Records not in same table!" unless $new->table eq $old->table;
484
485   my $primary_key = $old->dbdef_table->primary_key;
486   return "Can't change $primary_key"
487     if $primary_key
488        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
489
490   my $error = $new->check;
491   return $error if $error;
492
493   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
494     map {
495       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
496     } @diff
497   ). ' WHERE '.
498     join(' AND ',
499       map {
500         $old->getfield($_) eq ''
501           #? "( $_ IS NULL OR $_ = \"\" )"
502           ? ( driver_name =~ /^Pg$/i
503                 ? "$_ IS NULL"
504                 : "( $_ IS NULL OR $_ = \"\" )"
505             )
506           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
507       } ( $primary_key ? ( $primary_key ) : $old->fields )
508     )
509   ;
510   my $sth = dbh->prepare($statement) or return dbh->errstr;
511
512   local $SIG{HUP} = 'IGNORE';
513   local $SIG{INT} = 'IGNORE';
514   local $SIG{QUIT} = 'IGNORE'; 
515   local $SIG{TERM} = 'IGNORE';
516   local $SIG{TSTP} = 'IGNORE';
517   local $SIG{PIPE} = 'IGNORE';
518
519   my $rc = $sth->execute or return $sth->errstr;
520   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
521   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
522
523   '';
524
525 }
526
527 =item rep
528
529 Depriciated (use replace instead).
530
531 =cut
532
533 sub rep {
534   cluck "warning: FS::Record::rep depriciated!";
535   replace @_; #call method in this scope
536 }
537
538 =item check
539
540 Not yet implemented, croaks.  Derived classes should provide a check method.
541
542 =cut
543
544 sub check {
545   confess "FS::Record::check not implemented; supply one in subclass!";
546 }
547
548 =item unique COLUMN
549
550 Replaces COLUMN in record with a unique number.  Called by the B<add> method
551 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
552 Returns the new value.
553
554 =cut
555
556 sub unique {
557   my($self,$field) = @_;
558   my($table)=$self->table;
559
560   croak("&FS::UID::checkruid failed") unless &checkruid;
561
562   croak "Unique called on field $field, but it is ",
563         $self->getfield($field),
564         ", not null!"
565     if $self->getfield($field);
566
567   #warn "table $table is tainted" if is_tainted($table);
568   #warn "field $field is tainted" if is_tainted($field);
569
570   my($counter) = new File::CounterFile "$table.$field",0;
571 # hack for web demo
572 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
573 #  my($user)=$1;
574 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
575 # endhack
576
577   my($index)=$counter->inc;
578   $index=$counter->inc
579     while qsearchs($table,{$field=>$index}); #just in case
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' || $country eq 'CA' ) {
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_textn($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, $country ) = @_;
818   if ( $country eq 'US' ) {
819     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
820       or return "Illegal (zip) $field for country $country: ".
821                 $self->getfield($field);
822     $self->setfield($field,$1);
823   } else {
824     $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
825       or return "Illegal (zip) $field: ". $self->getfield($field);
826     $self->setfield($field,$1);
827   }
828   '';
829 }
830
831 =item ut_country COLUMN
832
833 Check/untaint country codes.  Country names are changed to codes, if possible -
834 see L<Locale::Country>.
835
836 =cut
837
838 sub ut_country {
839   my( $self, $field ) = @_;
840   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
841     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
842          && country2code($1) ) {
843       $self->setfield($field,uc(country2code($1)));
844     }
845   }
846   $self->getfield($field) =~ /^(\w\w)$/
847     or return "Illegal (country) $field: ". $self->getfield($field);
848   $self->setfield($field,uc($1));
849   '';
850 }
851
852 =item ut_anything COLUMN
853
854 Untaints arbitrary data.  Be careful.
855
856 =cut
857
858 sub ut_anything {
859   my( $self, $field ) = @_;
860   $self->getfield($field) =~ /^(.*)$/s
861     or return "Illegal $field: ". $self->getfield($field);
862   $self->setfield($field,$1);
863   '';
864 }
865
866 =item ut_enum COLUMN CHOICES_ARRAYREF
867
868 Check/untaint a column, supplying all possible choices, like the "enum" type.
869
870 =cut
871
872 sub ut_enum {
873   my( $self, $field, $choices ) = @_;
874   foreach my $choice ( @$choices ) {
875     if ( $self->getfield($field) eq $choice ) {
876       $self->setfield($choice);
877       return '';
878     }
879   }
880   return "Illegal (enum) field $field: ". $self->getfield($field);
881 }
882
883 =item fields [ TABLE ]
884
885 This can be used as both a subroutine and a method call.  It returns a list
886 of the columns in this record's table, or an explicitly specified table.
887 (See L<DBIx::DBSchema::Table>).
888
889 =cut
890
891 # Usage: @fields = fields($table);
892 #        @fields = $record->fields;
893 sub fields {
894   my $something = shift;
895   my $table;
896   if ( ref($something) ) {
897     $table = $something->table;
898   } else {
899     $table = $something;
900   }
901   #croak "Usage: \@fields = fields(\$table)\n   or: \@fields = \$record->fields" unless $table;
902   my($table_obj) = $dbdef->table($table);
903   confess "Unknown table $table" unless $table_obj;
904   $table_obj->columns;
905 }
906
907 =back
908
909 =head1 SUBROUTINES
910
911 =over 4
912
913 =item reload_dbdef([FILENAME])
914
915 Load a database definition (see L<DBIx::DBSchema>), optionally from a
916 non-default filename.  This command is executed at startup unless
917 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
918
919 =cut
920
921 sub reload_dbdef {
922   my $file = shift || $dbdef_file;
923   $dbdef = load DBIx::DBSchema $file;
924 }
925
926 =item dbdef
927
928 Returns the current database definition.  See L<FS::dbdef>.
929
930 =cut
931
932 sub dbdef { $dbdef; }
933
934 =item _quote VALUE, TABLE, COLUMN
935
936 This is an internal function used to construct SQL statements.  It returns
937 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
938 type (see L<FS::dbdef_column>) does not end in `char' or `binary'.
939
940 =cut
941
942 sub _quote {
943   my($value,$table,$field)=@_;
944   my($dbh)=dbh;
945   if ( $value =~ /^\d+(\.\d+)?$/ && 
946 #       ! ( datatype($table,$field) =~ /^char/ ) 
947        ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i ) 
948   ) {
949     $value;
950   } else {
951     $dbh->quote($value);
952   }
953 }
954
955 =item hfields TABLE
956
957 This is depriciated.  Don't use it.
958
959 It returns a hash-type list with the fields of this record's table set true.
960
961 =cut
962
963 sub hfields {
964   carp "warning: hfields is depriciated";
965   my($table)=@_;
966   my(%hash);
967   foreach (fields($table)) {
968     $hash{$_}=1;
969   }
970   \%hash;
971 }
972
973 #sub _dump {
974 #  my($self)=@_;
975 #  join("\n", map {
976 #    "$_: ". $self->getfield($_). "|"
977 #  } (fields($self->table)) );
978 #}
979
980 sub DESTROY { return; }
981
982 #sub DESTROY {
983 #  my $self = shift;
984 #  #use Carp qw(cluck);
985 #  #cluck "DESTROYING $self";
986 #  warn "DESTROYING $self";
987 #}
988
989 #sub is_tainted {
990 #             return ! eval { join('',@_), kill 0; 1; };
991 #         }
992
993 =back
994
995 =head1 VERSION
996
997 $Id: Record.pm,v 1.29 2001-09-16 12:45:35 ivan Exp $
998
999 =head1 BUGS
1000
1001 This module should probably be renamed, since much of the functionality is
1002 of general use.  It is not completely unlike Adapter::DBI (see below).
1003
1004 Exported qsearch and qsearchs should be depriciated in favor of method calls
1005 (against an FS::Record object like the old search and searchs that qsearch
1006 and qsearchs were on top of.)
1007
1008 The whole fields / hfields mess should be removed.
1009
1010 The various WHERE clauses should be subroutined.
1011
1012 table string should be depriciated in favor of FS::dbdef_table.
1013
1014 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1015 true maps to the database (and WHERE clauses) would also help.
1016
1017 The ut_ methods should ask the dbdef for a default length.
1018
1019 ut_sqltype (like ut_varchar) should all be defined
1020
1021 A fallback check method should be provided which uses the dbdef.
1022
1023 The ut_money method assumes money has two decimal digits.
1024
1025 The Pg money kludge in the new method only strips `$'.
1026
1027 The ut_phonen method only checks US-style phone numbers.
1028
1029 The _quote function should probably use ut_float instead of a regex.
1030
1031 All the subroutines probably should be methods, here or elsewhere.
1032
1033 Probably should borrow/use some dbdef methods where appropriate (like sub
1034 fields)
1035
1036 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1037 or allow it to be set.  Working around it is ugly any way around - DBI should
1038 be fixed.  (only affects RDBMS which return uppercase column names)
1039
1040 ut_zip should take an optional country like ut_phone.
1041
1042 =head1 SEE ALSO
1043
1044 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1045
1046 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1047
1048 =cut
1049
1050 1;
1051