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