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