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