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