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