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