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