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