depend on DBIx::DBSchema 0.26 for dbdef-create (for Pg 'public' schema fix) and 0...
[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.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 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   if (!defined($old)) { 
887     warn "[debug]$me replace called with no arguments; autoloading old record\n"
888      if $DEBUG;
889     my $primary_key = $new->dbdef_table->primary_key;
890     if ( $primary_key ) {
891       $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
892         or croak "can't find ". $new->table. ".$primary_key ".
893                  $new->$primary_key();
894     } else {
895       croak $new->table. " has no primary key; pass old record as argument";
896     }
897   }
898
899   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
900
901   return "Records not in same table!" unless $new->table eq $old->table;
902
903   my $primary_key = $old->dbdef_table->primary_key;
904   return "Can't change $primary_key"
905     if $primary_key
906        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
907
908   my $error = $new->check;
909   return $error if $error;
910   
911   # Encrypt for replace
912   my $saved = {};
913   if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
914     foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
915       $saved->{$field} = $new->getfield($field);
916       $new->setfield($field, $new->encrypt($new->getfield($field)));
917     }
918   }
919
920   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
921   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
922                    ? ($_, $new->getfield($_)) : () } $old->fields;
923                    
924   unless ( keys(%diff) ) {
925     carp "[warning]$me $new -> replace $old: records identical";
926     return '';
927   }
928
929   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
930     map {
931       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
932     } real_fields($old->table)
933   ). ' WHERE '.
934     join(' AND ',
935       map {
936
937         if ( $old->getfield($_) eq '' ) {
938
939          #false laziness w/qsearch
940          if ( driver_name eq 'Pg' ) {
941             my $type = $old->dbdef_table->column($_)->type;
942             if ( $type =~ /(int|serial)/i ) {
943               qq-( $_ IS NULL )-;
944             } else {
945               qq-( $_ IS NULL OR $_ = '' )-;
946             }
947           } else {
948             qq-( $_ IS NULL OR $_ = "" )-;
949           }
950
951         } else {
952           "$_ = ". _quote($old->getfield($_),$old->table,$_);
953         }
954
955       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
956     )
957   ;
958   warn "[debug]$me $statement\n" if $DEBUG > 1;
959   my $sth = dbh->prepare($statement) or return dbh->errstr;
960
961   my $h_old_sth;
962   if ( defined $dbdef->table('h_'. $old->table) ) {
963     my $h_old_statement = $old->_h_statement('replace_old');
964     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
965     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
966   } else {
967     $h_old_sth = '';
968   }
969
970   my $h_new_sth;
971   if ( defined $dbdef->table('h_'. $new->table) ) {
972     my $h_new_statement = $new->_h_statement('replace_new');
973     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
974     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
975   } else {
976     $h_new_sth = '';
977   }
978
979   # For virtual fields we have three cases with different SQL 
980   # statements: add, replace, delete
981   my $v_add_sth;
982   my $v_rep_sth;
983   my $v_del_sth;
984   my (@add_vfields, @rep_vfields, @del_vfields);
985   my $vfp = $old->vfieldpart_hashref;
986   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
987     if($diff{$_} eq '') {
988       # Delete
989       unless(@del_vfields) {
990         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
991                  "AND vfieldpart = ?";
992         warn "[debug]$me $st\n" if $DEBUG > 2;
993         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
994       }
995       push @del_vfields, $_;
996     } elsif($old->getfield($_) eq '') {
997       # Add
998       unless(@add_vfields) {
999         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1000                  "VALUES (?, ?, ?)";
1001         warn "[debug]$me $st\n" if $DEBUG > 2;
1002         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1003       }
1004       push @add_vfields, $_;
1005     } else {
1006       # Replace
1007       unless(@rep_vfields) {
1008         my $st = "UPDATE virtual_field SET value = ? ".
1009                  "WHERE recnum = ? AND vfieldpart = ?";
1010         warn "[debug]$me $st\n" if $DEBUG > 2;
1011         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1012       }
1013       push @rep_vfields, $_;
1014     }
1015   }
1016
1017   local $SIG{HUP} = 'IGNORE';
1018   local $SIG{INT} = 'IGNORE';
1019   local $SIG{QUIT} = 'IGNORE'; 
1020   local $SIG{TERM} = 'IGNORE';
1021   local $SIG{TSTP} = 'IGNORE';
1022   local $SIG{PIPE} = 'IGNORE';
1023
1024   my $rc = $sth->execute or return $sth->errstr;
1025   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1026   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1027   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1028
1029   $v_del_sth->execute($old->getfield($primary_key),
1030                       $vfp->{$_})
1031         or return $v_del_sth->errstr
1032       foreach(@del_vfields);
1033
1034   $v_add_sth->execute($new->getfield($_),
1035                       $old->getfield($primary_key),
1036                       $vfp->{$_})
1037         or return $v_add_sth->errstr
1038       foreach(@add_vfields);
1039
1040   $v_rep_sth->execute($new->getfield($_),
1041                       $old->getfield($primary_key),
1042                       $vfp->{$_})
1043         or return $v_rep_sth->errstr
1044       foreach(@rep_vfields);
1045
1046   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1047
1048   # Now that it has been saved, reset the encrypted fields so that $new 
1049   # can still be used.
1050   foreach my $field (keys %{$saved}) {
1051     $new->setfield($field, $saved->{$field});
1052   }
1053
1054   '';
1055
1056 }
1057
1058 =item rep
1059
1060 Depriciated (use replace instead).
1061
1062 =cut
1063
1064 sub rep {
1065   cluck "warning: FS::Record::rep deprecated!";
1066   replace @_; #call method in this scope
1067 }
1068
1069 =item check
1070
1071 Checks virtual fields (using check_blocks).  Subclasses should still provide 
1072 a check method to validate real fields, foreign keys, etc., and call this 
1073 method via $self->SUPER::check.
1074
1075 (FIXME: Should this method try to make sure that it I<is> being called from 
1076 a subclass's check method, to keep the current semantics as far as possible?)
1077
1078 =cut
1079
1080 sub check {
1081   #confess "FS::Record::check not implemented; supply one in subclass!";
1082   my $self = shift;
1083
1084   foreach my $field ($self->virtual_fields) {
1085     for ($self->getfield($field)) {
1086       # See notes on check_block in FS::part_virtual_field.
1087       eval $self->pvf($field)->check_block;
1088       if ( $@ ) {
1089         #this is bad, probably want to follow the stack backtrace up and see
1090         #wtf happened
1091         my $err = "Fatal error checking $field for $self";
1092         cluck "$err: $@";
1093         return "$err (see log for backtrace): $@";
1094
1095       }
1096       $self->setfield($field, $_);
1097     }
1098   }
1099   '';
1100 }
1101
1102 sub _h_statement {
1103   my( $self, $action, $time ) = @_;
1104
1105   $time ||= time;
1106
1107   my @fields =
1108     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1109     real_fields($self->table);
1110   ;
1111   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1112
1113   "INSERT INTO h_". $self->table. " ( ".
1114       join(', ', qw(history_date history_user history_action), @fields ).
1115     ") VALUES (".
1116       join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1117     ")"
1118   ;
1119 }
1120
1121 =item unique COLUMN
1122
1123 B<Warning>: External use is B<deprecated>.  
1124
1125 Replaces COLUMN in record with a unique number, using counters in the
1126 filesystem.  Used by the B<insert> method on single-field unique columns
1127 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1128 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1129
1130 Returns the new value.
1131
1132 =cut
1133
1134 sub unique {
1135   my($self,$field) = @_;
1136   my($table)=$self->table;
1137
1138   croak "Unique called on field $field, but it is ",
1139         $self->getfield($field),
1140         ", not null!"
1141     if $self->getfield($field);
1142
1143   #warn "table $table is tainted" if is_tainted($table);
1144   #warn "field $field is tainted" if is_tainted($field);
1145
1146   my($counter) = new File::CounterFile "$table.$field",0;
1147 # hack for web demo
1148 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1149 #  my($user)=$1;
1150 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1151 # endhack
1152
1153   my $index = $counter->inc;
1154   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1155
1156   $index =~ /^(\d*)$/;
1157   $index=$1;
1158
1159   $self->setfield($field,$index);
1160
1161 }
1162
1163 =item ut_float COLUMN
1164
1165 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1166 null.  If there is an error, returns the error, otherwise returns false.
1167
1168 =cut
1169
1170 sub ut_float {
1171   my($self,$field)=@_ ;
1172   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1173    $self->getfield($field) =~ /^(\d+)$/ ||
1174    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1175    $self->getfield($field) =~ /^(\d+e\d+)$/)
1176     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1177   $self->setfield($field,$1);
1178   '';
1179 }
1180
1181 =item ut_snumber COLUMN
1182
1183 Check/untaint signed numeric data (whole numbers).  May not be null.  If there
1184 is an error, returns the error, otherwise returns false.
1185
1186 =cut
1187
1188 sub ut_snumber {
1189   my($self, $field) = @_;
1190   $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1191     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1192   $self->setfield($field, "$1$2");
1193   '';
1194 }
1195
1196 =item ut_number COLUMN
1197
1198 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1199 is an error, returns the error, otherwise returns false.
1200
1201 =cut
1202
1203 sub ut_number {
1204   my($self,$field)=@_;
1205   $self->getfield($field) =~ /^(\d+)$/
1206     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1207   $self->setfield($field,$1);
1208   '';
1209 }
1210
1211 =item ut_numbern COLUMN
1212
1213 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1214 an error, returns the error, otherwise returns false.
1215
1216 =cut
1217
1218 sub ut_numbern {
1219   my($self,$field)=@_;
1220   $self->getfield($field) =~ /^(\d*)$/
1221     or return "Illegal (numeric) $field: ". $self->getfield($field);
1222   $self->setfield($field,$1);
1223   '';
1224 }
1225
1226 =item ut_money COLUMN
1227
1228 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1229 is an error, returns the error, otherwise returns false.
1230
1231 =cut
1232
1233 sub ut_money {
1234   my($self,$field)=@_;
1235   $self->setfield($field, 0) if $self->getfield($field) eq '';
1236   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1237     or return "Illegal (money) $field: ". $self->getfield($field);
1238   #$self->setfield($field, "$1$2$3" || 0);
1239   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1240   '';
1241 }
1242
1243 =item ut_text COLUMN
1244
1245 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1246 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1247 May not be null.  If there is an error, returns the error, otherwise returns
1248 false.
1249
1250 =cut
1251
1252 sub ut_text {
1253   my($self,$field)=@_;
1254   #warn "msgcat ". \&msgcat. "\n";
1255   #warn "notexist ". \&notexist. "\n";
1256   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1257   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1258     or return gettext('illegal_or_empty_text'). " $field: ".
1259                $self->getfield($field);
1260   $self->setfield($field,$1);
1261   '';
1262 }
1263
1264 =item ut_textn COLUMN
1265
1266 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1267 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1268 May be null.  If there is an error, returns the error, otherwise returns false.
1269
1270 =cut
1271
1272 sub ut_textn {
1273   my($self,$field)=@_;
1274   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1275     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1276   $self->setfield($field,$1);
1277   '';
1278 }
1279
1280 =item ut_alpha COLUMN
1281
1282 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1283 an error, returns the error, otherwise returns false.
1284
1285 =cut
1286
1287 sub ut_alpha {
1288   my($self,$field)=@_;
1289   $self->getfield($field) =~ /^(\w+)$/
1290     or return "Illegal or empty (alphanumeric) $field: ".
1291               $self->getfield($field);
1292   $self->setfield($field,$1);
1293   '';
1294 }
1295
1296 =item ut_alpha COLUMN
1297
1298 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1299 error, returns the error, otherwise returns false.
1300
1301 =cut
1302
1303 sub ut_alphan {
1304   my($self,$field)=@_;
1305   $self->getfield($field) =~ /^(\w*)$/ 
1306     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1307   $self->setfield($field,$1);
1308   '';
1309 }
1310
1311 =item ut_phonen COLUMN [ COUNTRY ]
1312
1313 Check/untaint phone numbers.  May be null.  If there is an error, returns
1314 the error, otherwise returns false.
1315
1316 Takes an optional two-letter ISO country code; without it or with unsupported
1317 countries, ut_phonen simply calls ut_alphan.
1318
1319 =cut
1320
1321 sub ut_phonen {
1322   my( $self, $field, $country ) = @_;
1323   return $self->ut_alphan($field) unless defined $country;
1324   my $phonen = $self->getfield($field);
1325   if ( $phonen eq '' ) {
1326     $self->setfield($field,'');
1327   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1328     $phonen =~ s/\D//g;
1329     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1330       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1331     $phonen = "$1-$2-$3";
1332     $phonen .= " x$4" if $4;
1333     $self->setfield($field,$phonen);
1334   } else {
1335     warn "warning: don't know how to check phone numbers for country $country";
1336     return $self->ut_textn($field);
1337   }
1338   '';
1339 }
1340
1341 =item ut_ip COLUMN
1342
1343 Check/untaint ip addresses.  IPv4 only for now.
1344
1345 =cut
1346
1347 sub ut_ip {
1348   my( $self, $field ) = @_;
1349   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1350     or return "Illegal (IP address) $field: ". $self->getfield($field);
1351   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1352   $self->setfield($field, "$1.$2.$3.$4");
1353   '';
1354 }
1355
1356 =item ut_ipn COLUMN
1357
1358 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1359
1360 =cut
1361
1362 sub ut_ipn {
1363   my( $self, $field ) = @_;
1364   if ( $self->getfield($field) =~ /^()$/ ) {
1365     $self->setfield($field,'');
1366     '';
1367   } else {
1368     $self->ut_ip($field);
1369   }
1370 }
1371
1372 =item ut_domain COLUMN
1373
1374 Check/untaint host and domain names.
1375
1376 =cut
1377
1378 sub ut_domain {
1379   my( $self, $field ) = @_;
1380   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1381   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1382     or return "Illegal (domain) $field: ". $self->getfield($field);
1383   $self->setfield($field,$1);
1384   '';
1385 }
1386
1387 =item ut_name COLUMN
1388
1389 Check/untaint proper names; allows alphanumerics, spaces and the following
1390 punctuation: , . - '
1391
1392 May not be null.
1393
1394 =cut
1395
1396 sub ut_name {
1397   my( $self, $field ) = @_;
1398   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1399     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1400   $self->setfield($field,$1);
1401   '';
1402 }
1403
1404 =item ut_zip COLUMN
1405
1406 Check/untaint zip codes.
1407
1408 =cut
1409
1410 sub ut_zip {
1411   my( $self, $field, $country ) = @_;
1412   if ( $country eq 'US' ) {
1413     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1414       or return gettext('illegal_zip'). " $field for country $country: ".
1415                 $self->getfield($field);
1416     $self->setfield($field,$1);
1417   } else {
1418     if ( $self->getfield($field) =~ /^\s*$/ ) {
1419       $self->setfield($field,'');
1420     } else {
1421       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1422         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1423       $self->setfield($field,$1);
1424     }
1425   }
1426   '';
1427 }
1428
1429 =item ut_country COLUMN
1430
1431 Check/untaint country codes.  Country names are changed to codes, if possible -
1432 see L<Locale::Country>.
1433
1434 =cut
1435
1436 sub ut_country {
1437   my( $self, $field ) = @_;
1438   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1439     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1440          && country2code($1) ) {
1441       $self->setfield($field,uc(country2code($1)));
1442     }
1443   }
1444   $self->getfield($field) =~ /^(\w\w)$/
1445     or return "Illegal (country) $field: ". $self->getfield($field);
1446   $self->setfield($field,uc($1));
1447   '';
1448 }
1449
1450 =item ut_anything COLUMN
1451
1452 Untaints arbitrary data.  Be careful.
1453
1454 =cut
1455
1456 sub ut_anything {
1457   my( $self, $field ) = @_;
1458   $self->getfield($field) =~ /^(.*)$/s
1459     or return "Illegal $field: ". $self->getfield($field);
1460   $self->setfield($field,$1);
1461   '';
1462 }
1463
1464 =item ut_enum COLUMN CHOICES_ARRAYREF
1465
1466 Check/untaint a column, supplying all possible choices, like the "enum" type.
1467
1468 =cut
1469
1470 sub ut_enum {
1471   my( $self, $field, $choices ) = @_;
1472   foreach my $choice ( @$choices ) {
1473     if ( $self->getfield($field) eq $choice ) {
1474       $self->setfield($choice);
1475       return '';
1476     }
1477   }
1478   return "Illegal (enum) field $field: ". $self->getfield($field);
1479 }
1480
1481 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1482
1483 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1484 on the column first.
1485
1486 =cut
1487
1488 sub ut_foreign_key {
1489   my( $self, $field, $table, $foreign ) = @_;
1490   qsearchs($table, { $foreign => $self->getfield($field) })
1491     or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1492               " in $table.$foreign";
1493   '';
1494 }
1495
1496 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1497
1498 Like ut_foreign_key, except the null value is also allowed.
1499
1500 =cut
1501
1502 sub ut_foreign_keyn {
1503   my( $self, $field, $table, $foreign ) = @_;
1504   $self->getfield($field)
1505     ? $self->ut_foreign_key($field, $table, $foreign)
1506     : '';
1507 }
1508
1509
1510 =item virtual_fields [ TABLE ]
1511
1512 Returns a list of virtual fields defined for the table.  This should not 
1513 be exported, and should only be called as an instance or class method.
1514
1515 =cut
1516
1517 sub virtual_fields {
1518   my $self = shift;
1519   my $table;
1520   $table = $self->table or confess "virtual_fields called on non-table";
1521
1522   confess "Unknown table $table" unless $dbdef->table($table);
1523
1524   return () unless $self->dbdef->table('part_virtual_field');
1525
1526   unless ( $virtual_fields_cache{$table} ) {
1527     my $query = 'SELECT name from part_virtual_field ' .
1528                 "WHERE dbtable = '$table'";
1529     my $dbh = dbh;
1530     my $result = $dbh->selectcol_arrayref($query);
1531     confess $dbh->errstr if $dbh->err;
1532     $virtual_fields_cache{$table} = $result;
1533   }
1534
1535   @{$virtual_fields_cache{$table}};
1536
1537 }
1538
1539
1540 =item fields [ TABLE ]
1541
1542 This is a wrapper for real_fields and virtual_fields.  Code that called
1543 fields before should probably continue to call fields.
1544
1545 =cut
1546
1547 sub fields {
1548   my $something = shift;
1549   my $table;
1550   if($something->isa('FS::Record')) {
1551     $table = $something->table;
1552   } else {
1553     $table = $something;
1554     $something = "FS::$table";
1555   }
1556   return (real_fields($table), $something->virtual_fields());
1557 }
1558
1559 =back
1560
1561 =item pvf FIELD_NAME
1562
1563 Returns the FS::part_virtual_field object corresponding to a field in the 
1564 record (specified by FIELD_NAME).
1565
1566 =cut
1567
1568 sub pvf {
1569   my ($self, $name) = (shift, shift);
1570
1571   if(grep /^$name$/, $self->virtual_fields) {
1572     return qsearchs('part_virtual_field', { dbtable => $self->table,
1573                                             name    => $name } );
1574   }
1575   ''
1576 }
1577
1578 =head1 SUBROUTINES
1579
1580 =over 4
1581
1582 =item real_fields [ TABLE ]
1583
1584 Returns a list of the real columns in the specified table.  Called only by 
1585 fields() and other subroutines elsewhere in FS::Record.
1586
1587 =cut
1588
1589 sub real_fields {
1590   my $table = shift;
1591
1592   my($table_obj) = $dbdef->table($table);
1593   confess "Unknown table $table" unless $table_obj;
1594   $table_obj->columns;
1595 }
1596
1597 =item reload_dbdef([FILENAME])
1598
1599 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1600 non-default filename.  This command is executed at startup unless
1601 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1602
1603 =cut
1604
1605 sub reload_dbdef {
1606   my $file = shift || $dbdef_file;
1607
1608   unless ( exists $dbdef_cache{$file} ) {
1609     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1610     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1611                             or die "can't load database schema from $file";
1612   } else {
1613     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1614   }
1615   $dbdef = $dbdef_cache{$file};
1616 }
1617
1618 =item dbdef
1619
1620 Returns the current database definition.  See L<DBIx::DBSchema>.
1621
1622 =cut
1623
1624 sub dbdef { $dbdef; }
1625
1626 =item _quote VALUE, TABLE, COLUMN
1627
1628 This is an internal function used to construct SQL statements.  It returns
1629 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1630 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1631
1632 =cut
1633
1634 sub _quote {
1635   my($value, $table, $column) = @_;
1636   my $column_obj = $dbdef->table($table)->column($column);
1637   my $column_type = $column_obj->type;
1638   my $nullable = $column_obj->null;
1639
1640   warn "  $table.$column: $value ($column_type".
1641        ( $nullable ? ' NULL' : ' NOT NULL' ).
1642        ")\n" if $DEBUG > 2;
1643
1644   if ( $value eq '' && $column_type =~ /^int/ ) {
1645     if ( $nullable ) {
1646       'NULL';
1647     } else {
1648       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1649             "using 0 instead";
1650       0;
1651     }
1652   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1653             ! $column_type =~ /(char|binary|text)$/i ) {
1654     $value;
1655   } else {
1656     dbh->quote($value);
1657   }
1658 }
1659
1660 =item vfieldpart_hashref TABLE
1661
1662 Returns a hashref of virtual field names and vfieldparts applicable to the given
1663 TABLE.
1664
1665 =cut
1666
1667 sub vfieldpart_hashref {
1668   my $self = shift;
1669   my $table = $self->table;
1670
1671   return {} unless $self->dbdef->table('part_virtual_field');
1672
1673   my $dbh = dbh;
1674   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1675                   "dbtable = '$table'";
1676   my $sth = $dbh->prepare($statement);
1677   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1678   return { map { $_->{name}, $_->{vfieldpart} } 
1679     @{$sth->fetchall_arrayref({})} };
1680
1681 }
1682
1683
1684 =item hfields TABLE
1685
1686 This is deprecated.  Don't use it.
1687
1688 It returns a hash-type list with the fields of this record's table set true.
1689
1690 =cut
1691
1692 sub hfields {
1693   carp "warning: hfields is deprecated";
1694   my($table)=@_;
1695   my(%hash);
1696   foreach (fields($table)) {
1697     $hash{$_}=1;
1698   }
1699   \%hash;
1700 }
1701
1702 sub _dump {
1703   my($self)=@_;
1704   join("\n", map {
1705     "$_: ". $self->getfield($_). "|"
1706   } (fields($self->table)) );
1707 }
1708
1709 sub encrypt {
1710   my ($self, $value) = @_;
1711   my $encrypted;
1712
1713   if ($conf->exists('encryption')) {
1714     if ($self->is_encrypted($value)) {
1715       # Return the original value if it isn't plaintext.
1716       $encrypted = $value;
1717     } else {
1718       $self->loadRSA;
1719       if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1720         # RSA doesn't like the empty string so let's pack it up
1721         # The database doesn't like the RSA data so uuencode it
1722         my $length = length($value)+1;
1723         $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1724       } else {
1725         die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1726       }
1727     }
1728   }
1729   return $encrypted;
1730 }
1731
1732 sub is_encrypted {
1733   my ($self, $value) = @_;
1734   # Possible Bug - Some work may be required here....
1735
1736   if (length($value) > 80) {
1737     return 1;
1738   } else {
1739     return 0;
1740   }
1741 }
1742
1743 sub decrypt {
1744   my ($self,$value) = @_;
1745   my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1746   if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1747     $self->loadRSA;
1748     if (ref($rsa_decrypt) =~ /::RSA/) {
1749       my $encrypted = unpack ("u*", $value);
1750       $decrypted =  unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1751     }
1752   }
1753   return $decrypted;
1754 }
1755
1756 sub loadRSA {
1757     my $self = shift;
1758     #Initialize the Module
1759     $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1760
1761     if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1762       $rsa_module = $conf->config('encryptionmodule');
1763     }
1764
1765     if (!$rsa_loaded) {
1766         eval ("require $rsa_module"); # No need to import the namespace
1767         $rsa_loaded++;
1768     }
1769     # Initialize Encryption
1770     if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1771       my $public_key = join("\n",$conf->config('encryptionpublickey'));
1772       $rsa_encrypt = $rsa_module->new_public_key($public_key);
1773     }
1774     
1775     # Intitalize Decryption
1776     if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1777       my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1778       $rsa_decrypt = $rsa_module->new_private_key($private_key);
1779     }
1780 }
1781
1782 sub DESTROY { return; }
1783
1784 #sub DESTROY {
1785 #  my $self = shift;
1786 #  #use Carp qw(cluck);
1787 #  #cluck "DESTROYING $self";
1788 #  warn "DESTROYING $self";
1789 #}
1790
1791 #sub is_tainted {
1792 #             return ! eval { join('',@_), kill 0; 1; };
1793 #         }
1794
1795 =back
1796
1797 =head1 BUGS
1798
1799 This module should probably be renamed, since much of the functionality is
1800 of general use.  It is not completely unlike Adapter::DBI (see below).
1801
1802 Exported qsearch and qsearchs should be deprecated in favor of method calls
1803 (against an FS::Record object like the old search and searchs that qsearch
1804 and qsearchs were on top of.)
1805
1806 The whole fields / hfields mess should be removed.
1807
1808 The various WHERE clauses should be subroutined.
1809
1810 table string should be deprecated in favor of DBIx::DBSchema::Table.
1811
1812 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1813 true maps to the database (and WHERE clauses) would also help.
1814
1815 The ut_ methods should ask the dbdef for a default length.
1816
1817 ut_sqltype (like ut_varchar) should all be defined
1818
1819 A fallback check method should be provided which uses the dbdef.
1820
1821 The ut_money method assumes money has two decimal digits.
1822
1823 The Pg money kludge in the new method only strips `$'.
1824
1825 The ut_phonen method only checks US-style phone numbers.
1826
1827 The _quote function should probably use ut_float instead of a regex.
1828
1829 All the subroutines probably should be methods, here or elsewhere.
1830
1831 Probably should borrow/use some dbdef methods where appropriate (like sub
1832 fields)
1833
1834 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1835 or allow it to be set.  Working around it is ugly any way around - DBI should
1836 be fixed.  (only affects RDBMS which return uppercase column names)
1837
1838 ut_zip should take an optional country like ut_phone.
1839
1840 =head1 SEE ALSO
1841
1842 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1843
1844 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1845
1846 http://poop.sf.net/
1847
1848 =cut
1849
1850 1;
1851