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