so we can pass in a time if we're back-filling history records
[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 %virtual_fields_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.23;
13 use FS::UID qw(dbh getotaker datasrc driver_name);
14 use FS::SearchCache;
15 use FS::Msgcat qw(gettext);
16 use FS::Conf;
17
18 use FS::part_virtual_field;
19
20 use Tie::IxHash;
21
22 @ISA = qw(Exporter);
23 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
24
25 $DEBUG = 0;
26 $me = '[FS::Record]';
27
28 my $conf;
29 my $rsa_module;
30 my $rsa_loaded;
31 my $rsa_encrypt;
32 my $rsa_decrypt;
33
34 #ask FS::UID to run this stuff for us later
35 $FS::UID::callback{'FS::Record'} = sub { 
36   $conf = new FS::Conf; 
37   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
38   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
39   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
40 };
41
42 =head1 NAME
43
44 FS::Record - Database record objects
45
46 =head1 SYNOPSIS
47
48     use FS::Record;
49     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
50
51     $record = new FS::Record 'table', \%hash;
52     $record = new FS::Record 'table', { 'column' => 'value', ... };
53
54     $record  = qsearchs FS::Record 'table', \%hash;
55     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
56     @records = qsearch  FS::Record 'table', \%hash; 
57     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
58
59     $table = $record->table;
60     $dbdef_table = $record->dbdef_table;
61
62     $value = $record->get('column');
63     $value = $record->getfield('column');
64     $value = $record->column;
65
66     $record->set( 'column' => 'value' );
67     $record->setfield( 'column' => 'value' );
68     $record->column('value');
69
70     %hash = $record->hash;
71
72     $hashref = $record->hashref;
73
74     $error = $record->insert;
75
76     $error = $record->delete;
77
78     $error = $new_record->replace($old_record);
79
80     # external use deprecated - handled by the database (at least for Pg, mysql)
81     $value = $record->unique('column');
82
83     $error = $record->ut_float('column');
84     $error = $record->ut_number('column');
85     $error = $record->ut_numbern('column');
86     $error = $record->ut_money('column');
87     $error = $record->ut_text('column');
88     $error = $record->ut_textn('column');
89     $error = $record->ut_alpha('column');
90     $error = $record->ut_alphan('column');
91     $error = $record->ut_phonen('column');
92     $error = $record->ut_anything('column');
93     $error = $record->ut_name('column');
94
95     $dbdef = reload_dbdef;
96     $dbdef = reload_dbdef "/non/standard/filename";
97     $dbdef = dbdef;
98
99     $quoted_value = _quote($value,'table','field');
100
101     #deprecated
102     $fields = hfields('table');
103     if ( $fields->{Field} ) { # etc.
104
105     @fields = fields 'table'; #as a subroutine
106     @fields = $record->fields; #as a method call
107
108
109 =head1 DESCRIPTION
110
111 (Mostly) object-oriented interface to database records.  Records are currently
112 implemented on top of DBI.  FS::Record is intended as a base class for
113 table-specific classes to inherit from, i.e. FS::cust_main.
114
115 =head1 CONSTRUCTORS
116
117 =over 4
118
119 =item new [ TABLE, ] HASHREF
120
121 Creates a new record.  It doesn't store it in the database, though.  See
122 L<"insert"> for that.
123
124 Note that the object stores this hash reference, not a distinct copy of the
125 hash it points to.  You can ask the object for a copy with the I<hash> 
126 method.
127
128 TABLE can only be omitted when a dervived class overrides the table method.
129
130 =cut
131
132 sub new { 
133   my $proto = shift;
134   my $class = ref($proto) || $proto;
135   my $self = {};
136   bless ($self, $class);
137
138   unless ( defined ( $self->table ) ) {
139     $self->{'Table'} = shift;
140     carp "warning: FS::Record::new called with table name ". $self->{'Table'};
141   }
142   
143   $self->{'Hash'} = shift;
144
145   foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) { 
146     $self->{'Hash'}{$field}='';
147   }
148
149   $self->_rebless if $self->can('_rebless');
150
151   $self->{'modified'} = 0;
152
153   $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
154
155   $self;
156 }
157
158 sub new_or_cached {
159   my $proto = shift;
160   my $class = ref($proto) || $proto;
161   my $self = {};
162   bless ($self, $class);
163
164   $self->{'Table'} = shift unless defined ( $self->table );
165
166   my $hashref = $self->{'Hash'} = shift;
167   my $cache = shift;
168   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
169     my $obj = $cache->cache->{$hashref->{$cache->key}};
170     $obj->_cache($hashref, $cache) if $obj->can('_cache');
171     $obj;
172   } else {
173     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
174   }
175
176 }
177
178 sub create {
179   my $proto = shift;
180   my $class = ref($proto) || $proto;
181   my $self = {};
182   bless ($self, $class);
183   if ( defined $self->table ) {
184     cluck "create constructor is deprecated, use new!";
185     $self->new(@_);
186   } else {
187     croak "FS::Record::create called (not from a subclass)!";
188   }
189 }
190
191 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
192
193 Searches the database for all records matching (at least) the key/value pairs
194 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
195 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
196 objects.
197
198 ###oops, argh, FS::Record::new only lets us create database fields.
199 #Normal behaviour if SELECT is not specified is `*', as in
200 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
201 #feature where you can specify SELECT - remember, the objects returned,
202 #although blessed into the appropriate `FS::TABLE' package, will only have the
203 #fields you specify.  This might have unwanted results if you then go calling
204 #regular FS::TABLE methods
205 #on it.
206
207 =cut
208
209 sub qsearch {
210   my($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
211   #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
212   #for jsearch
213   $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
214   $stable = $1;
215   $select ||= '*';
216   my $dbh = dbh;
217
218   my $table = $cache ? $cache->table : $stable;
219   my $dbdef_table = $dbdef->table($table)
220     or die "No schema for table $table found - ".
221            "do you need to create it or run dbdef-create?";
222   my $pkey = $dbdef_table->primary_key;
223
224   my @real_fields = grep exists($record->{$_}), real_fields($table);
225   my @virtual_fields;
226   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
227     @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
228   } else {
229     cluck "warning: FS::$table not loaded; virtual fields not searchable";
230     @virtual_fields = ();
231   }
232
233   my $statement = "SELECT $select FROM $stable";
234   $statement .= " $addl_from" if $addl_from;
235   if ( @real_fields or @virtual_fields ) {
236     $statement .= ' WHERE '. join(' AND ',
237       ( map {
238
239       my $op = '=';
240       my $column = $_;
241       if ( ref($record->{$_}) ) {
242         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
243         #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
244         if ( uc($op) eq 'ILIKE' ) {
245           $op = 'LIKE';
246           $record->{$_}{'value'} = lc($record->{$_}{'value'});
247           $column = "LOWER($_)";
248         }
249         $record->{$_} = $record->{$_}{'value'}
250       }
251
252       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
253         if ( $op eq '=' ) {
254           if ( driver_name eq 'Pg' ) {
255             my $type = $dbdef->table($table)->column($column)->type;
256             if ( $type =~ /(int|serial)/i ) {
257               qq-( $column IS NULL )-;
258             } else {
259               qq-( $column IS NULL OR $column = '' )-;
260             }
261           } else {
262             qq-( $column IS NULL OR $column = "" )-;
263           }
264         } elsif ( $op eq '!=' ) {
265           if ( driver_name eq 'Pg' ) {
266             my $type = $dbdef->table($table)->column($column)->type;
267             if ( $type =~ /(int|serial)/i ) {
268               qq-( $column IS NOT NULL )-;
269             } else {
270               qq-( $column IS NOT NULL AND $column != '' )-;
271             }
272           } else {
273             qq-( $column IS NOT NULL AND $column != "" )-;
274           }
275         } else {
276           if ( driver_name eq 'Pg' ) {
277             qq-( $column $op '' )-;
278           } else {
279             qq-( $column $op "" )-;
280           }
281         }
282       } else {
283         "$column $op ?";
284       }
285     } @real_fields ), 
286     ( map {
287       my $op = '=';
288       my $column = $_;
289       if ( ref($record->{$_}) ) {
290         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
291         if ( uc($op) eq 'ILIKE' ) {
292           $op = 'LIKE';
293           $record->{$_}{'value'} = lc($record->{$_}{'value'});
294           $column = "LOWER($_)";
295         }
296         $record->{$_} = $record->{$_}{'value'};
297       }
298
299       # ... EXISTS ( SELECT name, value FROM part_virtual_field
300       #              JOIN virtual_field
301       #              ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
302       #              WHERE recnum = svc_acct.svcnum
303       #              AND (name, value) = ('egad', 'brain') )
304
305       my $value = $record->{$_};
306
307       my $subq;
308
309       $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
310       "( SELECT part_virtual_field.name, virtual_field.value ".
311       "FROM part_virtual_field JOIN virtual_field ".
312       "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
313       "WHERE virtual_field.recnum = ${table}.${pkey} ".
314       "AND part_virtual_field.name = '${column}'".
315       ($value ? 
316         " AND virtual_field.value ${op} '${value}'"
317       : "") . ")";
318       $subq;
319
320     } @virtual_fields ) );
321
322   }
323
324   $statement .= " $extra_sql" if defined($extra_sql);
325
326   warn "[debug]$me $statement\n" if $DEBUG > 1;
327   my $sth = $dbh->prepare($statement)
328     or croak "$dbh->errstr doing $statement";
329
330   my $bind = 1;
331
332   foreach my $field (
333     grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
334   ) {
335     if ( $record->{$field} =~ /^\d+(\.\d+)?$/
336          && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
337     ) {
338       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
339     } else {
340       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
341     }
342   }
343
344 #  $sth->execute( map $record->{$_},
345 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
346 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
347
348   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
349
350   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
351     @virtual_fields = "FS::$table"->virtual_fields;
352   } else {
353     cluck "warning: FS::$table not loaded; virtual fields not returned either";
354     @virtual_fields = ();
355   }
356
357   my %result;
358   tie %result, "Tie::IxHash";
359   my @stuff = @{ $sth->fetchall_arrayref( {} ) };
360   if($pkey) {
361     %result = map { $_->{$pkey}, $_ } @stuff;
362   } else {
363     @result{@stuff} = @stuff;
364   }
365
366   $sth->finish;
367
368   if ( keys(%result) and @virtual_fields ) {
369     $statement =
370       "SELECT virtual_field.recnum, part_virtual_field.name, ".
371              "virtual_field.value ".
372       "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
373       "WHERE part_virtual_field.dbtable = '$table' AND ".
374       "virtual_field.recnum IN (".
375       join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
376       join(q!', '!, @virtual_fields) . "')";
377     warn "[debug]$me $statement\n" if $DEBUG > 1;
378     $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
379     $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
380
381     foreach (@{ $sth->fetchall_arrayref({}) }) {
382       my $recnum = $_->{recnum};
383       my $name = $_->{name};
384       my $value = $_->{value};
385       if (exists($result{$recnum})) {
386         $result{$recnum}->{$name} = $value;
387       }
388     }
389   }
390   my @return;
391   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
392     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
393       #derivied class didn't override new method, so this optimization is safe
394       if ( $cache ) {
395         @return = map {
396           new_or_cached( "FS::$table", { %{$_} }, $cache )
397         } values(%result);
398       } else {
399         @return = map {
400           new( "FS::$table", { %{$_} } )
401         } values(%result);
402       }
403     } else {
404       warn "untested code (class FS::$table uses custom new method)";
405       @return = map {
406         eval 'FS::'. $table. '->new( { %{$_} } )';
407       } values(%result);
408     }
409
410     # Check for encrypted fields and decrypt them.
411     if ($conf->exists('encryption') && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
412       foreach my $record (@return) {
413         foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
414           # Set it directly... This may cause a problem in the future...
415           $record->setfield($field, $record->decrypt($record->getfield($field)));
416         }
417       }
418     }
419   } else {
420     cluck "warning: FS::$table not loaded; returning FS::Record objects";
421     @return = map {
422       FS::Record->new( $table, { %{$_} } );
423     } values(%result);
424   }
425   return @return;
426 }
427
428 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
429
430 Experimental JOINed search method.  Using this method, you can execute a
431 single SELECT spanning multiple tables, and cache the results for subsequent
432 method calls.  Interface will almost definately change in an incompatible
433 fashion.
434
435 Arguments: 
436
437 =cut
438
439 sub jsearch {
440   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
441   my $cache = FS::SearchCache->new( $ptable, $pkey );
442   my %saw;
443   ( $cache,
444     grep { !$saw{$_->getfield($pkey)}++ }
445       qsearch($table, $record, $select, $extra_sql, $cache )
446   );
447 }
448
449 =item qsearchs TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
450
451 Same as qsearch, except that if more than one record matches, it B<carp>s but
452 returns the first.  If this happens, you either made a logic error in asking
453 for a single item, or your data is corrupted.
454
455 =cut
456
457 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
458   my $table = $_[0];
459   my(@result) = qsearch(@_);
460   cluck "warning: Multiple records in scalar search ($table)"
461     if scalar(@result) > 1;
462   #should warn more vehemently if the search was on a primary key?
463   scalar(@result) ? ($result[0]) : ();
464 }
465
466 =back
467
468 =head1 METHODS
469
470 =over 4
471
472 =item table
473
474 Returns the table name.
475
476 =cut
477
478 sub table {
479 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
480   my $self = shift;
481   $self -> {'Table'};
482 }
483
484 =item dbdef_table
485
486 Returns the DBIx::DBSchema::Table object for the table.
487
488 =cut
489
490 sub dbdef_table {
491   my($self)=@_;
492   my($table)=$self->table;
493   $dbdef->table($table);
494 }
495
496 =item get, getfield COLUMN
497
498 Returns the value of the column/field/key COLUMN.
499
500 =cut
501
502 sub get {
503   my($self,$field) = @_;
504   # to avoid "Use of unitialized value" errors
505   if ( defined ( $self->{Hash}->{$field} ) ) {
506     $self->{Hash}->{$field};
507   } else { 
508     '';
509   }
510 }
511 sub getfield {
512   my $self = shift;
513   $self->get(@_);
514 }
515
516 =item set, setfield COLUMN, VALUE
517
518 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
519
520 =cut
521
522 sub set { 
523   my($self,$field,$value) = @_;
524   $self->{'modified'} = 1;
525   $self->{'Hash'}->{$field} = $value;
526 }
527 sub setfield {
528   my $self = shift;
529   $self->set(@_);
530 }
531
532 =item AUTLOADED METHODS
533
534 $record->column is a synonym for $record->get('column');
535
536 $record->column('value') is a synonym for $record->set('column','value');
537
538 =cut
539
540 # readable/safe
541 sub AUTOLOAD {
542   my($self,$value)=@_;
543   my($field)=$AUTOLOAD;
544   $field =~ s/.*://;
545   if ( defined($value) ) {
546     confess "errant AUTOLOAD $field for $self (arg $value)"
547       unless ref($self) && $self->can('setfield');
548     $self->setfield($field,$value);
549   } else {
550     confess "errant AUTOLOAD $field for $self (no args)"
551       unless ref($self) && $self->can('getfield');
552     $self->getfield($field);
553   }    
554 }
555
556 # efficient
557 #sub AUTOLOAD {
558 #  my $field = $AUTOLOAD;
559 #  $field =~ s/.*://;
560 #  if ( defined($_[1]) ) {
561 #    $_[0]->setfield($field, $_[1]);
562 #  } else {
563 #    $_[0]->getfield($field);
564 #  }    
565 #}
566
567 =item hash
568
569 Returns a list of the column/value pairs, usually for assigning to a new hash.
570
571 To make a distinct duplicate of an FS::Record object, you can do:
572
573     $new = new FS::Record ( $old->table, { $old->hash } );
574
575 =cut
576
577 sub hash {
578   my($self) = @_;
579   confess $self. ' -> hash: Hash attribute is undefined'
580     unless defined($self->{'Hash'});
581   %{ $self->{'Hash'} }; 
582 }
583
584 =item hashref
585
586 Returns a reference to the column/value hash.  This may be deprecated in the
587 future; if there's a reason you can't just use the autoloaded or get/set
588 methods, speak up.
589
590 =cut
591
592 sub hashref {
593   my($self) = @_;
594   $self->{'Hash'};
595 }
596
597 =item modified
598
599 Returns true if any of this object's values have been modified with set (or via
600 an autoloaded method).  Doesn't yet recognize when you retreive a hashref and
601 modify that.
602
603 =cut
604
605 sub modified {
606   my $self = shift;
607   $self->{'modified'};
608 }
609
610 =item insert
611
612 Inserts this record to the database.  If there is an error, returns the error,
613 otherwise returns false.
614
615 =cut
616
617 sub insert {
618   my $self = shift;
619   my $saved = {};
620
621   my $error = $self->check;
622   return $error if $error;
623
624   #single-field unique keys are given a value if false
625   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
626   foreach ( $self->dbdef_table->unique->singles ) {
627     $self->unique($_) unless $self->getfield($_);
628   }
629
630   #and also the primary key, if the database isn't going to
631   my $primary_key = $self->dbdef_table->primary_key;
632   my $db_seq = 0;
633   if ( $primary_key ) {
634     my $col = $self->dbdef_table->column($primary_key);
635     
636     $db_seq =
637       uc($col->type) eq 'SERIAL'
638       || ( driver_name eq 'Pg'
639              && defined($col->default)
640              && $col->default =~ /^nextval\(/i
641          )
642       || ( driver_name eq 'mysql'
643              && defined($col->local)
644              && $col->local =~ /AUTO_INCREMENT/i
645          );
646     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
647   }
648
649   my $table = $self->table;
650
651   
652   # Encrypt before the database
653   if ($conf->exists('encryption') && defined(eval '@FS::'. $table . 'encrypted_fields')) {
654     foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
655       $self->{'saved'} = $self->getfield($field);
656       $self->setfield($field, $self->enrypt($self->getfield($field)));
657     }
658   }
659
660
661   #false laziness w/delete
662   my @real_fields =
663     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
664     real_fields($table)
665   ;
666   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
667   #eslaf
668
669   my $statement = "INSERT INTO $table ( ".
670       join( ', ', @real_fields ).
671     ") VALUES (".
672       join( ', ', @values ).
673     ")"
674   ;
675   warn "[debug]$me $statement\n" if $DEBUG > 1;
676   my $sth = dbh->prepare($statement) or return dbh->errstr;
677
678   local $SIG{HUP} = 'IGNORE';
679   local $SIG{INT} = 'IGNORE';
680   local $SIG{QUIT} = 'IGNORE'; 
681   local $SIG{TERM} = 'IGNORE';
682   local $SIG{TSTP} = 'IGNORE';
683   local $SIG{PIPE} = 'IGNORE';
684
685   $sth->execute or return $sth->errstr;
686
687   my $insertid = '';
688   if ( $db_seq ) { # get inserted id from the database, if applicable
689     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
690     if ( driver_name eq 'Pg' ) {
691
692       my $oid = $sth->{'pg_oid_status'};
693       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
694       my $i_sth = dbh->prepare($i_sql) or do {
695         dbh->rollback if $FS::UID::AutoCommit;
696         return dbh->errstr;
697       };
698       $i_sth->execute($oid) or do {
699         dbh->rollback if $FS::UID::AutoCommit;
700         return $i_sth->errstr;
701       };
702       $insertid = $i_sth->fetchrow_arrayref->[0];
703
704     } elsif ( driver_name eq 'mysql' ) {
705
706       $insertid = dbh->{'mysql_insertid'};
707       # work around mysql_insertid being null some of the time, ala RT :/
708       unless ( $insertid ) {
709         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
710              "using SELECT LAST_INSERT_ID();";
711         my $i_sql = "SELECT LAST_INSERT_ID()";
712         my $i_sth = dbh->prepare($i_sql) or do {
713           dbh->rollback if $FS::UID::AutoCommit;
714           return dbh->errstr;
715         };
716         $i_sth->execute or do {
717           dbh->rollback if $FS::UID::AutoCommit;
718           return $i_sth->errstr;
719         };
720         $insertid = $i_sth->fetchrow_arrayref->[0];
721       }
722
723     } else {
724       dbh->rollback if $FS::UID::AutoCommit;
725       return "don't know how to retreive inserted ids from ". driver_name. 
726              ", try using counterfiles (maybe run dbdef-create?)";
727     }
728     $self->setfield($primary_key, $insertid);
729   }
730
731   my @virtual_fields = 
732       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
733           $self->virtual_fields;
734   if (@virtual_fields) {
735     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
736
737     my $vfieldpart = $self->vfieldpart_hashref;
738
739     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
740                     "VALUES (?, ?, ?)";
741
742     my $v_sth = dbh->prepare($v_statement) or do {
743       dbh->rollback if $FS::UID::AutoCommit;
744       return dbh->errstr;
745     };
746
747     foreach (keys(%v_values)) {
748       $v_sth->execute($self->getfield($primary_key),
749                       $vfieldpart->{$_},
750                       $v_values{$_})
751       or do {
752         dbh->rollback if $FS::UID::AutoCommit;
753         return $v_sth->errstr;
754       };
755     }
756   }
757
758
759   my $h_sth;
760   if ( defined $dbdef->table('h_'. $table) ) {
761     my $h_statement = $self->_h_statement('insert');
762     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
763     $h_sth = dbh->prepare($h_statement) or do {
764       dbh->rollback if $FS::UID::AutoCommit;
765       return dbh->errstr;
766     };
767   } else {
768     $h_sth = '';
769   }
770   $h_sth->execute or return $h_sth->errstr if $h_sth;
771
772   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
773
774   # Now that it has been saved, reset the encrypted fields so that $new 
775   # can still be used.
776   foreach my $field (keys %{$saved}) {
777     $self->setfield($field, $saved->{$field});
778   }
779
780   '';
781 }
782
783 =item add
784
785 Depriciated (use insert instead).
786
787 =cut
788
789 sub add {
790   cluck "warning: FS::Record::add deprecated!";
791   insert @_; #call method in this scope
792 }
793
794 =item delete
795
796 Delete this record from the database.  If there is an error, returns the error,
797 otherwise returns false.
798
799 =cut
800
801 sub delete {
802   my $self = shift;
803
804   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
805     map {
806       $self->getfield($_) eq ''
807         #? "( $_ IS NULL OR $_ = \"\" )"
808         ? ( driver_name eq 'Pg'
809               ? "$_ IS NULL"
810               : "( $_ IS NULL OR $_ = \"\" )"
811           )
812         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
813     } ( $self->dbdef_table->primary_key )
814           ? ( $self->dbdef_table->primary_key)
815           : real_fields($self->table)
816   );
817   warn "[debug]$me $statement\n" if $DEBUG > 1;
818   my $sth = dbh->prepare($statement) or return dbh->errstr;
819
820   my $h_sth;
821   if ( defined $dbdef->table('h_'. $self->table) ) {
822     my $h_statement = $self->_h_statement('delete');
823     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
824     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
825   } else {
826     $h_sth = '';
827   }
828
829   my $primary_key = $self->dbdef_table->primary_key;
830   my $v_sth;
831   my @del_vfields;
832   my $vfp = $self->vfieldpart_hashref;
833   foreach($self->virtual_fields) {
834     next if $self->getfield($_) eq '';
835     unless(@del_vfields) {
836       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
837       $v_sth = dbh->prepare($st) or return dbh->errstr;
838     }
839     push @del_vfields, $_;
840   }
841
842   local $SIG{HUP} = 'IGNORE';
843   local $SIG{INT} = 'IGNORE';
844   local $SIG{QUIT} = 'IGNORE'; 
845   local $SIG{TERM} = 'IGNORE';
846   local $SIG{TSTP} = 'IGNORE';
847   local $SIG{PIPE} = 'IGNORE';
848
849   my $rc = $sth->execute or return $sth->errstr;
850   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
851   $h_sth->execute or return $h_sth->errstr if $h_sth;
852   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
853     or return $v_sth->errstr 
854         foreach (@del_vfields);
855   
856   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
857
858   #no need to needlessly destoy the data either (causes problems actually)
859   #undef $self; #no need to keep object!
860
861   '';
862 }
863
864 =item del
865
866 Depriciated (use delete instead).
867
868 =cut
869
870 sub del {
871   cluck "warning: FS::Record::del deprecated!";
872   &delete(@_); #call method in this scope
873 }
874
875 =item replace OLD_RECORD
876
877 Replace the OLD_RECORD with this one in the database.  If there is an error,
878 returns the error, otherwise returns false.
879
880 =cut
881
882 sub replace {
883   my $new = shift;
884   my $old = shift;  
885
886   my $saved = {};
887
888   if (!defined($old)) { 
889     warn "[debug]$me replace called with no arguments; autoloading old record\n"
890      if $DEBUG;
891     my $primary_key = $new->dbdef_table->primary_key;
892     if ( $primary_key ) {
893       $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
894         or croak "can't find ". $new->table. ".$primary_key ".
895                  $new->$primary_key();
896     } else {
897       croak $new->table. " has no primary key; pass old record as argument";
898     }
899   }
900
901   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
902
903   return "Records not in same table!" unless $new->table eq $old->table;
904
905   my $primary_key = $old->dbdef_table->primary_key;
906   return "Can't change $primary_key"
907     if $primary_key
908        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
909
910   my $error = $new->check;
911   return $error if $error;
912   
913   # Encrypt for replace
914   if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
915     foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
916       $saved->{$field} = $new->getfield($field);
917       $new->setfield($field, $new->encrypt($new->getfield($field)));
918     }
919   }
920
921   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
922   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
923                    ? ($_, $new->getfield($_)) : () } $old->fields;
924                    
925   unless ( keys(%diff) ) {
926     carp "[warning]$me $new -> replace $old: records identical";
927     return '';
928   }
929
930   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
931     map {
932       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
933     } real_fields($old->table)
934   ). ' WHERE '.
935     join(' AND ',
936       map {
937
938         if ( $old->getfield($_) eq '' ) {
939
940          #false laziness w/qsearch
941          if ( driver_name eq 'Pg' ) {
942             my $type = $old->dbdef_table->column($_)->type;
943             if ( $type =~ /(int|serial)/i ) {
944               qq-( $_ IS NULL )-;
945             } else {
946               qq-( $_ IS NULL OR $_ = '' )-;
947             }
948           } else {
949             qq-( $_ IS NULL OR $_ = "" )-;
950           }
951
952         } else {
953           "$_ = ". _quote($old->getfield($_),$old->table,$_);
954         }
955
956       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
957     )
958   ;
959   warn "[debug]$me $statement\n" if $DEBUG > 1;
960   my $sth = dbh->prepare($statement) or return dbh->errstr;
961
962   my $h_old_sth;
963   if ( defined $dbdef->table('h_'. $old->table) ) {
964     my $h_old_statement = $old->_h_statement('replace_old');
965     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
966     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
967   } else {
968     $h_old_sth = '';
969   }
970
971   my $h_new_sth;
972   if ( defined $dbdef->table('h_'. $new->table) ) {
973     my $h_new_statement = $new->_h_statement('replace_new');
974     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
975     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
976   } else {
977     $h_new_sth = '';
978   }
979
980   # For virtual fields we have three cases with different SQL 
981   # statements: add, replace, delete
982   my $v_add_sth;
983   my $v_rep_sth;
984   my $v_del_sth;
985   my (@add_vfields, @rep_vfields, @del_vfields);
986   my $vfp = $old->vfieldpart_hashref;
987   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
988     if($diff{$_} eq '') {
989       # Delete
990       unless(@del_vfields) {
991         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
992                  "AND vfieldpart = ?";
993         warn "[debug]$me $st\n" if $DEBUG > 2;
994         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
995       }
996       push @del_vfields, $_;
997     } elsif($old->getfield($_) eq '') {
998       # Add
999       unless(@add_vfields) {
1000         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1001                  "VALUES (?, ?, ?)";
1002         warn "[debug]$me $st\n" if $DEBUG > 2;
1003         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1004       }
1005       push @add_vfields, $_;
1006     } else {
1007       # Replace
1008       unless(@rep_vfields) {
1009         my $st = "UPDATE virtual_field SET value = ? ".
1010                  "WHERE recnum = ? AND vfieldpart = ?";
1011         warn "[debug]$me $st\n" if $DEBUG > 2;
1012         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1013       }
1014       push @rep_vfields, $_;
1015     }
1016   }
1017
1018   local $SIG{HUP} = 'IGNORE';
1019   local $SIG{INT} = 'IGNORE';
1020   local $SIG{QUIT} = 'IGNORE'; 
1021   local $SIG{TERM} = 'IGNORE';
1022   local $SIG{TSTP} = 'IGNORE';
1023   local $SIG{PIPE} = 'IGNORE';
1024
1025   my $rc = $sth->execute or return $sth->errstr;
1026   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1027   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1028   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1029
1030   $v_del_sth->execute($old->getfield($primary_key),
1031                       $vfp->{$_})
1032         or return $v_del_sth->errstr
1033       foreach(@del_vfields);
1034
1035   $v_add_sth->execute($new->getfield($_),
1036                       $old->getfield($primary_key),
1037                       $vfp->{$_})
1038         or return $v_add_sth->errstr
1039       foreach(@add_vfields);
1040
1041   $v_rep_sth->execute($new->getfield($_),
1042                       $old->getfield($primary_key),
1043                       $vfp->{$_})
1044         or return $v_rep_sth->errstr
1045       foreach(@rep_vfields);
1046
1047   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1048
1049   # Now that it has been saved, reset the encrypted fields so that $new 
1050   # can still be used.
1051   foreach my $field (keys %{$saved}) {
1052     $new->setfield($field, $saved->{$field});
1053   }
1054
1055   '';
1056
1057 }
1058
1059 =item rep
1060
1061 Depriciated (use replace instead).
1062
1063 =cut
1064
1065 sub rep {
1066   cluck "warning: FS::Record::rep deprecated!";
1067   replace @_; #call method in this scope
1068 }
1069
1070 =item check
1071
1072 Checks virtual fields (using check_blocks).  Subclasses should still provide 
1073 a check method to validate real fields, foreign keys, etc., and call this 
1074 method via $self->SUPER::check.
1075
1076 (FIXME: Should this method try to make sure that it I<is> being called from 
1077 a subclass's check method, to keep the current semantics as far as possible?)
1078
1079 =cut
1080
1081 sub check {
1082   #confess "FS::Record::check not implemented; supply one in subclass!";
1083   my $self = shift;
1084
1085   foreach my $field ($self->virtual_fields) {
1086     for ($self->getfield($field)) {
1087       # See notes on check_block in FS::part_virtual_field.
1088       eval $self->pvf($field)->check_block;
1089       if ( $@ ) {
1090         #this is bad, probably want to follow the stack backtrace up and see
1091         #wtf happened
1092         my $err = "Fatal error checking $field for $self";
1093         cluck "$err: $@";
1094         return "$err (see log for backtrace): $@";
1095
1096       }
1097       $self->setfield($field, $_);
1098     }
1099   }
1100   '';
1101 }
1102
1103 sub _h_statement {
1104   my( $self, $action, $time ) = @_;
1105
1106   $time ||= time;
1107
1108   my @fields =
1109     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1110     real_fields($self->table);
1111   ;
1112   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1113
1114   "INSERT INTO h_". $self->table. " ( ".
1115       join(', ', qw(history_date history_user history_action), @fields ).
1116     ") VALUES (".
1117       join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1118     ")"
1119   ;
1120 }
1121
1122 =item unique COLUMN
1123
1124 B<Warning>: External use is B<deprecated>.  
1125
1126 Replaces COLUMN in record with a unique number, using counters in the
1127 filesystem.  Used by the B<insert> method on single-field unique columns
1128 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1129 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1130
1131 Returns the new value.
1132
1133 =cut
1134
1135 sub unique {
1136   my($self,$field) = @_;
1137   my($table)=$self->table;
1138
1139   croak "Unique called on field $field, but it is ",
1140         $self->getfield($field),
1141         ", not null!"
1142     if $self->getfield($field);
1143
1144   #warn "table $table is tainted" if is_tainted($table);
1145   #warn "field $field is tainted" if is_tainted($field);
1146
1147   my($counter) = new File::CounterFile "$table.$field",0;
1148 # hack for web demo
1149 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1150 #  my($user)=$1;
1151 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1152 # endhack
1153
1154   my $index = $counter->inc;
1155   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1156
1157   $index =~ /^(\d*)$/;
1158   $index=$1;
1159
1160   $self->setfield($field,$index);
1161
1162 }
1163
1164 =item ut_float COLUMN
1165
1166 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1167 null.  If there is an error, returns the error, otherwise returns false.
1168
1169 =cut
1170
1171 sub ut_float {
1172   my($self,$field)=@_ ;
1173   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1174    $self->getfield($field) =~ /^(\d+)$/ ||
1175    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1176    $self->getfield($field) =~ /^(\d+e\d+)$/)
1177     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1178   $self->setfield($field,$1);
1179   '';
1180 }
1181
1182 =item ut_snumber COLUMN
1183
1184 Check/untaint signed numeric data (whole numbers).  May not be null.  If there
1185 is an error, returns the error, otherwise returns false.
1186
1187 =cut
1188
1189 sub ut_snumber {
1190   my($self, $field) = @_;
1191   $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1192     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1193   $self->setfield($field, "$1$2");
1194   '';
1195 }
1196
1197 =item ut_number COLUMN
1198
1199 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1200 is an error, returns the error, otherwise returns false.
1201
1202 =cut
1203
1204 sub ut_number {
1205   my($self,$field)=@_;
1206   $self->getfield($field) =~ /^(\d+)$/
1207     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1208   $self->setfield($field,$1);
1209   '';
1210 }
1211
1212 =item ut_numbern COLUMN
1213
1214 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1215 an error, returns the error, otherwise returns false.
1216
1217 =cut
1218
1219 sub ut_numbern {
1220   my($self,$field)=@_;
1221   $self->getfield($field) =~ /^(\d*)$/
1222     or return "Illegal (numeric) $field: ". $self->getfield($field);
1223   $self->setfield($field,$1);
1224   '';
1225 }
1226
1227 =item ut_money COLUMN
1228
1229 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1230 is an error, returns the error, otherwise returns false.
1231
1232 =cut
1233
1234 sub ut_money {
1235   my($self,$field)=@_;
1236   $self->setfield($field, 0) if $self->getfield($field) eq '';
1237   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1238     or return "Illegal (money) $field: ". $self->getfield($field);
1239   #$self->setfield($field, "$1$2$3" || 0);
1240   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1241   '';
1242 }
1243
1244 =item ut_text COLUMN
1245
1246 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1247 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1248 May not be null.  If there is an error, returns the error, otherwise returns
1249 false.
1250
1251 =cut
1252
1253 sub ut_text {
1254   my($self,$field)=@_;
1255   #warn "msgcat ". \&msgcat. "\n";
1256   #warn "notexist ". \&notexist. "\n";
1257   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1258   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1259     or return gettext('illegal_or_empty_text'). " $field: ".
1260                $self->getfield($field);
1261   $self->setfield($field,$1);
1262   '';
1263 }
1264
1265 =item ut_textn COLUMN
1266
1267 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1268 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1269 May be null.  If there is an error, returns the error, otherwise returns false.
1270
1271 =cut
1272
1273 sub ut_textn {
1274   my($self,$field)=@_;
1275   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1276     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1277   $self->setfield($field,$1);
1278   '';
1279 }
1280
1281 =item ut_alpha COLUMN
1282
1283 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1284 an error, returns the error, otherwise returns false.
1285
1286 =cut
1287
1288 sub ut_alpha {
1289   my($self,$field)=@_;
1290   $self->getfield($field) =~ /^(\w+)$/
1291     or return "Illegal or empty (alphanumeric) $field: ".
1292               $self->getfield($field);
1293   $self->setfield($field,$1);
1294   '';
1295 }
1296
1297 =item ut_alpha COLUMN
1298
1299 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1300 error, returns the error, otherwise returns false.
1301
1302 =cut
1303
1304 sub ut_alphan {
1305   my($self,$field)=@_;
1306   $self->getfield($field) =~ /^(\w*)$/ 
1307     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1308   $self->setfield($field,$1);
1309   '';
1310 }
1311
1312 =item ut_phonen COLUMN [ COUNTRY ]
1313
1314 Check/untaint phone numbers.  May be null.  If there is an error, returns
1315 the error, otherwise returns false.
1316
1317 Takes an optional two-letter ISO country code; without it or with unsupported
1318 countries, ut_phonen simply calls ut_alphan.
1319
1320 =cut
1321
1322 sub ut_phonen {
1323   my( $self, $field, $country ) = @_;
1324   return $self->ut_alphan($field) unless defined $country;
1325   my $phonen = $self->getfield($field);
1326   if ( $phonen eq '' ) {
1327     $self->setfield($field,'');
1328   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1329     $phonen =~ s/\D//g;
1330     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1331       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1332     $phonen = "$1-$2-$3";
1333     $phonen .= " x$4" if $4;
1334     $self->setfield($field,$phonen);
1335   } else {
1336     warn "warning: don't know how to check phone numbers for country $country";
1337     return $self->ut_textn($field);
1338   }
1339   '';
1340 }
1341
1342 =item ut_ip COLUMN
1343
1344 Check/untaint ip addresses.  IPv4 only for now.
1345
1346 =cut
1347
1348 sub ut_ip {
1349   my( $self, $field ) = @_;
1350   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1351     or return "Illegal (IP address) $field: ". $self->getfield($field);
1352   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1353   $self->setfield($field, "$1.$2.$3.$4");
1354   '';
1355 }
1356
1357 =item ut_ipn COLUMN
1358
1359 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1360
1361 =cut
1362
1363 sub ut_ipn {
1364   my( $self, $field ) = @_;
1365   if ( $self->getfield($field) =~ /^()$/ ) {
1366     $self->setfield($field,'');
1367     '';
1368   } else {
1369     $self->ut_ip($field);
1370   }
1371 }
1372
1373 =item ut_domain COLUMN
1374
1375 Check/untaint host and domain names.
1376
1377 =cut
1378
1379 sub ut_domain {
1380   my( $self, $field ) = @_;
1381   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1382   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1383     or return "Illegal (domain) $field: ". $self->getfield($field);
1384   $self->setfield($field,$1);
1385   '';
1386 }
1387
1388 =item ut_name COLUMN
1389
1390 Check/untaint proper names; allows alphanumerics, spaces and the following
1391 punctuation: , . - '
1392
1393 May not be null.
1394
1395 =cut
1396
1397 sub ut_name {
1398   my( $self, $field ) = @_;
1399   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1400     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1401   $self->setfield($field,$1);
1402   '';
1403 }
1404
1405 =item ut_zip COLUMN
1406
1407 Check/untaint zip codes.
1408
1409 =cut
1410
1411 sub ut_zip {
1412   my( $self, $field, $country ) = @_;
1413   if ( $country eq 'US' ) {
1414     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1415       or return gettext('illegal_zip'). " $field for country $country: ".
1416                 $self->getfield($field);
1417     $self->setfield($field,$1);
1418   } else {
1419     if ( $self->getfield($field) =~ /^\s*$/ ) {
1420       $self->setfield($field,'');
1421     } else {
1422       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1423         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1424       $self->setfield($field,$1);
1425     }
1426   }
1427   '';
1428 }
1429
1430 =item ut_country COLUMN
1431
1432 Check/untaint country codes.  Country names are changed to codes, if possible -
1433 see L<Locale::Country>.
1434
1435 =cut
1436
1437 sub ut_country {
1438   my( $self, $field ) = @_;
1439   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1440     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1441          && country2code($1) ) {
1442       $self->setfield($field,uc(country2code($1)));
1443     }
1444   }
1445   $self->getfield($field) =~ /^(\w\w)$/
1446     or return "Illegal (country) $field: ". $self->getfield($field);
1447   $self->setfield($field,uc($1));
1448   '';
1449 }
1450
1451 =item ut_anything COLUMN
1452
1453 Untaints arbitrary data.  Be careful.
1454
1455 =cut
1456
1457 sub ut_anything {
1458   my( $self, $field ) = @_;
1459   $self->getfield($field) =~ /^(.*)$/s
1460     or return "Illegal $field: ". $self->getfield($field);
1461   $self->setfield($field,$1);
1462   '';
1463 }
1464
1465 =item ut_enum COLUMN CHOICES_ARRAYREF
1466
1467 Check/untaint a column, supplying all possible choices, like the "enum" type.
1468
1469 =cut
1470
1471 sub ut_enum {
1472   my( $self, $field, $choices ) = @_;
1473   foreach my $choice ( @$choices ) {
1474     if ( $self->getfield($field) eq $choice ) {
1475       $self->setfield($choice);
1476       return '';
1477     }
1478   }
1479   return "Illegal (enum) field $field: ". $self->getfield($field);
1480 }
1481
1482 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1483
1484 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1485 on the column first.
1486
1487 =cut
1488
1489 sub ut_foreign_key {
1490   my( $self, $field, $table, $foreign ) = @_;
1491   qsearchs($table, { $foreign => $self->getfield($field) })
1492     or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1493               " in $table.$foreign";
1494   '';
1495 }
1496
1497 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1498
1499 Like ut_foreign_key, except the null value is also allowed.
1500
1501 =cut
1502
1503 sub ut_foreign_keyn {
1504   my( $self, $field, $table, $foreign ) = @_;
1505   $self->getfield($field)
1506     ? $self->ut_foreign_key($field, $table, $foreign)
1507     : '';
1508 }
1509
1510
1511 =item virtual_fields [ TABLE ]
1512
1513 Returns a list of virtual fields defined for the table.  This should not 
1514 be exported, and should only be called as an instance or class method.
1515
1516 =cut
1517
1518 sub virtual_fields {
1519   my $self = shift;
1520   my $table;
1521   $table = $self->table or confess "virtual_fields called on non-table";
1522
1523   confess "Unknown table $table" unless $dbdef->table($table);
1524
1525   return () unless $self->dbdef->table('part_virtual_field');
1526
1527   unless ( $virtual_fields_cache{$table} ) {
1528     my $query = 'SELECT name from part_virtual_field ' .
1529                 "WHERE dbtable = '$table'";
1530     my $dbh = dbh;
1531     my $result = $dbh->selectcol_arrayref($query);
1532     confess $dbh->errstr if $dbh->err;
1533     $virtual_fields_cache{$table} = $result;
1534   }
1535
1536   @{$virtual_fields_cache{$table}};
1537
1538 }
1539
1540
1541 =item fields [ TABLE ]
1542
1543 This is a wrapper for real_fields and virtual_fields.  Code that called
1544 fields before should probably continue to call fields.
1545
1546 =cut
1547
1548 sub fields {
1549   my $something = shift;
1550   my $table;
1551   if($something->isa('FS::Record')) {
1552     $table = $something->table;
1553   } else {
1554     $table = $something;
1555     $something = "FS::$table";
1556   }
1557   return (real_fields($table), $something->virtual_fields());
1558 }
1559
1560 =back
1561
1562 =item pvf FIELD_NAME
1563
1564 Returns the FS::part_virtual_field object corresponding to a field in the 
1565 record (specified by FIELD_NAME).
1566
1567 =cut
1568
1569 sub pvf {
1570   my ($self, $name) = (shift, shift);
1571
1572   if(grep /^$name$/, $self->virtual_fields) {
1573     return qsearchs('part_virtual_field', { dbtable => $self->table,
1574                                             name    => $name } );
1575   }
1576   ''
1577 }
1578
1579 =head1 SUBROUTINES
1580
1581 =over 4
1582
1583 =item real_fields [ TABLE ]
1584
1585 Returns a list of the real columns in the specified table.  Called only by 
1586 fields() and other subroutines elsewhere in FS::Record.
1587
1588 =cut
1589
1590 sub real_fields {
1591   my $table = shift;
1592
1593   my($table_obj) = $dbdef->table($table);
1594   confess "Unknown table $table" unless $table_obj;
1595   $table_obj->columns;
1596 }
1597
1598 =item reload_dbdef([FILENAME])
1599
1600 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1601 non-default filename.  This command is executed at startup unless
1602 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1603
1604 =cut
1605
1606 sub reload_dbdef {
1607   my $file = shift || $dbdef_file;
1608
1609   unless ( exists $dbdef_cache{$file} ) {
1610     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1611     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1612                             or die "can't load database schema from $file";
1613   } else {
1614     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1615   }
1616   $dbdef = $dbdef_cache{$file};
1617 }
1618
1619 =item dbdef
1620
1621 Returns the current database definition.  See L<DBIx::DBSchema>.
1622
1623 =cut
1624
1625 sub dbdef { $dbdef; }
1626
1627 =item _quote VALUE, TABLE, COLUMN
1628
1629 This is an internal function used to construct SQL statements.  It returns
1630 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1631 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1632
1633 =cut
1634
1635 sub _quote {
1636   my($value, $table, $column) = @_;
1637   my $column_obj = $dbdef->table($table)->column($column);
1638   my $column_type = $column_obj->type;
1639   my $nullable = $column_obj->null;
1640
1641   warn "  $table.$column: $value ($column_type".
1642        ( $nullable ? ' NULL' : ' NOT NULL' ).
1643        ")\n" if $DEBUG > 2;
1644
1645   if ( $value eq '' && $column_type =~ /^int/ ) {
1646     if ( $nullable ) {
1647       'NULL';
1648     } else {
1649       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1650             "using 0 instead";
1651       0;
1652     }
1653   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1654             ! $column_type =~ /(char|binary|text)$/i ) {
1655     $value;
1656   } else {
1657     dbh->quote($value);
1658   }
1659 }
1660
1661 =item vfieldpart_hashref TABLE
1662
1663 Returns a hashref of virtual field names and vfieldparts applicable to the given
1664 TABLE.
1665
1666 =cut
1667
1668 sub vfieldpart_hashref {
1669   my $self = shift;
1670   my $table = $self->table;
1671
1672   return {} unless $self->dbdef->table('part_virtual_field');
1673
1674   my $dbh = dbh;
1675   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1676                   "dbtable = '$table'";
1677   my $sth = $dbh->prepare($statement);
1678   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1679   return { map { $_->{name}, $_->{vfieldpart} } 
1680     @{$sth->fetchall_arrayref({})} };
1681
1682 }
1683
1684
1685 =item hfields TABLE
1686
1687 This is deprecated.  Don't use it.
1688
1689 It returns a hash-type list with the fields of this record's table set true.
1690
1691 =cut
1692
1693 sub hfields {
1694   carp "warning: hfields is deprecated";
1695   my($table)=@_;
1696   my(%hash);
1697   foreach (fields($table)) {
1698     $hash{$_}=1;
1699   }
1700   \%hash;
1701 }
1702
1703 sub _dump {
1704   my($self)=@_;
1705   join("\n", map {
1706     "$_: ". $self->getfield($_). "|"
1707   } (fields($self->table)) );
1708 }
1709
1710 sub encrypt {
1711   my ($self, $value) = @_;
1712   my $encrypted;
1713
1714   if ($conf->exists('encryption')) {
1715     if ($self->is_encrypted($value)) {
1716       # Return the original value if it isn't plaintext.
1717       $encrypted = $value;
1718     } else {
1719       $self->loadRSA;
1720       if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1721         # RSA doesn't like the empty string so let's pack it up
1722         # The database doesn't like the RSA data so uuencode it
1723         my $length = length($value)+1;
1724         $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1725       } else {
1726         die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1727       }
1728     }
1729   }
1730   return $encrypted;
1731 }
1732
1733 sub is_encrypted {
1734   my ($self, $value) = @_;
1735   # Possible Bug - Some work may be required here....
1736
1737   if (length($value) > 80) {
1738     return 1;
1739   } else {
1740     return 0;
1741   }
1742 }
1743
1744 sub decrypt {
1745   my ($self,$value) = @_;
1746   my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1747   if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1748     $self->loadRSA;
1749     if (ref($rsa_decrypt) =~ /::RSA/) {
1750       my $encrypted = unpack ("u*", $value);
1751       $decrypted =  unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1752     }
1753   }
1754   return $decrypted;
1755 }
1756
1757 sub loadRSA {
1758     my $self = shift;
1759     #Initialize the Module
1760     $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1761
1762     if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1763       $rsa_module = $conf->config('encryptionmodule');
1764     }
1765
1766     if (!$rsa_loaded) {
1767         eval ("require $rsa_module"); # No need to import the namespace
1768         $rsa_loaded++;
1769     }
1770     # Initialize Encryption
1771     if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1772       my $public_key = join("\n",$conf->config('encryptionpublickey'));
1773       $rsa_encrypt = $rsa_module->new_public_key($public_key);
1774     }
1775     
1776     # Intitalize Decryption
1777     if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1778       my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1779       $rsa_decrypt = $rsa_module->new_private_key($private_key);
1780     }
1781 }
1782
1783 sub DESTROY { return; }
1784
1785 #sub DESTROY {
1786 #  my $self = shift;
1787 #  #use Carp qw(cluck);
1788 #  #cluck "DESTROYING $self";
1789 #  warn "DESTROYING $self";
1790 #}
1791
1792 #sub is_tainted {
1793 #             return ! eval { join('',@_), kill 0; 1; };
1794 #         }
1795
1796 =back
1797
1798 =head1 BUGS
1799
1800 This module should probably be renamed, since much of the functionality is
1801 of general use.  It is not completely unlike Adapter::DBI (see below).
1802
1803 Exported qsearch and qsearchs should be deprecated in favor of method calls
1804 (against an FS::Record object like the old search and searchs that qsearch
1805 and qsearchs were on top of.)
1806
1807 The whole fields / hfields mess should be removed.
1808
1809 The various WHERE clauses should be subroutined.
1810
1811 table string should be deprecated in favor of DBIx::DBSchema::Table.
1812
1813 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1814 true maps to the database (and WHERE clauses) would also help.
1815
1816 The ut_ methods should ask the dbdef for a default length.
1817
1818 ut_sqltype (like ut_varchar) should all be defined
1819
1820 A fallback check method should be provided which uses the dbdef.
1821
1822 The ut_money method assumes money has two decimal digits.
1823
1824 The Pg money kludge in the new method only strips `$'.
1825
1826 The ut_phonen method only checks US-style phone numbers.
1827
1828 The _quote function should probably use ut_float instead of a regex.
1829
1830 All the subroutines probably should be methods, here or elsewhere.
1831
1832 Probably should borrow/use some dbdef methods where appropriate (like sub
1833 fields)
1834
1835 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1836 or allow it to be set.  Working around it is ugly any way around - DBI should
1837 be fixed.  (only affects RDBMS which return uppercase column names)
1838
1839 ut_zip should take an optional country like ut_phone.
1840
1841 =head1 SEE ALSO
1842
1843 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1844
1845 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1846
1847 http://poop.sf.net/
1848
1849 =cut
1850
1851 1;
1852