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