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