patch from rjbs to add by_key contructor to Record.pm
[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 by_key PRIMARY_KEY_VALUE
431
432 This is a class method that returns the record with the given primary key
433 value.  This method is only useful in FS::Record subclasses.  For example:
434
435   my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
436
437 is equivalent to:
438
439   my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
440
441 =cut
442
443 sub by_key {
444   my ($class, $pkey_value) = @_;
445
446   my $table = $class->table
447     or croak "No table for $class found";
448
449   my $dbdef_table = $dbdef->table($table)
450     or die "No schema for table $table found - ".
451            "do you need to create it or run dbdef-create?";
452   my $pkey = $dbdef_table->primary_key
453     or die "No primary key for table $table";
454
455   return qsearchs($table, { $pkey => $pkey_value });
456 }
457
458 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
459
460 Experimental JOINed search method.  Using this method, you can execute a
461 single SELECT spanning multiple tables, and cache the results for subsequent
462 method calls.  Interface will almost definately change in an incompatible
463 fashion.
464
465 Arguments: 
466
467 =cut
468
469 sub jsearch {
470   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
471   my $cache = FS::SearchCache->new( $ptable, $pkey );
472   my %saw;
473   ( $cache,
474     grep { !$saw{$_->getfield($pkey)}++ }
475       qsearch($table, $record, $select, $extra_sql, $cache )
476   );
477 }
478
479 =item qsearchs TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
480
481 Same as qsearch, except that if more than one record matches, it B<carp>s but
482 returns the first.  If this happens, you either made a logic error in asking
483 for a single item, or your data is corrupted.
484
485 =cut
486
487 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
488   my $table = $_[0];
489   my(@result) = qsearch(@_);
490   cluck "warning: Multiple records in scalar search ($table)"
491     if scalar(@result) > 1;
492   #should warn more vehemently if the search was on a primary key?
493   scalar(@result) ? ($result[0]) : ();
494 }
495
496 =back
497
498 =head1 METHODS
499
500 =over 4
501
502 =item table
503
504 Returns the table name.
505
506 =cut
507
508 sub table {
509 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
510   my $self = shift;
511   $self -> {'Table'};
512 }
513
514 =item dbdef_table
515
516 Returns the DBIx::DBSchema::Table object for the table.
517
518 =cut
519
520 sub dbdef_table {
521   my($self)=@_;
522   my($table)=$self->table;
523   $dbdef->table($table);
524 }
525
526 =item get, getfield COLUMN
527
528 Returns the value of the column/field/key COLUMN.
529
530 =cut
531
532 sub get {
533   my($self,$field) = @_;
534   # to avoid "Use of unitialized value" errors
535   if ( defined ( $self->{Hash}->{$field} ) ) {
536     $self->{Hash}->{$field};
537   } else { 
538     '';
539   }
540 }
541 sub getfield {
542   my $self = shift;
543   $self->get(@_);
544 }
545
546 =item set, setfield COLUMN, VALUE
547
548 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
549
550 =cut
551
552 sub set { 
553   my($self,$field,$value) = @_;
554   $self->{'modified'} = 1;
555   $self->{'Hash'}->{$field} = $value;
556 }
557 sub setfield {
558   my $self = shift;
559   $self->set(@_);
560 }
561
562 =item AUTLOADED METHODS
563
564 $record->column is a synonym for $record->get('column');
565
566 $record->column('value') is a synonym for $record->set('column','value');
567
568 =cut
569
570 # readable/safe
571 sub AUTOLOAD {
572   my($self,$value)=@_;
573   my($field)=$AUTOLOAD;
574   $field =~ s/.*://;
575   if ( defined($value) ) {
576     confess "errant AUTOLOAD $field for $self (arg $value)"
577       unless ref($self) && $self->can('setfield');
578     $self->setfield($field,$value);
579   } else {
580     confess "errant AUTOLOAD $field for $self (no args)"
581       unless ref($self) && $self->can('getfield');
582     $self->getfield($field);
583   }    
584 }
585
586 # efficient
587 #sub AUTOLOAD {
588 #  my $field = $AUTOLOAD;
589 #  $field =~ s/.*://;
590 #  if ( defined($_[1]) ) {
591 #    $_[0]->setfield($field, $_[1]);
592 #  } else {
593 #    $_[0]->getfield($field);
594 #  }    
595 #}
596
597 =item hash
598
599 Returns a list of the column/value pairs, usually for assigning to a new hash.
600
601 To make a distinct duplicate of an FS::Record object, you can do:
602
603     $new = new FS::Record ( $old->table, { $old->hash } );
604
605 =cut
606
607 sub hash {
608   my($self) = @_;
609   confess $self. ' -> hash: Hash attribute is undefined'
610     unless defined($self->{'Hash'});
611   %{ $self->{'Hash'} }; 
612 }
613
614 =item hashref
615
616 Returns a reference to the column/value hash.  This may be deprecated in the
617 future; if there's a reason you can't just use the autoloaded or get/set
618 methods, speak up.
619
620 =cut
621
622 sub hashref {
623   my($self) = @_;
624   $self->{'Hash'};
625 }
626
627 =item modified
628
629 Returns true if any of this object's values have been modified with set (or via
630 an autoloaded method).  Doesn't yet recognize when you retreive a hashref and
631 modify that.
632
633 =cut
634
635 sub modified {
636   my $self = shift;
637   $self->{'modified'};
638 }
639
640 =item insert
641
642 Inserts this record to the database.  If there is an error, returns the error,
643 otherwise returns false.
644
645 =cut
646
647 sub insert {
648   my $self = shift;
649   my $saved = {};
650
651   my $error = $self->check;
652   return $error if $error;
653
654   #single-field unique keys are given a value if false
655   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
656   foreach ( $self->dbdef_table->unique->singles ) {
657     $self->unique($_) unless $self->getfield($_);
658   }
659
660   #and also the primary key, if the database isn't going to
661   my $primary_key = $self->dbdef_table->primary_key;
662   my $db_seq = 0;
663   if ( $primary_key ) {
664     my $col = $self->dbdef_table->column($primary_key);
665     
666     $db_seq =
667       uc($col->type) eq 'SERIAL'
668       || ( driver_name eq 'Pg'
669              && defined($col->default)
670              && $col->default =~ /^nextval\(/i
671          )
672       || ( driver_name eq 'mysql'
673              && defined($col->local)
674              && $col->local =~ /AUTO_INCREMENT/i
675          );
676     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
677   }
678
679   my $table = $self->table;
680
681   
682   # Encrypt before the database
683   if ($conf->exists('encryption') && defined(eval '@FS::'. $table . 'encrypted_fields')) {
684     foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
685       $self->{'saved'} = $self->getfield($field);
686       $self->setfield($field, $self->enrypt($self->getfield($field)));
687     }
688   }
689
690
691   #false laziness w/delete
692   my @real_fields =
693     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
694     real_fields($table)
695   ;
696   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
697   #eslaf
698
699   my $statement = "INSERT INTO $table ( ".
700       join( ', ', @real_fields ).
701     ") VALUES (".
702       join( ', ', @values ).
703     ")"
704   ;
705   warn "[debug]$me $statement\n" if $DEBUG > 1;
706   my $sth = dbh->prepare($statement) or return dbh->errstr;
707
708   local $SIG{HUP} = 'IGNORE';
709   local $SIG{INT} = 'IGNORE';
710   local $SIG{QUIT} = 'IGNORE'; 
711   local $SIG{TERM} = 'IGNORE';
712   local $SIG{TSTP} = 'IGNORE';
713   local $SIG{PIPE} = 'IGNORE';
714
715   $sth->execute or return $sth->errstr;
716
717   my $insertid = '';
718   if ( $db_seq ) { # get inserted id from the database, if applicable
719     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
720     if ( driver_name eq 'Pg' ) {
721
722       my $oid = $sth->{'pg_oid_status'};
723       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
724       my $i_sth = dbh->prepare($i_sql) or do {
725         dbh->rollback if $FS::UID::AutoCommit;
726         return dbh->errstr;
727       };
728       $i_sth->execute($oid) or do {
729         dbh->rollback if $FS::UID::AutoCommit;
730         return $i_sth->errstr;
731       };
732       $insertid = $i_sth->fetchrow_arrayref->[0];
733
734     } elsif ( driver_name eq 'mysql' ) {
735
736       $insertid = dbh->{'mysql_insertid'};
737       # work around mysql_insertid being null some of the time, ala RT :/
738       unless ( $insertid ) {
739         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
740              "using SELECT LAST_INSERT_ID();";
741         my $i_sql = "SELECT LAST_INSERT_ID()";
742         my $i_sth = dbh->prepare($i_sql) or do {
743           dbh->rollback if $FS::UID::AutoCommit;
744           return dbh->errstr;
745         };
746         $i_sth->execute or do {
747           dbh->rollback if $FS::UID::AutoCommit;
748           return $i_sth->errstr;
749         };
750         $insertid = $i_sth->fetchrow_arrayref->[0];
751       }
752
753     } else {
754       dbh->rollback if $FS::UID::AutoCommit;
755       return "don't know how to retreive inserted ids from ". driver_name. 
756              ", try using counterfiles (maybe run dbdef-create?)";
757     }
758     $self->setfield($primary_key, $insertid);
759   }
760
761   my @virtual_fields = 
762       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
763           $self->virtual_fields;
764   if (@virtual_fields) {
765     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
766
767     my $vfieldpart = $self->vfieldpart_hashref;
768
769     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
770                     "VALUES (?, ?, ?)";
771
772     my $v_sth = dbh->prepare($v_statement) or do {
773       dbh->rollback if $FS::UID::AutoCommit;
774       return dbh->errstr;
775     };
776
777     foreach (keys(%v_values)) {
778       $v_sth->execute($self->getfield($primary_key),
779                       $vfieldpart->{$_},
780                       $v_values{$_})
781       or do {
782         dbh->rollback if $FS::UID::AutoCommit;
783         return $v_sth->errstr;
784       };
785     }
786   }
787
788
789   my $h_sth;
790   if ( defined $dbdef->table('h_'. $table) ) {
791     my $h_statement = $self->_h_statement('insert');
792     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
793     $h_sth = dbh->prepare($h_statement) or do {
794       dbh->rollback if $FS::UID::AutoCommit;
795       return dbh->errstr;
796     };
797   } else {
798     $h_sth = '';
799   }
800   $h_sth->execute or return $h_sth->errstr if $h_sth;
801
802   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
803
804   # Now that it has been saved, reset the encrypted fields so that $new 
805   # can still be used.
806   foreach my $field (keys %{$saved}) {
807     $self->setfield($field, $saved->{$field});
808   }
809
810   '';
811 }
812
813 =item add
814
815 Depriciated (use insert instead).
816
817 =cut
818
819 sub add {
820   cluck "warning: FS::Record::add deprecated!";
821   insert @_; #call method in this scope
822 }
823
824 =item delete
825
826 Delete this record from the database.  If there is an error, returns the error,
827 otherwise returns false.
828
829 =cut
830
831 sub delete {
832   my $self = shift;
833
834   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
835     map {
836       $self->getfield($_) eq ''
837         #? "( $_ IS NULL OR $_ = \"\" )"
838         ? ( driver_name eq 'Pg'
839               ? "$_ IS NULL"
840               : "( $_ IS NULL OR $_ = \"\" )"
841           )
842         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
843     } ( $self->dbdef_table->primary_key )
844           ? ( $self->dbdef_table->primary_key)
845           : real_fields($self->table)
846   );
847   warn "[debug]$me $statement\n" if $DEBUG > 1;
848   my $sth = dbh->prepare($statement) or return dbh->errstr;
849
850   my $h_sth;
851   if ( defined $dbdef->table('h_'. $self->table) ) {
852     my $h_statement = $self->_h_statement('delete');
853     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
854     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
855   } else {
856     $h_sth = '';
857   }
858
859   my $primary_key = $self->dbdef_table->primary_key;
860   my $v_sth;
861   my @del_vfields;
862   my $vfp = $self->vfieldpart_hashref;
863   foreach($self->virtual_fields) {
864     next if $self->getfield($_) eq '';
865     unless(@del_vfields) {
866       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
867       $v_sth = dbh->prepare($st) or return dbh->errstr;
868     }
869     push @del_vfields, $_;
870   }
871
872   local $SIG{HUP} = 'IGNORE';
873   local $SIG{INT} = 'IGNORE';
874   local $SIG{QUIT} = 'IGNORE'; 
875   local $SIG{TERM} = 'IGNORE';
876   local $SIG{TSTP} = 'IGNORE';
877   local $SIG{PIPE} = 'IGNORE';
878
879   my $rc = $sth->execute or return $sth->errstr;
880   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
881   $h_sth->execute or return $h_sth->errstr if $h_sth;
882   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
883     or return $v_sth->errstr 
884         foreach (@del_vfields);
885   
886   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
887
888   #no need to needlessly destoy the data either (causes problems actually)
889   #undef $self; #no need to keep object!
890
891   '';
892 }
893
894 =item del
895
896 Depriciated (use delete instead).
897
898 =cut
899
900 sub del {
901   cluck "warning: FS::Record::del deprecated!";
902   &delete(@_); #call method in this scope
903 }
904
905 =item replace OLD_RECORD
906
907 Replace the OLD_RECORD with this one in the database.  If there is an error,
908 returns the error, otherwise returns false.
909
910 =cut
911
912 sub replace {
913   my $new = shift;
914   my $old = shift;  
915
916   if (!defined($old)) { 
917     warn "[debug]$me replace called with no arguments; autoloading old record\n"
918      if $DEBUG;
919     my $primary_key = $new->dbdef_table->primary_key;
920     if ( $primary_key ) {
921       $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
922         or croak "can't find ". $new->table. ".$primary_key ".
923                  $new->$primary_key();
924     } else {
925       croak $new->table. " has no primary key; pass old record as argument";
926     }
927   }
928
929   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
930
931   return "Records not in same table!" unless $new->table eq $old->table;
932
933   my $primary_key = $old->dbdef_table->primary_key;
934   return "Can't change primary key $primary_key ".
935          'from '. $old->getfield($primary_key).
936          ' to ' . $new->getfield($primary_key)
937     if $primary_key
938        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
939
940   my $error = $new->check;
941   return $error if $error;
942   
943   # Encrypt for replace
944   my $saved = {};
945   if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
946     foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
947       $saved->{$field} = $new->getfield($field);
948       $new->setfield($field, $new->encrypt($new->getfield($field)));
949     }
950   }
951
952   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
953   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
954                    ? ($_, $new->getfield($_)) : () } $old->fields;
955                    
956   unless ( keys(%diff) ) {
957     carp "[warning]$me $new -> replace $old: records identical"
958       unless $nowarn_identical;
959     return '';
960   }
961
962   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
963     map {
964       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
965     } real_fields($old->table)
966   ). ' WHERE '.
967     join(' AND ',
968       map {
969
970         if ( $old->getfield($_) eq '' ) {
971
972          #false laziness w/qsearch
973          if ( driver_name eq 'Pg' ) {
974             my $type = $old->dbdef_table->column($_)->type;
975             if ( $type =~ /(int|serial)/i ) {
976               qq-( $_ IS NULL )-;
977             } else {
978               qq-( $_ IS NULL OR $_ = '' )-;
979             }
980           } else {
981             qq-( $_ IS NULL OR $_ = "" )-;
982           }
983
984         } else {
985           "$_ = ". _quote($old->getfield($_),$old->table,$_);
986         }
987
988       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
989     )
990   ;
991   warn "[debug]$me $statement\n" if $DEBUG > 1;
992   my $sth = dbh->prepare($statement) or return dbh->errstr;
993
994   my $h_old_sth;
995   if ( defined $dbdef->table('h_'. $old->table) ) {
996     my $h_old_statement = $old->_h_statement('replace_old');
997     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
998     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
999   } else {
1000     $h_old_sth = '';
1001   }
1002
1003   my $h_new_sth;
1004   if ( defined $dbdef->table('h_'. $new->table) ) {
1005     my $h_new_statement = $new->_h_statement('replace_new');
1006     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1007     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1008   } else {
1009     $h_new_sth = '';
1010   }
1011
1012   # For virtual fields we have three cases with different SQL 
1013   # statements: add, replace, delete
1014   my $v_add_sth;
1015   my $v_rep_sth;
1016   my $v_del_sth;
1017   my (@add_vfields, @rep_vfields, @del_vfields);
1018   my $vfp = $old->vfieldpart_hashref;
1019   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1020     if($diff{$_} eq '') {
1021       # Delete
1022       unless(@del_vfields) {
1023         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1024                  "AND vfieldpart = ?";
1025         warn "[debug]$me $st\n" if $DEBUG > 2;
1026         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1027       }
1028       push @del_vfields, $_;
1029     } elsif($old->getfield($_) eq '') {
1030       # Add
1031       unless(@add_vfields) {
1032         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1033                  "VALUES (?, ?, ?)";
1034         warn "[debug]$me $st\n" if $DEBUG > 2;
1035         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1036       }
1037       push @add_vfields, $_;
1038     } else {
1039       # Replace
1040       unless(@rep_vfields) {
1041         my $st = "UPDATE virtual_field SET value = ? ".
1042                  "WHERE recnum = ? AND vfieldpart = ?";
1043         warn "[debug]$me $st\n" if $DEBUG > 2;
1044         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1045       }
1046       push @rep_vfields, $_;
1047     }
1048   }
1049
1050   local $SIG{HUP} = 'IGNORE';
1051   local $SIG{INT} = 'IGNORE';
1052   local $SIG{QUIT} = 'IGNORE'; 
1053   local $SIG{TERM} = 'IGNORE';
1054   local $SIG{TSTP} = 'IGNORE';
1055   local $SIG{PIPE} = 'IGNORE';
1056
1057   my $rc = $sth->execute or return $sth->errstr;
1058   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1059   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1060   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1061
1062   $v_del_sth->execute($old->getfield($primary_key),
1063                       $vfp->{$_})
1064         or return $v_del_sth->errstr
1065       foreach(@del_vfields);
1066
1067   $v_add_sth->execute($new->getfield($_),
1068                       $old->getfield($primary_key),
1069                       $vfp->{$_})
1070         or return $v_add_sth->errstr
1071       foreach(@add_vfields);
1072
1073   $v_rep_sth->execute($new->getfield($_),
1074                       $old->getfield($primary_key),
1075                       $vfp->{$_})
1076         or return $v_rep_sth->errstr
1077       foreach(@rep_vfields);
1078
1079   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1080
1081   # Now that it has been saved, reset the encrypted fields so that $new 
1082   # can still be used.
1083   foreach my $field (keys %{$saved}) {
1084     $new->setfield($field, $saved->{$field});
1085   }
1086
1087   '';
1088
1089 }
1090
1091 =item rep
1092
1093 Depriciated (use replace instead).
1094
1095 =cut
1096
1097 sub rep {
1098   cluck "warning: FS::Record::rep deprecated!";
1099   replace @_; #call method in this scope
1100 }
1101
1102 =item check
1103
1104 Checks virtual fields (using check_blocks).  Subclasses should still provide 
1105 a check method to validate real fields, foreign keys, etc., and call this 
1106 method via $self->SUPER::check.
1107
1108 (FIXME: Should this method try to make sure that it I<is> being called from 
1109 a subclass's check method, to keep the current semantics as far as possible?)
1110
1111 =cut
1112
1113 sub check {
1114   #confess "FS::Record::check not implemented; supply one in subclass!";
1115   my $self = shift;
1116
1117   foreach my $field ($self->virtual_fields) {
1118     for ($self->getfield($field)) {
1119       # See notes on check_block in FS::part_virtual_field.
1120       eval $self->pvf($field)->check_block;
1121       if ( $@ ) {
1122         #this is bad, probably want to follow the stack backtrace up and see
1123         #wtf happened
1124         my $err = "Fatal error checking $field for $self";
1125         cluck "$err: $@";
1126         return "$err (see log for backtrace): $@";
1127
1128       }
1129       $self->setfield($field, $_);
1130     }
1131   }
1132   '';
1133 }
1134
1135 sub _h_statement {
1136   my( $self, $action, $time ) = @_;
1137
1138   $time ||= time;
1139
1140   my @fields =
1141     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1142     real_fields($self->table);
1143   ;
1144   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1145
1146   "INSERT INTO h_". $self->table. " ( ".
1147       join(', ', qw(history_date history_user history_action), @fields ).
1148     ") VALUES (".
1149       join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1150     ")"
1151   ;
1152 }
1153
1154 =item unique COLUMN
1155
1156 B<Warning>: External use is B<deprecated>.  
1157
1158 Replaces COLUMN in record with a unique number, using counters in the
1159 filesystem.  Used by the B<insert> method on single-field unique columns
1160 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1161 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1162
1163 Returns the new value.
1164
1165 =cut
1166
1167 sub unique {
1168   my($self,$field) = @_;
1169   my($table)=$self->table;
1170
1171   croak "Unique called on field $field, but it is ",
1172         $self->getfield($field),
1173         ", not null!"
1174     if $self->getfield($field);
1175
1176   #warn "table $table is tainted" if is_tainted($table);
1177   #warn "field $field is tainted" if is_tainted($field);
1178
1179   my($counter) = new File::CounterFile "$table.$field",0;
1180 # hack for web demo
1181 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1182 #  my($user)=$1;
1183 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1184 # endhack
1185
1186   my $index = $counter->inc;
1187   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1188
1189   $index =~ /^(\d*)$/;
1190   $index=$1;
1191
1192   $self->setfield($field,$index);
1193
1194 }
1195
1196 =item ut_float COLUMN
1197
1198 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1199 null.  If there is an error, returns the error, otherwise returns false.
1200
1201 =cut
1202
1203 sub ut_float {
1204   my($self,$field)=@_ ;
1205   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1206    $self->getfield($field) =~ /^(\d+)$/ ||
1207    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1208    $self->getfield($field) =~ /^(\d+e\d+)$/)
1209     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1210   $self->setfield($field,$1);
1211   '';
1212 }
1213
1214 =item ut_snumber COLUMN
1215
1216 Check/untaint signed numeric data (whole numbers).  May not be null.  If there
1217 is an error, returns the error, otherwise returns false.
1218
1219 =cut
1220
1221 sub ut_snumber {
1222   my($self, $field) = @_;
1223   $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1224     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1225   $self->setfield($field, "$1$2");
1226   '';
1227 }
1228
1229 =item ut_number COLUMN
1230
1231 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1232 is an error, returns the error, otherwise returns false.
1233
1234 =cut
1235
1236 sub ut_number {
1237   my($self,$field)=@_;
1238   $self->getfield($field) =~ /^(\d+)$/
1239     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1240   $self->setfield($field,$1);
1241   '';
1242 }
1243
1244 =item ut_numbern COLUMN
1245
1246 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1247 an error, returns the error, otherwise returns false.
1248
1249 =cut
1250
1251 sub ut_numbern {
1252   my($self,$field)=@_;
1253   $self->getfield($field) =~ /^(\d*)$/
1254     or return "Illegal (numeric) $field: ". $self->getfield($field);
1255   $self->setfield($field,$1);
1256   '';
1257 }
1258
1259 =item ut_money COLUMN
1260
1261 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1262 is an error, returns the error, otherwise returns false.
1263
1264 =cut
1265
1266 sub ut_money {
1267   my($self,$field)=@_;
1268   $self->setfield($field, 0) if $self->getfield($field) eq '';
1269   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1270     or return "Illegal (money) $field: ". $self->getfield($field);
1271   #$self->setfield($field, "$1$2$3" || 0);
1272   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1273   '';
1274 }
1275
1276 =item ut_text COLUMN
1277
1278 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1279 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1280 May not be null.  If there is an error, returns the error, otherwise returns
1281 false.
1282
1283 =cut
1284
1285 sub ut_text {
1286   my($self,$field)=@_;
1287   #warn "msgcat ". \&msgcat. "\n";
1288   #warn "notexist ". \&notexist. "\n";
1289   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1290   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1291     or return gettext('illegal_or_empty_text'). " $field: ".
1292                $self->getfield($field);
1293   $self->setfield($field,$1);
1294   '';
1295 }
1296
1297 =item ut_textn COLUMN
1298
1299 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1300 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1301 May be null.  If there is an error, returns the error, otherwise returns false.
1302
1303 =cut
1304
1305 sub ut_textn {
1306   my($self,$field)=@_;
1307   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1308     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1309   $self->setfield($field,$1);
1310   '';
1311 }
1312
1313 =item ut_alpha COLUMN
1314
1315 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1316 an error, returns the error, otherwise returns false.
1317
1318 =cut
1319
1320 sub ut_alpha {
1321   my($self,$field)=@_;
1322   $self->getfield($field) =~ /^(\w+)$/
1323     or return "Illegal or empty (alphanumeric) $field: ".
1324               $self->getfield($field);
1325   $self->setfield($field,$1);
1326   '';
1327 }
1328
1329 =item ut_alpha COLUMN
1330
1331 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1332 error, returns the error, otherwise returns false.
1333
1334 =cut
1335
1336 sub ut_alphan {
1337   my($self,$field)=@_;
1338   $self->getfield($field) =~ /^(\w*)$/ 
1339     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1340   $self->setfield($field,$1);
1341   '';
1342 }
1343
1344 =item ut_phonen COLUMN [ COUNTRY ]
1345
1346 Check/untaint phone numbers.  May be null.  If there is an error, returns
1347 the error, otherwise returns false.
1348
1349 Takes an optional two-letter ISO country code; without it or with unsupported
1350 countries, ut_phonen simply calls ut_alphan.
1351
1352 =cut
1353
1354 sub ut_phonen {
1355   my( $self, $field, $country ) = @_;
1356   return $self->ut_alphan($field) unless defined $country;
1357   my $phonen = $self->getfield($field);
1358   if ( $phonen eq '' ) {
1359     $self->setfield($field,'');
1360   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1361     $phonen =~ s/\D//g;
1362     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1363       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1364     $phonen = "$1-$2-$3";
1365     $phonen .= " x$4" if $4;
1366     $self->setfield($field,$phonen);
1367   } else {
1368     warn "warning: don't know how to check phone numbers for country $country";
1369     return $self->ut_textn($field);
1370   }
1371   '';
1372 }
1373
1374 =item ut_ip COLUMN
1375
1376 Check/untaint ip addresses.  IPv4 only for now.
1377
1378 =cut
1379
1380 sub ut_ip {
1381   my( $self, $field ) = @_;
1382   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1383     or return "Illegal (IP address) $field: ". $self->getfield($field);
1384   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1385   $self->setfield($field, "$1.$2.$3.$4");
1386   '';
1387 }
1388
1389 =item ut_ipn COLUMN
1390
1391 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1392
1393 =cut
1394
1395 sub ut_ipn {
1396   my( $self, $field ) = @_;
1397   if ( $self->getfield($field) =~ /^()$/ ) {
1398     $self->setfield($field,'');
1399     '';
1400   } else {
1401     $self->ut_ip($field);
1402   }
1403 }
1404
1405 =item ut_domain COLUMN
1406
1407 Check/untaint host and domain names.
1408
1409 =cut
1410
1411 sub ut_domain {
1412   my( $self, $field ) = @_;
1413   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1414   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1415     or return "Illegal (domain) $field: ". $self->getfield($field);
1416   $self->setfield($field,$1);
1417   '';
1418 }
1419
1420 =item ut_name COLUMN
1421
1422 Check/untaint proper names; allows alphanumerics, spaces and the following
1423 punctuation: , . - '
1424
1425 May not be null.
1426
1427 =cut
1428
1429 sub ut_name {
1430   my( $self, $field ) = @_;
1431   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1432     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1433   $self->setfield($field,$1);
1434   '';
1435 }
1436
1437 =item ut_zip COLUMN
1438
1439 Check/untaint zip codes.
1440
1441 =cut
1442
1443 sub ut_zip {
1444   my( $self, $field, $country ) = @_;
1445   if ( $country eq 'US' ) {
1446     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1447       or return gettext('illegal_zip'). " $field for country $country: ".
1448                 $self->getfield($field);
1449     $self->setfield($field,$1);
1450   } else {
1451     if ( $self->getfield($field) =~ /^\s*$/ ) {
1452       $self->setfield($field,'');
1453     } else {
1454       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1455         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1456       $self->setfield($field,$1);
1457     }
1458   }
1459   '';
1460 }
1461
1462 =item ut_country COLUMN
1463
1464 Check/untaint country codes.  Country names are changed to codes, if possible -
1465 see L<Locale::Country>.
1466
1467 =cut
1468
1469 sub ut_country {
1470   my( $self, $field ) = @_;
1471   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1472     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1473          && country2code($1) ) {
1474       $self->setfield($field,uc(country2code($1)));
1475     }
1476   }
1477   $self->getfield($field) =~ /^(\w\w)$/
1478     or return "Illegal (country) $field: ". $self->getfield($field);
1479   $self->setfield($field,uc($1));
1480   '';
1481 }
1482
1483 =item ut_anything COLUMN
1484
1485 Untaints arbitrary data.  Be careful.
1486
1487 =cut
1488
1489 sub ut_anything {
1490   my( $self, $field ) = @_;
1491   $self->getfield($field) =~ /^(.*)$/s
1492     or return "Illegal $field: ". $self->getfield($field);
1493   $self->setfield($field,$1);
1494   '';
1495 }
1496
1497 =item ut_enum COLUMN CHOICES_ARRAYREF
1498
1499 Check/untaint a column, supplying all possible choices, like the "enum" type.
1500
1501 =cut
1502
1503 sub ut_enum {
1504   my( $self, $field, $choices ) = @_;
1505   foreach my $choice ( @$choices ) {
1506     if ( $self->getfield($field) eq $choice ) {
1507       $self->setfield($choice);
1508       return '';
1509     }
1510   }
1511   return "Illegal (enum) field $field: ". $self->getfield($field);
1512 }
1513
1514 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1515
1516 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1517 on the column first.
1518
1519 =cut
1520
1521 sub ut_foreign_key {
1522   my( $self, $field, $table, $foreign ) = @_;
1523   qsearchs($table, { $foreign => $self->getfield($field) })
1524     or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1525               " in $table.$foreign";
1526   '';
1527 }
1528
1529 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1530
1531 Like ut_foreign_key, except the null value is also allowed.
1532
1533 =cut
1534
1535 sub ut_foreign_keyn {
1536   my( $self, $field, $table, $foreign ) = @_;
1537   $self->getfield($field)
1538     ? $self->ut_foreign_key($field, $table, $foreign)
1539     : '';
1540 }
1541
1542
1543 =item virtual_fields [ TABLE ]
1544
1545 Returns a list of virtual fields defined for the table.  This should not 
1546 be exported, and should only be called as an instance or class method.
1547
1548 =cut
1549
1550 sub virtual_fields {
1551   my $self = shift;
1552   my $table;
1553   $table = $self->table or confess "virtual_fields called on non-table";
1554
1555   confess "Unknown table $table" unless $dbdef->table($table);
1556
1557   return () unless $self->dbdef->table('part_virtual_field');
1558
1559   unless ( $virtual_fields_cache{$table} ) {
1560     my $query = 'SELECT name from part_virtual_field ' .
1561                 "WHERE dbtable = '$table'";
1562     my $dbh = dbh;
1563     my $result = $dbh->selectcol_arrayref($query);
1564     confess $dbh->errstr if $dbh->err;
1565     $virtual_fields_cache{$table} = $result;
1566   }
1567
1568   @{$virtual_fields_cache{$table}};
1569
1570 }
1571
1572
1573 =item fields [ TABLE ]
1574
1575 This is a wrapper for real_fields and virtual_fields.  Code that called
1576 fields before should probably continue to call fields.
1577
1578 =cut
1579
1580 sub fields {
1581   my $something = shift;
1582   my $table;
1583   if($something->isa('FS::Record')) {
1584     $table = $something->table;
1585   } else {
1586     $table = $something;
1587     $something = "FS::$table";
1588   }
1589   return (real_fields($table), $something->virtual_fields());
1590 }
1591
1592 =back
1593
1594 =item pvf FIELD_NAME
1595
1596 Returns the FS::part_virtual_field object corresponding to a field in the 
1597 record (specified by FIELD_NAME).
1598
1599 =cut
1600
1601 sub pvf {
1602   my ($self, $name) = (shift, shift);
1603
1604   if(grep /^$name$/, $self->virtual_fields) {
1605     return qsearchs('part_virtual_field', { dbtable => $self->table,
1606                                             name    => $name } );
1607   }
1608   ''
1609 }
1610
1611 =head1 SUBROUTINES
1612
1613 =over 4
1614
1615 =item real_fields [ TABLE ]
1616
1617 Returns a list of the real columns in the specified table.  Called only by 
1618 fields() and other subroutines elsewhere in FS::Record.
1619
1620 =cut
1621
1622 sub real_fields {
1623   my $table = shift;
1624
1625   my($table_obj) = $dbdef->table($table);
1626   confess "Unknown table $table" unless $table_obj;
1627   $table_obj->columns;
1628 }
1629
1630 =item reload_dbdef([FILENAME])
1631
1632 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1633 non-default filename.  This command is executed at startup unless
1634 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1635
1636 =cut
1637
1638 sub reload_dbdef {
1639   my $file = shift || $dbdef_file;
1640
1641   unless ( exists $dbdef_cache{$file} ) {
1642     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1643     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1644                             or die "can't load database schema from $file";
1645   } else {
1646     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1647   }
1648   $dbdef = $dbdef_cache{$file};
1649 }
1650
1651 =item dbdef
1652
1653 Returns the current database definition.  See L<DBIx::DBSchema>.
1654
1655 =cut
1656
1657 sub dbdef { $dbdef; }
1658
1659 =item _quote VALUE, TABLE, COLUMN
1660
1661 This is an internal function used to construct SQL statements.  It returns
1662 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1663 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1664
1665 =cut
1666
1667 sub _quote {
1668   my($value, $table, $column) = @_;
1669   my $column_obj = $dbdef->table($table)->column($column);
1670   my $column_type = $column_obj->type;
1671   my $nullable = $column_obj->null;
1672
1673   warn "  $table.$column: $value ($column_type".
1674        ( $nullable ? ' NULL' : ' NOT NULL' ).
1675        ")\n" if $DEBUG > 2;
1676
1677   if ( $value eq '' && $column_type =~ /^int/ ) {
1678     if ( $nullable ) {
1679       'NULL';
1680     } else {
1681       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1682             "using 0 instead";
1683       0;
1684     }
1685   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1686             ! $column_type =~ /(char|binary|text)$/i ) {
1687     $value;
1688   } else {
1689     dbh->quote($value);
1690   }
1691 }
1692
1693 =item vfieldpart_hashref TABLE
1694
1695 Returns a hashref of virtual field names and vfieldparts applicable to the given
1696 TABLE.
1697
1698 =cut
1699
1700 sub vfieldpart_hashref {
1701   my $self = shift;
1702   my $table = $self->table;
1703
1704   return {} unless $self->dbdef->table('part_virtual_field');
1705
1706   my $dbh = dbh;
1707   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1708                   "dbtable = '$table'";
1709   my $sth = $dbh->prepare($statement);
1710   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1711   return { map { $_->{name}, $_->{vfieldpart} } 
1712     @{$sth->fetchall_arrayref({})} };
1713
1714 }
1715
1716
1717 =item hfields TABLE
1718
1719 This is deprecated.  Don't use it.
1720
1721 It returns a hash-type list with the fields of this record's table set true.
1722
1723 =cut
1724
1725 sub hfields {
1726   carp "warning: hfields is deprecated";
1727   my($table)=@_;
1728   my(%hash);
1729   foreach (fields($table)) {
1730     $hash{$_}=1;
1731   }
1732   \%hash;
1733 }
1734
1735 sub _dump {
1736   my($self)=@_;
1737   join("\n", map {
1738     "$_: ". $self->getfield($_). "|"
1739   } (fields($self->table)) );
1740 }
1741
1742 sub encrypt {
1743   my ($self, $value) = @_;
1744   my $encrypted;
1745
1746   if ($conf->exists('encryption')) {
1747     if ($self->is_encrypted($value)) {
1748       # Return the original value if it isn't plaintext.
1749       $encrypted = $value;
1750     } else {
1751       $self->loadRSA;
1752       if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1753         # RSA doesn't like the empty string so let's pack it up
1754         # The database doesn't like the RSA data so uuencode it
1755         my $length = length($value)+1;
1756         $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1757       } else {
1758         die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1759       }
1760     }
1761   }
1762   return $encrypted;
1763 }
1764
1765 sub is_encrypted {
1766   my ($self, $value) = @_;
1767   # Possible Bug - Some work may be required here....
1768
1769   if (length($value) > 80) {
1770     return 1;
1771   } else {
1772     return 0;
1773   }
1774 }
1775
1776 sub decrypt {
1777   my ($self,$value) = @_;
1778   my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1779   if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1780     $self->loadRSA;
1781     if (ref($rsa_decrypt) =~ /::RSA/) {
1782       my $encrypted = unpack ("u*", $value);
1783       $decrypted =  unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1784     }
1785   }
1786   return $decrypted;
1787 }
1788
1789 sub loadRSA {
1790     my $self = shift;
1791     #Initialize the Module
1792     $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1793
1794     if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1795       $rsa_module = $conf->config('encryptionmodule');
1796     }
1797
1798     if (!$rsa_loaded) {
1799         eval ("require $rsa_module"); # No need to import the namespace
1800         $rsa_loaded++;
1801     }
1802     # Initialize Encryption
1803     if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1804       my $public_key = join("\n",$conf->config('encryptionpublickey'));
1805       $rsa_encrypt = $rsa_module->new_public_key($public_key);
1806     }
1807     
1808     # Intitalize Decryption
1809     if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1810       my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1811       $rsa_decrypt = $rsa_module->new_private_key($private_key);
1812     }
1813 }
1814
1815 sub DESTROY { return; }
1816
1817 #sub DESTROY {
1818 #  my $self = shift;
1819 #  #use Carp qw(cluck);
1820 #  #cluck "DESTROYING $self";
1821 #  warn "DESTROYING $self";
1822 #}
1823
1824 #sub is_tainted {
1825 #             return ! eval { join('',@_), kill 0; 1; };
1826 #         }
1827
1828 =back
1829
1830 =head1 BUGS
1831
1832 This module should probably be renamed, since much of the functionality is
1833 of general use.  It is not completely unlike Adapter::DBI (see below).
1834
1835 Exported qsearch and qsearchs should be deprecated in favor of method calls
1836 (against an FS::Record object like the old search and searchs that qsearch
1837 and qsearchs were on top of.)
1838
1839 The whole fields / hfields mess should be removed.
1840
1841 The various WHERE clauses should be subroutined.
1842
1843 table string should be deprecated in favor of DBIx::DBSchema::Table.
1844
1845 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1846 true maps to the database (and WHERE clauses) would also help.
1847
1848 The ut_ methods should ask the dbdef for a default length.
1849
1850 ut_sqltype (like ut_varchar) should all be defined
1851
1852 A fallback check method should be provided which uses the dbdef.
1853
1854 The ut_money method assumes money has two decimal digits.
1855
1856 The Pg money kludge in the new method only strips `$'.
1857
1858 The ut_phonen method only checks US-style phone numbers.
1859
1860 The _quote function should probably use ut_float instead of a regex.
1861
1862 All the subroutines probably should be methods, here or elsewhere.
1863
1864 Probably should borrow/use some dbdef methods where appropriate (like sub
1865 fields)
1866
1867 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1868 or allow it to be set.  Working around it is ugly any way around - DBI should
1869 be fixed.  (only affects RDBMS which return uppercase column names)
1870
1871 ut_zip should take an optional country like ut_phone.
1872
1873 =head1 SEE ALSO
1874
1875 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1876
1877 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1878
1879 http://poop.sf.net/
1880
1881 =cut
1882
1883 1;
1884