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