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