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