This commit was generated by cvs2svn to compensate for changes in r11022,
[freeside.git] / FS / FS / Record.pm
1 package FS::Record;
2
3 use strict;
4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5              $conf $conf_encryption $me
6              %virtual_fields_cache
7              $nowarn_identical $nowarn_classload
8              $no_update_diff $no_check_foreign
9            );
10 use Exporter;
11 use Carp qw(carp cluck croak confess);
12 use Scalar::Util qw( blessed );
13 use File::CounterFile;
14 use Locale::Country;
15 use Text::CSV_XS;
16 use File::Slurp qw( slurp );
17 use DBI qw(:sql_types);
18 use DBIx::DBSchema 0.38;
19 use FS::UID qw(dbh getotaker datasrc driver_name);
20 use FS::CurrentUser;
21 use FS::Schema qw(dbdef);
22 use FS::SearchCache;
23 use FS::Msgcat qw(gettext);
24 use NetAddr::IP; # for validation
25 #use FS::Conf; #dependency loop bs, in install_callback below instead
26
27 use FS::part_virtual_field;
28
29 use Tie::IxHash;
30
31 @ISA = qw(Exporter);
32
33 #export dbdef for now... everything else expects to find it here
34 @EXPORT_OK = qw(
35   dbh fields hfields qsearch qsearchs dbdef jsearch
36   str2time_sql str2time_sql_closing regexp_sql not_regexp_sql concat_sql
37 );
38
39 $DEBUG = 0;
40 $me = '[FS::Record]';
41
42 $nowarn_identical = 0;
43 $nowarn_classload = 0;
44 $no_update_diff = 0;
45 $no_check_foreign = 0;
46
47 my $rsa_module;
48 my $rsa_loaded;
49 my $rsa_encrypt;
50 my $rsa_decrypt;
51
52 $conf = '';
53 $conf_encryption = '';
54 FS::UID->install_callback( sub {
55   eval "use FS::Conf;";
56   die $@ if $@;
57   $conf = FS::Conf->new; 
58   $conf_encryption = $conf->exists('encryption');
59   $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
60   if ( driver_name eq 'Pg' ) {
61     eval "use DBD::Pg ':pg_types'";
62     die $@ if $@;
63   } else {
64     eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
65   }
66 } );
67
68 =head1 NAME
69
70 FS::Record - Database record objects
71
72 =head1 SYNOPSIS
73
74     use FS::Record;
75     use FS::Record qw(dbh fields qsearch qsearchs);
76
77     $record = new FS::Record 'table', \%hash;
78     $record = new FS::Record 'table', { 'column' => 'value', ... };
79
80     $record  = qsearchs FS::Record 'table', \%hash;
81     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
82     @records = qsearch  FS::Record 'table', \%hash; 
83     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
84
85     $table = $record->table;
86     $dbdef_table = $record->dbdef_table;
87
88     $value = $record->get('column');
89     $value = $record->getfield('column');
90     $value = $record->column;
91
92     $record->set( 'column' => 'value' );
93     $record->setfield( 'column' => 'value' );
94     $record->column('value');
95
96     %hash = $record->hash;
97
98     $hashref = $record->hashref;
99
100     $error = $record->insert;
101
102     $error = $record->delete;
103
104     $error = $new_record->replace($old_record);
105
106     # external use deprecated - handled by the database (at least for Pg, mysql)
107     $value = $record->unique('column');
108
109     $error = $record->ut_float('column');
110     $error = $record->ut_floatn('column');
111     $error = $record->ut_number('column');
112     $error = $record->ut_numbern('column');
113     $error = $record->ut_snumber('column');
114     $error = $record->ut_snumbern('column');
115     $error = $record->ut_money('column');
116     $error = $record->ut_text('column');
117     $error = $record->ut_textn('column');
118     $error = $record->ut_alpha('column');
119     $error = $record->ut_alphan('column');
120     $error = $record->ut_phonen('column');
121     $error = $record->ut_anything('column');
122     $error = $record->ut_name('column');
123
124     $quoted_value = _quote($value,'table','field');
125
126     #deprecated
127     $fields = hfields('table');
128     if ( $fields->{Field} ) { # etc.
129
130     @fields = fields 'table'; #as a subroutine
131     @fields = $record->fields; #as a method call
132
133
134 =head1 DESCRIPTION
135
136 (Mostly) object-oriented interface to database records.  Records are currently
137 implemented on top of DBI.  FS::Record is intended as a base class for
138 table-specific classes to inherit from, i.e. FS::cust_main.
139
140 =head1 CONSTRUCTORS
141
142 =over 4
143
144 =item new [ TABLE, ] HASHREF
145
146 Creates a new record.  It doesn't store it in the database, though.  See
147 L<"insert"> for that.
148
149 Note that the object stores this hash reference, not a distinct copy of the
150 hash it points to.  You can ask the object for a copy with the I<hash> 
151 method.
152
153 TABLE can only be omitted when a dervived class overrides the table method.
154
155 =cut
156
157 sub new { 
158   my $proto = shift;
159   my $class = ref($proto) || $proto;
160   my $self = {};
161   bless ($self, $class);
162
163   unless ( defined ( $self->table ) ) {
164     $self->{'Table'} = shift;
165     carp "warning: FS::Record::new called with table name ". $self->{'Table'}
166       unless $nowarn_classload;
167   }
168   
169   $self->{'Hash'} = shift;
170
171   foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) { 
172     $self->{'Hash'}{$field}='';
173   }
174
175   $self->_rebless if $self->can('_rebless');
176
177   $self->{'modified'} = 0;
178
179   $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
180
181   $self;
182 }
183
184 sub new_or_cached {
185   my $proto = shift;
186   my $class = ref($proto) || $proto;
187   my $self = {};
188   bless ($self, $class);
189
190   $self->{'Table'} = shift unless defined ( $self->table );
191
192   my $hashref = $self->{'Hash'} = shift;
193   my $cache = shift;
194   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
195     my $obj = $cache->cache->{$hashref->{$cache->key}};
196     $obj->_cache($hashref, $cache) if $obj->can('_cache');
197     $obj;
198   } else {
199     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
200   }
201
202 }
203
204 sub create {
205   my $proto = shift;
206   my $class = ref($proto) || $proto;
207   my $self = {};
208   bless ($self, $class);
209   if ( defined $self->table ) {
210     cluck "create constructor is deprecated, use new!";
211     $self->new(@_);
212   } else {
213     croak "FS::Record::create called (not from a subclass)!";
214   }
215 }
216
217 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
218
219 Searches the database for all records matching (at least) the key/value pairs
220 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
221 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
222 objects.
223
224 The preferred usage is to pass a hash reference of named parameters:
225
226   @records = qsearch( {
227                         'table'       => 'table_name',
228                         'hashref'     => { 'field' => 'value'
229                                            'field' => { 'op'    => '<',
230                                                         'value' => '420',
231                                                       },
232                                          },
233
234                         #these are optional...
235                         'select'      => '*',
236                         'extra_sql'   => 'AND field = ? AND intfield = ?',
237                         'extra_param' => [ 'value', [ 5, 'int' ] ],
238                         'order_by'    => 'ORDER BY something',
239                         #'cache_obj'   => '', #optional
240                         'addl_from'   => 'LEFT JOIN othtable USING ( field )',
241                         'debug'       => 1,
242                       }
243                     );
244
245 Much code still uses old-style positional parameters, this is also probably
246 fine in the common case where there are only two parameters:
247
248   my @records = qsearch( 'table', { 'field' => 'value' } );
249
250 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
251 the individual PARAMS_HASHREF queries
252
253 ###oops, argh, FS::Record::new only lets us create database fields.
254 #Normal behaviour if SELECT is not specified is `*', as in
255 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
256 #feature where you can specify SELECT - remember, the objects returned,
257 #although blessed into the appropriate `FS::TABLE' package, will only have the
258 #fields you specify.  This might have unwanted results if you then go calling
259 #regular FS::TABLE methods
260 #on it.
261
262 =cut
263
264 my %TYPE = (); #for debugging
265
266 sub _bind_type {
267   my($type, $value) = @_;
268
269   my $bind_type = { TYPE => SQL_VARCHAR };
270
271   if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
272
273     $bind_type = { TYPE => SQL_INTEGER };
274
275   } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
276
277     if ( driver_name eq 'Pg' ) {
278       no strict 'subs';
279       $bind_type = { pg_type => PG_BYTEA };
280     #} else {
281     #  $bind_type = ? #SQL_VARCHAR could be fine?
282     }
283
284   #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
285   #fixed by DBD::Pg 2.11.8
286   #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
287   #(make a Tron test first)
288   } elsif ( _is_fs_float( $type, $value ) ) {
289
290     $bind_type = { TYPE => SQL_DECIMAL };
291
292   }
293
294   $bind_type;
295
296 }
297
298 sub _is_fs_float {
299   my($type, $value) = @_;
300   if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
301        ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
302      ) {
303     return 1;
304   }
305   '';
306 }
307
308 sub qsearch {
309   my( @stable, @record, @cache );
310   my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
311   my @debug = ();
312   my %union_options = ();
313   if ( ref($_[0]) eq 'ARRAY' ) {
314     my $optlist = shift;
315     %union_options = @_;
316     foreach my $href ( @$optlist ) {
317       push @stable,      ( $href->{'table'} or die "table name is required" );
318       push @record,      ( $href->{'hashref'}     || {} );
319       push @select,      ( $href->{'select'}      || '*' );
320       push @extra_sql,   ( $href->{'extra_sql'}   || '' );
321       push @extra_param, ( $href->{'extra_param'} || [] );
322       push @order_by,    ( $href->{'order_by'}    || '' );
323       push @cache,       ( $href->{'cache_obj'}   || '' );
324       push @addl_from,   ( $href->{'addl_from'}   || '' );
325       push @debug,       ( $href->{'debug'}       || '' );
326     }
327     die "at least one hashref is required" unless scalar(@stable);
328   } elsif ( ref($_[0]) eq 'HASH' ) {
329     my $opt = shift;
330     $stable[0]      = $opt->{'table'}       or die "table name is required";
331     $record[0]      = $opt->{'hashref'}     || {};
332     $select[0]      = $opt->{'select'}      || '*';
333     $extra_sql[0]   = $opt->{'extra_sql'}   || '';
334     $extra_param[0] = $opt->{'extra_param'} || [];
335     $order_by[0]    = $opt->{'order_by'}    || '';
336     $cache[0]       = $opt->{'cache_obj'}   || '';
337     $addl_from[0]   = $opt->{'addl_from'}   || '';
338     $debug[0]       = $opt->{'debug'}       || '';
339   } else {
340     ( $stable[0],
341       $record[0],
342       $select[0],
343       $extra_sql[0],
344       $cache[0],
345       $addl_from[0]
346     ) = @_;
347     $select[0] ||= '*';
348   }
349   my $cache = $cache[0];
350
351   my @statement = ();
352   my @value = ();
353   my @bind_type = ();
354   my $dbh = dbh;
355   foreach my $stable ( @stable ) {
356     #stop altering the caller's hashref
357     my $record      = { %{ shift(@record) || {} } };#and be liberal in receipt
358     my $select      = shift @select;
359     my $extra_sql   = shift @extra_sql;
360     my $extra_param = shift @extra_param;
361     my $order_by    = shift @order_by;
362     my $cache       = shift @cache;
363     my $addl_from   = shift @addl_from;
364     my $debug       = shift @debug;
365
366     #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
367     #for jsearch
368     $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
369     $stable = $1;
370
371     my $table = $cache ? $cache->table : $stable;
372     my $dbdef_table = dbdef->table($table)
373       or die "No schema for table $table found - ".
374              "do you need to run freeside-upgrade?";
375     my $pkey = $dbdef_table->primary_key;
376
377     my @real_fields = grep exists($record->{$_}), real_fields($table);
378     my @virtual_fields;
379     if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
380       @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
381     } else {
382       cluck "warning: FS::$table not loaded; virtual fields not searchable"
383         unless $nowarn_classload;
384       @virtual_fields = ();
385     }
386
387     my $statement .= "SELECT $select FROM $stable";
388     $statement .= " $addl_from" if $addl_from;
389     if ( @real_fields or @virtual_fields ) {
390       $statement .= ' WHERE '. join(' AND ',
391         get_real_fields($table, $record, \@real_fields) ,
392         get_virtual_fields($table, $pkey, $record, \@virtual_fields),
393         );
394     }
395
396     $statement .= " $extra_sql" if defined($extra_sql);
397     $statement .= " $order_by"  if defined($order_by);
398
399     push @statement, $statement;
400
401     warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
402  
403
404     foreach my $field (
405       grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
406     ) {
407
408       my $value = $record->{$field};
409       my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
410       $value = $value->{'value'} if ref($value);
411       my $type = dbdef->table($table)->column($field)->type;
412
413       my $bind_type = _bind_type($type, $value);
414
415       #if ( $DEBUG > 2 ) {
416       #  no strict 'refs';
417       #  %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
418       #    unless keys %TYPE;
419       #  warn "  bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
420       #}
421
422       push @value, $value;
423       push @bind_type, $bind_type;
424
425     }
426
427     foreach my $param ( @$extra_param ) {
428       my $bind_type = { TYPE => SQL_VARCHAR };
429       my $value = $param;
430       if ( ref($param) ) {
431         $value = $param->[0];
432         my $type = $param->[1];
433         $bind_type = _bind_type($type, $value);
434       }
435       push @value, $value;
436       push @bind_type, $bind_type;
437     }
438   }
439
440   my $statement = join( ' ) UNION ( ', @statement );
441   $statement = "( $statement )" if scalar(@statement) > 1;
442   $statement .= " $union_options{order_by}" if $union_options{order_by};
443
444   my $sth = $dbh->prepare($statement)
445     or croak "$dbh->errstr doing $statement";
446
447   my $bind = 1;
448   foreach my $value ( @value ) {
449     my $bind_type = shift @bind_type;
450     $sth->bind_param($bind++, $value, $bind_type );
451   }
452
453 #  $sth->execute( map $record->{$_},
454 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
455 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
456
457   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
458
459   # virtual fields and blessings are nonsense in a heterogeneous UNION, right?
460   my $table = $stable[0];
461   my $pkey = '';
462   $table = '' if grep { $_ ne $table } @stable;
463   $pkey = dbdef->table($table)->primary_key if $table;
464
465   my @virtual_fields = ();
466   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
467     @virtual_fields = "FS::$table"->virtual_fields;
468   } else {
469     cluck "warning: FS::$table not loaded; virtual fields not returned either"
470       unless $nowarn_classload;
471     @virtual_fields = ();
472   }
473
474   my %result;
475   tie %result, "Tie::IxHash";
476   my @stuff = @{ $sth->fetchall_arrayref( {} ) };
477   if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
478     %result = map { $_->{$pkey}, $_ } @stuff;
479   } else {
480     @result{@stuff} = @stuff;
481   }
482
483   $sth->finish;
484
485   if ( keys(%result) and @virtual_fields ) {
486     $statement =
487       "SELECT virtual_field.recnum, part_virtual_field.name, ".
488              "virtual_field.value ".
489       "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
490       "WHERE part_virtual_field.dbtable = '$table' AND ".
491       "virtual_field.recnum IN (".
492       join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
493       join(q!', '!, @virtual_fields) . "')";
494     warn "[debug]$me $statement\n" if $DEBUG > 1;
495     $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
496     $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
497
498     foreach (@{ $sth->fetchall_arrayref({}) }) {
499       my $recnum = $_->{recnum};
500       my $name = $_->{name};
501       my $value = $_->{value};
502       if (exists($result{$recnum})) {
503         $result{$recnum}->{$name} = $value;
504       }
505     }
506   }
507   my @return;
508   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
509     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
510       #derivied class didn't override new method, so this optimization is safe
511       if ( $cache ) {
512         @return = map {
513           new_or_cached( "FS::$table", { %{$_} }, $cache )
514         } values(%result);
515       } else {
516         @return = map {
517           new( "FS::$table", { %{$_} } )
518         } values(%result);
519       }
520     } else {
521       #okay, its been tested
522       # warn "untested code (class FS::$table uses custom new method)";
523       @return = map {
524         eval 'FS::'. $table. '->new( { %{$_} } )';
525       } values(%result);
526     }
527
528     # Check for encrypted fields and decrypt them.
529    ## only in the local copy, not the cached object
530     if ( $conf_encryption 
531          && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
532       foreach my $record (@return) {
533         foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
534           # Set it directly... This may cause a problem in the future...
535           $record->setfield($field, $record->decrypt($record->getfield($field)));
536         }
537       }
538     }
539   } else {
540     cluck "warning: FS::$table not loaded; returning FS::Record objects"
541       unless $nowarn_classload;
542     @return = map {
543       FS::Record->new( $table, { %{$_} } );
544     } values(%result);
545   }
546   return @return;
547 }
548
549 ## makes this easier to read
550
551 sub get_virtual_fields {
552    my $table = shift;
553    my $pkey = shift;
554    my $record = shift;
555    my $virtual_fields = shift;
556    
557    return
558     ( map {
559       my $op = '=';
560       my $column = $_;
561       if ( ref($record->{$_}) ) {
562         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
563         if ( uc($op) eq 'ILIKE' ) {
564           $op = 'LIKE';
565           $record->{$_}{'value'} = lc($record->{$_}{'value'});
566           $column = "LOWER($_)";
567         }
568         $record->{$_} = $record->{$_}{'value'};
569       }
570
571       # ... EXISTS ( SELECT name, value FROM part_virtual_field
572       #              JOIN virtual_field
573       #              ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
574       #              WHERE recnum = svc_acct.svcnum
575       #              AND (name, value) = ('egad', 'brain') )
576
577       my $value = $record->{$_};
578
579       my $subq;
580
581       $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
582       "( SELECT part_virtual_field.name, virtual_field.value ".
583       "FROM part_virtual_field JOIN virtual_field ".
584       "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
585       "WHERE virtual_field.recnum = ${table}.${pkey} ".
586       "AND part_virtual_field.name = '${column}'".
587       ($value ? 
588         " AND virtual_field.value ${op} '${value}'"
589       : "") . ")";
590       $subq;
591
592     } @{ $virtual_fields } ) ;
593 }
594
595 sub get_real_fields {
596   my $table = shift;
597   my $record = shift;
598   my $real_fields = shift;
599
600    ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
601       return ( 
602       map {
603
604       my $op = '=';
605       my $column = $_;
606       my $type = dbdef->table($table)->column($column)->type;
607       my $value = $record->{$column};
608       $value = $value->{'value'} if ref($value);
609       if ( ref($record->{$_}) ) {
610         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
611         #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
612         if ( uc($op) eq 'ILIKE' ) {
613           $op = 'LIKE';
614           $record->{$_}{'value'} = lc($record->{$_}{'value'});
615           $column = "LOWER($_)";
616         }
617         $record->{$_} = $record->{$_}{'value'}
618       }
619
620       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
621         if ( $op eq '=' ) {
622           if ( driver_name eq 'Pg' ) {
623             if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
624               qq-( $column IS NULL )-;
625             } else {
626               qq-( $column IS NULL OR $column = '' )-;
627             }
628           } else {
629             qq-( $column IS NULL OR $column = "" )-;
630           }
631         } elsif ( $op eq '!=' ) {
632           if ( driver_name eq 'Pg' ) {
633             if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
634               qq-( $column IS NOT NULL )-;
635             } else {
636               qq-( $column IS NOT NULL AND $column != '' )-;
637             }
638           } else {
639             qq-( $column IS NOT NULL AND $column != "" )-;
640           }
641         } else {
642           if ( driver_name eq 'Pg' ) {
643             qq-( $column $op '' )-;
644           } else {
645             qq-( $column $op "" )-;
646           }
647         }
648       #if this needs to be re-enabled, it needs to use a custom op like
649       #"APPROX=" or something (better name?, not '=', to avoid affecting other
650       # searches
651       #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
652       #  ( "$column <= ?", "$column >= ?" );
653       } else {
654         "$column $op ?";
655       }
656     } @{ $real_fields } );  
657 }
658
659 =item by_key PRIMARY_KEY_VALUE
660
661 This is a class method that returns the record with the given primary key
662 value.  This method is only useful in FS::Record subclasses.  For example:
663
664   my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
665
666 is equivalent to:
667
668   my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
669
670 =cut
671
672 sub by_key {
673   my ($class, $pkey_value) = @_;
674
675   my $table = $class->table
676     or croak "No table for $class found";
677
678   my $dbdef_table = dbdef->table($table)
679     or die "No schema for table $table found - ".
680            "do you need to create it or run dbdef-create?";
681   my $pkey = $dbdef_table->primary_key
682     or die "No primary key for table $table";
683
684   return qsearchs($table, { $pkey => $pkey_value });
685 }
686
687 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
688
689 Experimental JOINed search method.  Using this method, you can execute a
690 single SELECT spanning multiple tables, and cache the results for subsequent
691 method calls.  Interface will almost definately change in an incompatible
692 fashion.
693
694 Arguments: 
695
696 =cut
697
698 sub jsearch {
699   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
700   my $cache = FS::SearchCache->new( $ptable, $pkey );
701   my %saw;
702   ( $cache,
703     grep { !$saw{$_->getfield($pkey)}++ }
704       qsearch($table, $record, $select, $extra_sql, $cache )
705   );
706 }
707
708 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
709
710 Same as qsearch, except that if more than one record matches, it B<carp>s but
711 returns the first.  If this happens, you either made a logic error in asking
712 for a single item, or your data is corrupted.
713
714 =cut
715
716 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
717   my $table = $_[0];
718   my(@result) = qsearch(@_);
719   cluck "warning: Multiple records in scalar search ($table)"
720     if scalar(@result) > 1;
721   #should warn more vehemently if the search was on a primary key?
722   scalar(@result) ? ($result[0]) : ();
723 }
724
725 =back
726
727 =head1 METHODS
728
729 =over 4
730
731 =item table
732
733 Returns the table name.
734
735 =cut
736
737 sub table {
738 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
739   my $self = shift;
740   $self -> {'Table'};
741 }
742
743 =item dbdef_table
744
745 Returns the DBIx::DBSchema::Table object for the table.
746
747 =cut
748
749 sub dbdef_table {
750   my($self)=@_;
751   my($table)=$self->table;
752   dbdef->table($table);
753 }
754
755 =item primary_key
756
757 Returns the primary key for the table.
758
759 =cut
760
761 sub primary_key {
762   my $self = shift;
763   my $pkey = $self->dbdef_table->primary_key;
764 }
765
766 =item get, getfield COLUMN
767
768 Returns the value of the column/field/key COLUMN.
769
770 =cut
771
772 sub get {
773   my($self,$field) = @_;
774   # to avoid "Use of unitialized value" errors
775   if ( defined ( $self->{Hash}->{$field} ) ) {
776     $self->{Hash}->{$field};
777   } else { 
778     '';
779   }
780 }
781 sub getfield {
782   my $self = shift;
783   $self->get(@_);
784 }
785
786 =item set, setfield COLUMN, VALUE
787
788 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
789
790 =cut
791
792 sub set { 
793   my($self,$field,$value) = @_;
794   $self->{'modified'} = 1;
795   $self->{'Hash'}->{$field} = $value;
796 }
797 sub setfield {
798   my $self = shift;
799   $self->set(@_);
800 }
801
802 =item exists COLUMN
803
804 Returns true if the column/field/key COLUMN exists.
805
806 =cut
807
808 sub exists {
809   my($self,$field) = @_;
810   exists($self->{Hash}->{$field});
811 }
812
813 =item AUTLOADED METHODS
814
815 $record->column is a synonym for $record->get('column');
816
817 $record->column('value') is a synonym for $record->set('column','value');
818
819 =cut
820
821 # readable/safe
822 sub AUTOLOAD {
823   my($self,$value)=@_;
824   my($field)=$AUTOLOAD;
825   $field =~ s/.*://;
826   if ( defined($value) ) {
827     confess "errant AUTOLOAD $field for $self (arg $value)"
828       unless blessed($self) && $self->can('setfield');
829     $self->setfield($field,$value);
830   } else {
831     confess "errant AUTOLOAD $field for $self (no args)"
832       unless blessed($self) && $self->can('getfield');
833     $self->getfield($field);
834   }    
835 }
836
837 # efficient
838 #sub AUTOLOAD {
839 #  my $field = $AUTOLOAD;
840 #  $field =~ s/.*://;
841 #  if ( defined($_[1]) ) {
842 #    $_[0]->setfield($field, $_[1]);
843 #  } else {
844 #    $_[0]->getfield($field);
845 #  }    
846 #}
847
848 =item hash
849
850 Returns a list of the column/value pairs, usually for assigning to a new hash.
851
852 To make a distinct duplicate of an FS::Record object, you can do:
853
854     $new = new FS::Record ( $old->table, { $old->hash } );
855
856 =cut
857
858 sub hash {
859   my($self) = @_;
860   confess $self. ' -> hash: Hash attribute is undefined'
861     unless defined($self->{'Hash'});
862   %{ $self->{'Hash'} }; 
863 }
864
865 =item hashref
866
867 Returns a reference to the column/value hash.  This may be deprecated in the
868 future; if there's a reason you can't just use the autoloaded or get/set
869 methods, speak up.
870
871 =cut
872
873 sub hashref {
874   my($self) = @_;
875   $self->{'Hash'};
876 }
877
878 =item modified
879
880 Returns true if any of this object's values have been modified with set (or via
881 an autoloaded method).  Doesn't yet recognize when you retreive a hashref and
882 modify that.
883
884 =cut
885
886 sub modified {
887   my $self = shift;
888   $self->{'modified'};
889 }
890
891 =item select_for_update
892
893 Selects this record with the SQL "FOR UPDATE" command.  This can be useful as
894 a mutex.
895
896 =cut
897
898 sub select_for_update {
899   my $self = shift;
900   my $primary_key = $self->primary_key;
901   qsearchs( {
902     'select'    => '*',
903     'table'     => $self->table,
904     'hashref'   => { $primary_key => $self->$primary_key() },
905     'extra_sql' => 'FOR UPDATE',
906   } );
907 }
908
909 =item lock_table
910
911 Locks this table with a database-driver specific lock method.  This is used
912 as a mutex in order to do a duplicate search.
913
914 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
915
916 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
917
918 Errors are fatal; no useful return value.
919
920 Note: To use this method for new tables other than svc_acct and svc_phone,
921 edit freeside-upgrade and add those tables to the duplicate_lock list.
922
923 =cut
924
925 sub lock_table {
926   my $self = shift;
927   my $table = $self->table;
928
929   warn "$me locking $table table\n" if $DEBUG;
930
931   if ( driver_name =~ /^Pg/i ) {
932
933     dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
934       or die dbh->errstr;
935
936   } elsif ( driver_name =~ /^mysql/i ) {
937
938     dbh->do("SELECT * FROM duplicate_lock
939                WHERE lockname = '$table'
940                FOR UPDATE"
941            ) or die dbh->errstr;
942
943   } else {
944
945     die "unknown database ". driver_name. "; don't know how to lock table";
946
947   }
948
949   warn "$me acquired $table table lock\n" if $DEBUG;
950
951 }
952
953 =item insert
954
955 Inserts this record to the database.  If there is an error, returns the error,
956 otherwise returns false.
957
958 =cut
959
960 sub insert {
961   my $self = shift;
962   my $saved = {};
963
964   warn "$self -> insert" if $DEBUG;
965
966   my $error = $self->check;
967   return $error if $error;
968
969   #single-field unique keys are given a value if false
970   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
971   foreach ( $self->dbdef_table->unique_singles) {
972     $self->unique($_) unless $self->getfield($_);
973   }
974
975   #and also the primary key, if the database isn't going to
976   my $primary_key = $self->dbdef_table->primary_key;
977   my $db_seq = 0;
978   if ( $primary_key ) {
979     my $col = $self->dbdef_table->column($primary_key);
980
981     $db_seq =
982       uc($col->type) =~ /^(BIG)?SERIAL\d?/
983       || ( driver_name eq 'Pg'
984              && defined($col->default)
985              && $col->quoted_default =~ /^nextval\(/i
986          )
987       || ( driver_name eq 'mysql'
988              && defined($col->local)
989              && $col->local =~ /AUTO_INCREMENT/i
990          );
991     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
992   }
993
994   my $table = $self->table;
995   
996   # Encrypt before the database
997   if (    defined(eval '@FS::'. $table . '::encrypted_fields')
998        && scalar( eval '@FS::'. $table . '::encrypted_fields')
999        && $conf->exists('encryption')
1000   ) {
1001     foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1002       $self->{'saved'} = $self->getfield($field);
1003       $self->setfield($field, $self->encrypt($self->getfield($field)));
1004     }
1005   }
1006
1007   #false laziness w/delete
1008   my @real_fields =
1009     grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1010     real_fields($table)
1011   ;
1012   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1013   #eslaf
1014
1015   my $statement = "INSERT INTO $table ";
1016   if ( @real_fields ) {
1017     $statement .=
1018       "( ".
1019         join( ', ', @real_fields ).
1020       ") VALUES (".
1021         join( ', ', @values ).
1022        ")"
1023     ;
1024   } else {
1025     $statement .= 'DEFAULT VALUES';
1026   }
1027   warn "[debug]$me $statement\n" if $DEBUG > 1;
1028   my $sth = dbh->prepare($statement) or return dbh->errstr;
1029
1030   local $SIG{HUP} = 'IGNORE';
1031   local $SIG{INT} = 'IGNORE';
1032   local $SIG{QUIT} = 'IGNORE'; 
1033   local $SIG{TERM} = 'IGNORE';
1034   local $SIG{TSTP} = 'IGNORE';
1035   local $SIG{PIPE} = 'IGNORE';
1036
1037   $sth->execute or return $sth->errstr;
1038
1039   # get inserted id from the database, if applicable & needed
1040   if ( $db_seq && ! $self->getfield($primary_key) ) {
1041     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1042   
1043     my $insertid = '';
1044
1045     if ( driver_name eq 'Pg' ) {
1046
1047       #my $oid = $sth->{'pg_oid_status'};
1048       #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1049
1050       my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1051       unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1052         dbh->rollback if $FS::UID::AutoCommit;
1053         return "can't parse $table.$primary_key default value".
1054                " for sequence name: $default";
1055       }
1056       my $sequence = $1;
1057
1058       my $i_sql = "SELECT currval('$sequence')";
1059       my $i_sth = dbh->prepare($i_sql) or do {
1060         dbh->rollback if $FS::UID::AutoCommit;
1061         return dbh->errstr;
1062       };
1063       $i_sth->execute() or do { #$i_sth->execute($oid)
1064         dbh->rollback if $FS::UID::AutoCommit;
1065         return $i_sth->errstr;
1066       };
1067       $insertid = $i_sth->fetchrow_arrayref->[0];
1068
1069     } elsif ( driver_name eq 'mysql' ) {
1070
1071       $insertid = dbh->{'mysql_insertid'};
1072       # work around mysql_insertid being null some of the time, ala RT :/
1073       unless ( $insertid ) {
1074         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1075              "using SELECT LAST_INSERT_ID();";
1076         my $i_sql = "SELECT LAST_INSERT_ID()";
1077         my $i_sth = dbh->prepare($i_sql) or do {
1078           dbh->rollback if $FS::UID::AutoCommit;
1079           return dbh->errstr;
1080         };
1081         $i_sth->execute or do {
1082           dbh->rollback if $FS::UID::AutoCommit;
1083           return $i_sth->errstr;
1084         };
1085         $insertid = $i_sth->fetchrow_arrayref->[0];
1086       }
1087
1088     } else {
1089
1090       dbh->rollback if $FS::UID::AutoCommit;
1091       return "don't know how to retreive inserted ids from ". driver_name. 
1092              ", try using counterfiles (maybe run dbdef-create?)";
1093
1094     }
1095
1096     $self->setfield($primary_key, $insertid);
1097
1098   }
1099
1100   my @virtual_fields = 
1101       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1102           $self->virtual_fields;
1103   if (@virtual_fields) {
1104     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
1105
1106     my $vfieldpart = $self->vfieldpart_hashref;
1107
1108     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1109                     "VALUES (?, ?, ?)";
1110
1111     my $v_sth = dbh->prepare($v_statement) or do {
1112       dbh->rollback if $FS::UID::AutoCommit;
1113       return dbh->errstr;
1114     };
1115
1116     foreach (keys(%v_values)) {
1117       $v_sth->execute($self->getfield($primary_key),
1118                       $vfieldpart->{$_},
1119                       $v_values{$_})
1120       or do {
1121         dbh->rollback if $FS::UID::AutoCommit;
1122         return $v_sth->errstr;
1123       };
1124     }
1125   }
1126
1127
1128   my $h_sth;
1129   if ( defined dbdef->table('h_'. $table) ) {
1130     my $h_statement = $self->_h_statement('insert');
1131     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1132     $h_sth = dbh->prepare($h_statement) or do {
1133       dbh->rollback if $FS::UID::AutoCommit;
1134       return dbh->errstr;
1135     };
1136   } else {
1137     $h_sth = '';
1138   }
1139   $h_sth->execute or return $h_sth->errstr if $h_sth;
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     $self->setfield($field, $saved->{$field});
1147   }
1148
1149   '';
1150 }
1151
1152 =item add
1153
1154 Depriciated (use insert instead).
1155
1156 =cut
1157
1158 sub add {
1159   cluck "warning: FS::Record::add deprecated!";
1160   insert @_; #call method in this scope
1161 }
1162
1163 =item delete
1164
1165 Delete this record from the database.  If there is an error, returns the error,
1166 otherwise returns false.
1167
1168 =cut
1169
1170 sub delete {
1171   my $self = shift;
1172
1173   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1174     map {
1175       $self->getfield($_) eq ''
1176         #? "( $_ IS NULL OR $_ = \"\" )"
1177         ? ( driver_name eq 'Pg'
1178               ? "$_ IS NULL"
1179               : "( $_ IS NULL OR $_ = \"\" )"
1180           )
1181         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1182     } ( $self->dbdef_table->primary_key )
1183           ? ( $self->dbdef_table->primary_key)
1184           : real_fields($self->table)
1185   );
1186   warn "[debug]$me $statement\n" if $DEBUG > 1;
1187   my $sth = dbh->prepare($statement) or return dbh->errstr;
1188
1189   my $h_sth;
1190   if ( defined dbdef->table('h_'. $self->table) ) {
1191     my $h_statement = $self->_h_statement('delete');
1192     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1193     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1194   } else {
1195     $h_sth = '';
1196   }
1197
1198   my $primary_key = $self->dbdef_table->primary_key;
1199   my $v_sth;
1200   my @del_vfields;
1201   my $vfp = $self->vfieldpart_hashref;
1202   foreach($self->virtual_fields) {
1203     next if $self->getfield($_) eq '';
1204     unless(@del_vfields) {
1205       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1206       $v_sth = dbh->prepare($st) or return dbh->errstr;
1207     }
1208     push @del_vfields, $_;
1209   }
1210
1211   local $SIG{HUP} = 'IGNORE';
1212   local $SIG{INT} = 'IGNORE';
1213   local $SIG{QUIT} = 'IGNORE'; 
1214   local $SIG{TERM} = 'IGNORE';
1215   local $SIG{TSTP} = 'IGNORE';
1216   local $SIG{PIPE} = 'IGNORE';
1217
1218   my $rc = $sth->execute or return $sth->errstr;
1219   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1220   $h_sth->execute or return $h_sth->errstr if $h_sth;
1221   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
1222     or return $v_sth->errstr 
1223         foreach (@del_vfields);
1224   
1225   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1226
1227   #no need to needlessly destoy the data either (causes problems actually)
1228   #undef $self; #no need to keep object!
1229
1230   '';
1231 }
1232
1233 =item del
1234
1235 Depriciated (use delete instead).
1236
1237 =cut
1238
1239 sub del {
1240   cluck "warning: FS::Record::del deprecated!";
1241   &delete(@_); #call method in this scope
1242 }
1243
1244 =item replace OLD_RECORD
1245
1246 Replace the OLD_RECORD with this one in the database.  If there is an error,
1247 returns the error, otherwise returns false.
1248
1249 =cut
1250
1251 sub replace {
1252   my ($new, $old) = (shift, shift);
1253
1254   $old = $new->replace_old unless defined($old);
1255
1256   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1257
1258   if ( $new->can('replace_check') ) {
1259     my $error = $new->replace_check($old);
1260     return $error if $error;
1261   }
1262
1263   return "Records not in same table!" unless $new->table eq $old->table;
1264
1265   my $primary_key = $old->dbdef_table->primary_key;
1266   return "Can't change primary key $primary_key ".
1267          'from '. $old->getfield($primary_key).
1268          ' to ' . $new->getfield($primary_key)
1269     if $primary_key
1270        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1271
1272   my $error = $new->check;
1273   return $error if $error;
1274   
1275   # Encrypt for replace
1276   my $saved = {};
1277   if (    $conf->exists('encryption')
1278        && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1279        && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1280   ) {
1281     foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1282       $saved->{$field} = $new->getfield($field);
1283       $new->setfield($field, $new->encrypt($new->getfield($field)));
1284     }
1285   }
1286
1287   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1288   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1289                    ? ($_, $new->getfield($_)) : () } $old->fields;
1290                    
1291   unless (keys(%diff) || $no_update_diff ) {
1292     carp "[warning]$me $new -> replace $old: records identical"
1293       unless $nowarn_identical;
1294     return '';
1295   }
1296
1297   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1298     map {
1299       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
1300     } real_fields($old->table)
1301   ). ' WHERE '.
1302     join(' AND ',
1303       map {
1304
1305         if ( $old->getfield($_) eq '' ) {
1306
1307          #false laziness w/qsearch
1308          if ( driver_name eq 'Pg' ) {
1309             my $type = $old->dbdef_table->column($_)->type;
1310             if ( $type =~ /(int|(big)?serial)/i ) {
1311               qq-( $_ IS NULL )-;
1312             } else {
1313               qq-( $_ IS NULL OR $_ = '' )-;
1314             }
1315           } else {
1316             qq-( $_ IS NULL OR $_ = "" )-;
1317           }
1318
1319         } else {
1320           "$_ = ". _quote($old->getfield($_),$old->table,$_);
1321         }
1322
1323       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1324     )
1325   ;
1326   warn "[debug]$me $statement\n" if $DEBUG > 1;
1327   my $sth = dbh->prepare($statement) or return dbh->errstr;
1328
1329   my $h_old_sth;
1330   if ( defined dbdef->table('h_'. $old->table) ) {
1331     my $h_old_statement = $old->_h_statement('replace_old');
1332     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1333     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1334   } else {
1335     $h_old_sth = '';
1336   }
1337
1338   my $h_new_sth;
1339   if ( defined dbdef->table('h_'. $new->table) ) {
1340     my $h_new_statement = $new->_h_statement('replace_new');
1341     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1342     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1343   } else {
1344     $h_new_sth = '';
1345   }
1346
1347   # For virtual fields we have three cases with different SQL 
1348   # statements: add, replace, delete
1349   my $v_add_sth;
1350   my $v_rep_sth;
1351   my $v_del_sth;
1352   my (@add_vfields, @rep_vfields, @del_vfields);
1353   my $vfp = $old->vfieldpart_hashref;
1354   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1355     if($diff{$_} eq '') {
1356       # Delete
1357       unless(@del_vfields) {
1358         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1359                  "AND vfieldpart = ?";
1360         warn "[debug]$me $st\n" if $DEBUG > 2;
1361         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1362       }
1363       push @del_vfields, $_;
1364     } elsif($old->getfield($_) eq '') {
1365       # Add
1366       unless(@add_vfields) {
1367         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1368                  "VALUES (?, ?, ?)";
1369         warn "[debug]$me $st\n" if $DEBUG > 2;
1370         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1371       }
1372       push @add_vfields, $_;
1373     } else {
1374       # Replace
1375       unless(@rep_vfields) {
1376         my $st = "UPDATE virtual_field SET value = ? ".
1377                  "WHERE recnum = ? AND vfieldpart = ?";
1378         warn "[debug]$me $st\n" if $DEBUG > 2;
1379         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1380       }
1381       push @rep_vfields, $_;
1382     }
1383   }
1384
1385   local $SIG{HUP} = 'IGNORE';
1386   local $SIG{INT} = 'IGNORE';
1387   local $SIG{QUIT} = 'IGNORE'; 
1388   local $SIG{TERM} = 'IGNORE';
1389   local $SIG{TSTP} = 'IGNORE';
1390   local $SIG{PIPE} = 'IGNORE';
1391
1392   my $rc = $sth->execute or return $sth->errstr;
1393   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1394   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1395   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1396
1397   $v_del_sth->execute($old->getfield($primary_key),
1398                       $vfp->{$_})
1399         or return $v_del_sth->errstr
1400       foreach(@del_vfields);
1401
1402   $v_add_sth->execute($new->getfield($_),
1403                       $old->getfield($primary_key),
1404                       $vfp->{$_})
1405         or return $v_add_sth->errstr
1406       foreach(@add_vfields);
1407
1408   $v_rep_sth->execute($new->getfield($_),
1409                       $old->getfield($primary_key),
1410                       $vfp->{$_})
1411         or return $v_rep_sth->errstr
1412       foreach(@rep_vfields);
1413
1414   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1415
1416   # Now that it has been saved, reset the encrypted fields so that $new 
1417   # can still be used.
1418   foreach my $field (keys %{$saved}) {
1419     $new->setfield($field, $saved->{$field});
1420   }
1421
1422   '';
1423
1424 }
1425
1426 sub replace_old {
1427   my( $self ) = shift;
1428   warn "[$me] replace called with no arguments; autoloading old record\n"
1429     if $DEBUG;
1430
1431   my $primary_key = $self->dbdef_table->primary_key;
1432   if ( $primary_key ) {
1433     $self->by_key( $self->$primary_key() ) #this is what's returned
1434       or croak "can't find ". $self->table. ".$primary_key ".
1435         $self->$primary_key();
1436   } else {
1437     croak $self->table. " has no primary key; pass old record as argument";
1438   }
1439
1440 }
1441
1442 =item rep
1443
1444 Depriciated (use replace instead).
1445
1446 =cut
1447
1448 sub rep {
1449   cluck "warning: FS::Record::rep deprecated!";
1450   replace @_; #call method in this scope
1451 }
1452
1453 =item check
1454
1455 Checks virtual fields (using check_blocks).  Subclasses should still provide 
1456 a check method to validate real fields, foreign keys, etc., and call this 
1457 method via $self->SUPER::check.
1458
1459 (FIXME: Should this method try to make sure that it I<is> being called from 
1460 a subclass's check method, to keep the current semantics as far as possible?)
1461
1462 =cut
1463
1464 sub check {
1465   #confess "FS::Record::check not implemented; supply one in subclass!";
1466   my $self = shift;
1467
1468   foreach my $field ($self->virtual_fields) {
1469     for ($self->getfield($field)) {
1470       # See notes on check_block in FS::part_virtual_field.
1471       eval $self->pvf($field)->check_block;
1472       if ( $@ ) {
1473         #this is bad, probably want to follow the stack backtrace up and see
1474         #wtf happened
1475         my $err = "Fatal error checking $field for $self";
1476         cluck "$err: $@";
1477         return "$err (see log for backtrace): $@";
1478
1479       }
1480       $self->setfield($field, $_);
1481     }
1482   }
1483   '';
1484 }
1485
1486 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1487
1488 Processes a batch import as a queued JSRPC job
1489
1490 JOB is an FS::queue entry.
1491
1492 OPTIONS_HASHREF can have the following keys:
1493
1494 =over 4
1495
1496 =item table
1497
1498 Table name (required).
1499
1500 =item params
1501
1502 Listref of field names for static fields.  They will be given values from the
1503 PARAMS hashref and passed as a "params" hashref to batch_import.
1504
1505 =item formats
1506
1507 Formats hashref.  Keys are field names, values are listrefs that define the
1508 format.
1509
1510 Each listref value can be a column name or a code reference.  Coderefs are run
1511 with the row object, data and a FS::Conf object as the three parameters.
1512 For example, this coderef does the same thing as using the "columnname" string:
1513
1514   sub {
1515     my( $record, $data, $conf ) = @_;
1516     $record->columnname( $data );
1517   },
1518
1519 Coderefs are run after all "column name" fields are assigned.
1520
1521 =item format_types
1522
1523 Optional format hashref of types.  Keys are field names, values are "csv",
1524 "xls" or "fixedlength".  Overrides automatic determination of file type
1525 from extension.
1526
1527 =item format_headers
1528
1529 Optional format hashref of header lines.  Keys are field names, values are 0
1530 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1531 number of lines.
1532
1533 =item format_sep_chars
1534
1535 Optional format hashref of CSV sep_chars.  Keys are field names, values are the
1536 CSV separation character.
1537
1538 =item format_fixedlenth_formats
1539
1540 Optional format hashref of fixed length format defintiions.  Keys are field
1541 names, values Parse::FixedLength listrefs of field definitions.
1542
1543 =item default_csv
1544
1545 Set true to default to CSV file type if the filename does not contain a
1546 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1547 format_types).
1548
1549 =back
1550
1551 PARAMS is a base64-encoded Storable string containing the POSTed data as
1552 a hash ref.  It normally contains at least one field, "uploaded files",
1553 generated by /elements/file-upload.html and containing the list of uploaded
1554 files.  Currently only supports a single file named "file".
1555
1556 =cut
1557
1558 use Storable qw(thaw);
1559 use Data::Dumper;
1560 use MIME::Base64;
1561 sub process_batch_import {
1562   my($job, $opt) = ( shift, shift );
1563
1564   my $table = $opt->{table};
1565   my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1566   my %formats = %{ $opt->{formats} };
1567
1568   my $param = thaw(decode_base64(shift));
1569   warn Dumper($param) if $DEBUG;
1570   
1571   my $files = $param->{'uploaded_files'}
1572     or die "No files provided.\n";
1573
1574   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1575
1576   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1577   my $file = $dir. $files{'file'};
1578
1579   my %iopt = (
1580     #class-static
1581     table                      => $table,
1582     formats                    => \%formats,
1583     format_types               => $opt->{format_types},
1584     format_headers             => $opt->{format_headers},
1585     format_sep_chars           => $opt->{format_sep_chars},
1586     format_fixedlength_formats => $opt->{format_fixedlength_formats},
1587     format_xml_formats         => $opt->{format_xml_formats},
1588     format_row_callbacks       => $opt->{format_row_callbacks},
1589     #per-import
1590     job                        => $job,
1591     file                       => $file,
1592     #type                       => $type,
1593     format                     => $param->{format},
1594     params                     => { map { $_ => $param->{$_} } @pass_params },
1595     #?
1596     default_csv                => $opt->{default_csv},
1597     postinsert_callback        => $opt->{postinsert_callback},
1598   );
1599
1600   if ( $opt->{'batch_namecol'} ) {
1601     $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1602     $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1603   }
1604
1605   my $error = FS::Record::batch_import( \%iopt );
1606
1607   unlink $file;
1608
1609   die "$error\n" if $error;
1610 }
1611
1612 =item batch_import PARAM_HASHREF
1613
1614 Class method for batch imports.  Available params:
1615
1616 =over 4
1617
1618 =item table
1619
1620 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1621
1622 =item formats
1623
1624 =item format_types
1625
1626 =item format_headers
1627
1628 =item format_sep_chars
1629
1630 =item format_fixedlength_formats
1631
1632 =item format_row_callbacks
1633
1634 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1635
1636 =item postinsert_callback
1637
1638 =item params
1639
1640 =item job
1641
1642 FS::queue object, will be updated with progress
1643
1644 =item file
1645
1646 =item type
1647
1648 csv, xls, fixedlength, xml
1649
1650 =item empty_ok
1651
1652 =back
1653
1654 =cut
1655
1656 sub batch_import {
1657   my $param = shift;
1658
1659   warn "$me batch_import call with params: \n". Dumper($param)
1660     if $DEBUG;
1661
1662   my $table   = $param->{table};
1663
1664   my $job     = $param->{job};
1665   my $file    = $param->{file};
1666   my $params  = $param->{params} || {};
1667
1668   my( $type, $header, $sep_char, $fixedlength_format, 
1669       $xml_format, $row_callback, @fields );
1670   my $postinsert_callback = '';
1671   $postinsert_callback = $param->{'postinsert_callback'}
1672           if $param->{'postinsert_callback'};
1673   if ( $param->{'format'} ) {
1674
1675     my $format  = $param->{'format'};
1676     my $formats = $param->{formats};
1677     die "unknown format $format" unless exists $formats->{ $format };
1678
1679     $type = $param->{'format_types'}
1680             ? $param->{'format_types'}{ $format }
1681             : $param->{type} || 'csv';
1682
1683
1684     $header = $param->{'format_headers'}
1685                ? $param->{'format_headers'}{ $param->{'format'} }
1686                : 0;
1687
1688     $sep_char = $param->{'format_sep_chars'}
1689                   ? $param->{'format_sep_chars'}{ $param->{'format'} }
1690                   : ',';
1691
1692     $fixedlength_format =
1693       $param->{'format_fixedlength_formats'}
1694         ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1695         : '';
1696
1697     $xml_format =
1698       $param->{'format_xml_formats'}
1699         ? $param->{'format_xml_formats'}{ $param->{'format'} }
1700         : '';
1701
1702     $row_callback =
1703       $param->{'format_row_callbacks'}
1704         ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1705         : '';
1706
1707     @fields = @{ $formats->{ $format } };
1708
1709   } elsif ( $param->{'fields'} ) {
1710
1711     $type = ''; #infer from filename
1712     $header = 0;
1713     $sep_char = ',';
1714     $fixedlength_format = '';
1715     $row_callback = '';
1716     @fields = @{ $param->{'fields'} };
1717
1718   } else {
1719     die "neither format nor fields specified";
1720   }
1721
1722   #my $file    = $param->{file};
1723
1724   unless ( $type ) {
1725     if ( $file =~ /\.(\w+)$/i ) {
1726       $type = lc($1);
1727     } else {
1728       #or error out???
1729       warn "can't parse file type from filename $file; defaulting to CSV";
1730       $type = 'csv';
1731     }
1732     $type = 'csv'
1733       if $param->{'default_csv'} && $type ne 'xls';
1734   }
1735
1736
1737   my $row = 0;
1738   my $count;
1739   my $parser;
1740   my @buffer = ();
1741   if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1742
1743     if ( $type eq 'csv' ) {
1744
1745       my %attr = ();
1746       $attr{sep_char} = $sep_char if $sep_char;
1747       $parser = new Text::CSV_XS \%attr;
1748
1749     } elsif ( $type eq 'fixedlength' ) {
1750
1751       eval "use Parse::FixedLength;";
1752       die $@ if $@;
1753       $parser = Parse::FixedLength->new($fixedlength_format);
1754
1755     }
1756     else {
1757       die "Unknown file type $type\n";
1758     }
1759
1760     @buffer = split(/\r?\n/, slurp($file) );
1761     splice(@buffer, 0, ($header || 0) );
1762     $count = scalar(@buffer);
1763
1764   } elsif ( $type eq 'xls' ) {
1765
1766     eval "use Spreadsheet::ParseExcel;";
1767     die $@ if $@;
1768
1769     eval "use DateTime::Format::Excel;";
1770     #for now, just let the error be thrown if it is used, since only CDR
1771     # formats bill_west and troop use it, not other excel-parsing things
1772     #die $@ if $@;
1773
1774     my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1775
1776     $parser = $excel->{Worksheet}[0]; #first sheet
1777
1778     $count = $parser->{MaxRow} || $parser->{MinRow};
1779     $count++;
1780
1781     $row = $header || 0;
1782   } elsif ( $type eq 'xml' ) {
1783     # FS::pay_batch
1784     eval "use XML::Simple;";
1785     die $@ if $@;
1786     my $xmlrow = $xml_format->{'xmlrow'};
1787     $parser = $xml_format->{'xmlkeys'};
1788     die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1789     my $data = XML::Simple::XMLin(
1790       $file,
1791       'SuppressEmpty' => '', #sets empty values to ''
1792       'KeepRoot'      => 1,
1793     );
1794     my $rows = $data;
1795     $rows = $rows->{$_} foreach @$xmlrow;
1796     $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1797     $count = @buffer = @$rows;
1798   } else {
1799     die "Unknown file type $type\n";
1800   }
1801
1802   #my $columns;
1803
1804   local $SIG{HUP} = 'IGNORE';
1805   local $SIG{INT} = 'IGNORE';
1806   local $SIG{QUIT} = 'IGNORE';
1807   local $SIG{TERM} = 'IGNORE';
1808   local $SIG{TSTP} = 'IGNORE';
1809   local $SIG{PIPE} = 'IGNORE';
1810
1811   my $oldAutoCommit = $FS::UID::AutoCommit;
1812   local $FS::UID::AutoCommit = 0;
1813   my $dbh = dbh;
1814
1815   #my $params  = $param->{params} || {};
1816   if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1817     my $batch_col   = $param->{'batch_keycol'};
1818
1819     my $batch_class = 'FS::'. $param->{'batch_table'};
1820     my $batch = $batch_class->new({
1821       $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1822     });
1823     my $error = $batch->insert;
1824     if ( $error ) {
1825       $dbh->rollback if $oldAutoCommit;
1826       return "can't insert batch record: $error";
1827     }
1828     #primary key via dbdef? (so the column names don't have to match)
1829     my $batch_value = $batch->get( $param->{'batch_keycol'} );
1830
1831     $params->{ $batch_col } = $batch_value;
1832   }
1833
1834   #my $job     = $param->{job};
1835   my $line;
1836   my $imported = 0;
1837   my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1838   while (1) {
1839
1840     my @columns = ();
1841     if ( $type eq 'csv' ) {
1842
1843       last unless scalar(@buffer);
1844       $line = shift(@buffer);
1845
1846       next if $line =~ /^\s*$/; #skip empty lines
1847
1848       $line = &{$row_callback}($line) if $row_callback;
1849
1850       $parser->parse($line) or do {
1851         $dbh->rollback if $oldAutoCommit;
1852         return "can't parse: ". $parser->error_input();
1853       };
1854       @columns = $parser->fields();
1855
1856     } elsif ( $type eq 'fixedlength' ) {
1857
1858       last unless scalar(@buffer);
1859       $line = shift(@buffer);
1860
1861       @columns = $parser->parse($line);
1862
1863     } elsif ( $type eq 'xls' ) {
1864
1865       last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1866            || ! $parser->{Cells}[$row];
1867
1868       my @row = @{ $parser->{Cells}[$row] };
1869       @columns = map $_->{Val}, @row;
1870
1871       #my $z = 'A';
1872       #warn $z++. ": $_\n" for @columns;
1873
1874     } elsif ( $type eq 'xml' ) {
1875       # $parser = [ 'Column0Key', 'Column1Key' ... ]
1876       last unless scalar(@buffer);
1877       my $row = shift @buffer;
1878       @columns = @{ $row }{ @$parser };
1879     } else {
1880       die "Unknown file type $type\n";
1881     }
1882
1883     my @later = ();
1884     my %hash = %$params;
1885
1886     foreach my $field ( @fields ) {
1887
1888       my $value = shift @columns;
1889      
1890       if ( ref($field) eq 'CODE' ) {
1891         #&{$field}(\%hash, $value);
1892         push @later, $field, $value;
1893       } else {
1894         #??? $hash{$field} = $value if length($value);
1895         $hash{$field} = $value if defined($value) && length($value);
1896       }
1897
1898     }
1899
1900     #my $table   = $param->{table};
1901     my $class = "FS::$table";
1902
1903     my $record = $class->new( \%hash );
1904
1905     my $param = {};
1906     while ( scalar(@later) ) {
1907       my $sub = shift @later;
1908       my $data = shift @later;
1909       eval {
1910         &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
1911       };
1912       if ( $@ ) {
1913         $dbh->rollback if $oldAutoCommit;
1914         return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
1915       }
1916       last if exists( $param->{skiprow} );
1917     }
1918     next if exists( $param->{skiprow} );
1919
1920     my $error = $record->insert;
1921
1922     if ( $error ) {
1923       $dbh->rollback if $oldAutoCommit;
1924       return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1925     }
1926
1927     $row++;
1928     $imported++;
1929
1930     if ( $postinsert_callback ) {
1931       my $error = &{$postinsert_callback}($record, $param);
1932       if ( $error ) {
1933         $dbh->rollback if $oldAutoCommit;
1934         return "postinsert_callback error". ( $line ? " for $line" : '' ).
1935                ": $error";
1936       }
1937     }
1938
1939     if ( $job && time - $min_sec > $last ) { #progress bar
1940       $job->update_statustext( int(100 * $imported / $count) );
1941       $last = time;
1942     }
1943
1944   }
1945
1946   unless ( $imported || $param->{empty_ok} ) {
1947     $dbh->rollback if $oldAutoCommit;
1948     return "Empty file!";
1949   }
1950
1951   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1952
1953   ''; #no error
1954
1955 }
1956
1957 sub _h_statement {
1958   my( $self, $action, $time ) = @_;
1959
1960   $time ||= time;
1961
1962   my %nohistory = map { $_=>1 } $self->nohistory_fields;
1963
1964   my @fields =
1965     grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1966     real_fields($self->table);
1967   ;
1968
1969   # If we're encrypting then don't store the payinfo in the history
1970   if ( $conf && $conf->exists('encryption') ) {
1971     @fields = grep { $_ ne 'payinfo' } @fields;
1972   }
1973
1974   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1975
1976   "INSERT INTO h_". $self->table. " ( ".
1977       join(', ', qw(history_date history_user history_action), @fields ).
1978     ") VALUES (".
1979       join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1980     ")"
1981   ;
1982 }
1983
1984 =item unique COLUMN
1985
1986 B<Warning>: External use is B<deprecated>.  
1987
1988 Replaces COLUMN in record with a unique number, using counters in the
1989 filesystem.  Used by the B<insert> method on single-field unique columns
1990 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1991 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1992
1993 Returns the new value.
1994
1995 =cut
1996
1997 sub unique {
1998   my($self,$field) = @_;
1999   my($table)=$self->table;
2000
2001   croak "Unique called on field $field, but it is ",
2002         $self->getfield($field),
2003         ", not null!"
2004     if $self->getfield($field);
2005
2006   #warn "table $table is tainted" if is_tainted($table);
2007   #warn "field $field is tainted" if is_tainted($field);
2008
2009   my($counter) = new File::CounterFile "$table.$field",0;
2010 # hack for web demo
2011 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2012 #  my($user)=$1;
2013 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
2014 # endhack
2015
2016   my $index = $counter->inc;
2017   $index = $counter->inc while qsearchs($table, { $field=>$index } );
2018
2019   $index =~ /^(\d*)$/;
2020   $index=$1;
2021
2022   $self->setfield($field,$index);
2023
2024 }
2025
2026 =item ut_float COLUMN
2027
2028 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
2029 null.  If there is an error, returns the error, otherwise returns false.
2030
2031 =cut
2032
2033 sub ut_float {
2034   my($self,$field)=@_ ;
2035   ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2036    $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2037    $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2038    $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2039     or return "Illegal or empty (float) $field: ". $self->getfield($field);
2040   $self->setfield($field,$1);
2041   '';
2042 }
2043 =item ut_floatn COLUMN
2044
2045 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May be
2046 null.  If there is an error, returns the error, otherwise returns false.
2047
2048 =cut
2049
2050 #false laziness w/ut_ipn
2051 sub ut_floatn {
2052   my( $self, $field ) = @_;
2053   if ( $self->getfield($field) =~ /^()$/ ) {
2054     $self->setfield($field,'');
2055     '';
2056   } else {
2057     $self->ut_float($field);
2058   }
2059 }
2060
2061 =item ut_sfloat COLUMN
2062
2063 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2064 May not be null.  If there is an error, returns the error, otherwise returns
2065 false.
2066
2067 =cut
2068
2069 sub ut_sfloat {
2070   my($self,$field)=@_ ;
2071   ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2072    $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2073    $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2074    $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2075     or return "Illegal or empty (float) $field: ". $self->getfield($field);
2076   $self->setfield($field,$1);
2077   '';
2078 }
2079 =item ut_sfloatn COLUMN
2080
2081 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May be
2082 null.  If there is an error, returns the error, otherwise returns false.
2083
2084 =cut
2085
2086 sub ut_sfloatn {
2087   my( $self, $field ) = @_;
2088   if ( $self->getfield($field) =~ /^()$/ ) {
2089     $self->setfield($field,'');
2090     '';
2091   } else {
2092     $self->ut_sfloat($field);
2093   }
2094 }
2095
2096 =item ut_snumber COLUMN
2097
2098 Check/untaint signed numeric data (whole numbers).  If there is an error,
2099 returns the error, otherwise returns false.
2100
2101 =cut
2102
2103 sub ut_snumber {
2104   my($self, $field) = @_;
2105   $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2106     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2107   $self->setfield($field, "$1$2");
2108   '';
2109 }
2110
2111 =item ut_snumbern COLUMN
2112
2113 Check/untaint signed numeric data (whole numbers).  If there is an error,
2114 returns the error, otherwise returns false.
2115
2116 =cut
2117
2118 sub ut_snumbern {
2119   my($self, $field) = @_;
2120   $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2121     or return "Illegal (numeric) $field: ". $self->getfield($field);
2122   if ($1) {
2123     return "Illegal (numeric) $field: ". $self->getfield($field)
2124       unless $2;
2125   }
2126   $self->setfield($field, "$1$2");
2127   '';
2128 }
2129
2130 =item ut_number COLUMN
2131
2132 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
2133 is an error, returns the error, otherwise returns false.
2134
2135 =cut
2136
2137 sub ut_number {
2138   my($self,$field)=@_;
2139   $self->getfield($field) =~ /^\s*(\d+)\s*$/
2140     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2141   $self->setfield($field,$1);
2142   '';
2143 }
2144
2145 =item ut_numbern COLUMN
2146
2147 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
2148 an error, returns the error, otherwise returns false.
2149
2150 =cut
2151
2152 sub ut_numbern {
2153   my($self,$field)=@_;
2154   $self->getfield($field) =~ /^\s*(\d*)\s*$/
2155     or return "Illegal (numeric) $field: ". $self->getfield($field);
2156   $self->setfield($field,$1);
2157   '';
2158 }
2159
2160 =item ut_money COLUMN
2161
2162 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
2163 is an error, returns the error, otherwise returns false.
2164
2165 =cut
2166
2167 sub ut_money {
2168   my($self,$field)=@_;
2169   $self->setfield($field, 0) if $self->getfield($field) eq '';
2170   $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
2171     or return "Illegal (money) $field: ". $self->getfield($field);
2172   #$self->setfield($field, "$1$2$3" || 0);
2173   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2174   '';
2175 }
2176
2177 =item ut_moneyn COLUMN
2178
2179 Check/untaint monetary numbers.  May be negative.  If there
2180 is an error, returns the error, otherwise returns false.
2181
2182 =cut
2183
2184 sub ut_moneyn {
2185   my($self,$field)=@_;
2186   if ($self->getfield($field) eq '') {
2187     $self->setfield($field, '');
2188     return '';
2189   }
2190   $self->ut_money($field);
2191 }
2192
2193 =item ut_text COLUMN
2194
2195 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
2196 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2197 May not be null.  If there is an error, returns the error, otherwise returns
2198 false.
2199
2200 =cut
2201
2202 sub ut_text {
2203   my($self,$field)=@_;
2204   #warn "msgcat ". \&msgcat. "\n";
2205   #warn "notexist ". \&notexist. "\n";
2206   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2207   $self->getfield($field)
2208     =~ /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
2209       or return gettext('illegal_or_empty_text'). " $field: ".
2210                  $self->getfield($field);
2211   $self->setfield($field,$1);
2212   '';
2213 }
2214
2215 =item ut_textn COLUMN
2216
2217 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
2218 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
2219 May be null.  If there is an error, returns the error, otherwise returns false.
2220
2221 =cut
2222
2223 sub ut_textn {
2224   my($self,$field)=@_;
2225   return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2226   $self->ut_text($field);
2227 }
2228
2229 =item ut_alpha COLUMN
2230
2231 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
2232 an error, returns the error, otherwise returns false.
2233
2234 =cut
2235
2236 sub ut_alpha {
2237   my($self,$field)=@_;
2238   $self->getfield($field) =~ /^(\w+)$/
2239     or return "Illegal or empty (alphanumeric) $field: ".
2240               $self->getfield($field);
2241   $self->setfield($field,$1);
2242   '';
2243 }
2244
2245 =item ut_alphan COLUMN
2246
2247 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
2248 error, returns the error, otherwise returns false.
2249
2250 =cut
2251
2252 sub ut_alphan {
2253   my($self,$field)=@_;
2254   $self->getfield($field) =~ /^(\w*)$/ 
2255     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2256   $self->setfield($field,$1);
2257   '';
2258 }
2259
2260 =item ut_alphasn COLUMN
2261
2262 Check/untaint alphanumeric strings, spaces allowed.  May be null.  If there is
2263 an error, returns the error, otherwise returns false.
2264
2265 =cut
2266
2267 sub ut_alphasn {
2268   my($self,$field)=@_;
2269   $self->getfield($field) =~ /^([\w ]*)$/ 
2270     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2271   $self->setfield($field,$1);
2272   '';
2273 }
2274
2275
2276 =item ut_alpha_lower COLUMN
2277
2278 Check/untaint lowercase alphanumeric strings (no spaces).  May not be null.  If
2279 there is an error, returns the error, otherwise returns false.
2280
2281 =cut
2282
2283 sub ut_alpha_lower {
2284   my($self,$field)=@_;
2285   $self->getfield($field) =~ /[[:upper:]]/
2286     and return "Uppercase characters are not permitted in $field";
2287   $self->ut_alpha($field);
2288 }
2289
2290 =item ut_phonen COLUMN [ COUNTRY ]
2291
2292 Check/untaint phone numbers.  May be null.  If there is an error, returns
2293 the error, otherwise returns false.
2294
2295 Takes an optional two-letter ISO country code; without it or with unsupported
2296 countries, ut_phonen simply calls ut_alphan.
2297
2298 =cut
2299
2300 sub ut_phonen {
2301   my( $self, $field, $country ) = @_;
2302   return $self->ut_alphan($field) unless defined $country;
2303   my $phonen = $self->getfield($field);
2304   if ( $phonen eq '' ) {
2305     $self->setfield($field,'');
2306   } elsif ( $country eq 'US' || $country eq 'CA' ) {
2307     $phonen =~ s/\D//g;
2308     $phonen = $conf->config('cust_main-default_areacode').$phonen
2309       if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2310     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2311       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2312     $phonen = "$1-$2-$3";
2313     $phonen .= " x$4" if $4;
2314     $self->setfield($field,$phonen);
2315   } else {
2316     warn "warning: don't know how to check phone numbers for country $country";
2317     return $self->ut_textn($field);
2318   }
2319   '';
2320 }
2321
2322 =item ut_hex COLUMN
2323
2324 Check/untaint hexadecimal values.
2325
2326 =cut
2327
2328 sub ut_hex {
2329   my($self, $field) = @_;
2330   $self->getfield($field) =~ /^([\da-fA-F]+)$/
2331     or return "Illegal (hex) $field: ". $self->getfield($field);
2332   $self->setfield($field, uc($1));
2333   '';
2334 }
2335
2336 =item ut_hexn COLUMN
2337
2338 Check/untaint hexadecimal values.  May be null.
2339
2340 =cut
2341
2342 sub ut_hexn {
2343   my($self, $field) = @_;
2344   $self->getfield($field) =~ /^([\da-fA-F]*)$/
2345     or return "Illegal (hex) $field: ". $self->getfield($field);
2346   $self->setfield($field, uc($1));
2347   '';
2348 }
2349 =item ut_ip COLUMN
2350
2351 Check/untaint ip addresses.  IPv4 only for now, though ::1 is auto-translated
2352 to 127.0.0.1.
2353
2354 =cut
2355
2356 sub ut_ip {
2357   my( $self, $field ) = @_;
2358   $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2359   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2360     or return "Illegal (IP address) $field: ". $self->getfield($field);
2361   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2362   $self->setfield($field, "$1.$2.$3.$4");
2363   '';
2364 }
2365
2366 =item ut_ipn COLUMN
2367
2368 Check/untaint ip addresses.  IPv4 only for now, though ::1 is auto-translated
2369 to 127.0.0.1.  May be null.
2370
2371 =cut
2372
2373 sub ut_ipn {
2374   my( $self, $field ) = @_;
2375   if ( $self->getfield($field) =~ /^()$/ ) {
2376     $self->setfield($field,'');
2377     '';
2378   } else {
2379     $self->ut_ip($field);
2380   }
2381 }
2382
2383 =item ut_ip46 COLUMN
2384
2385 Check/untaint IPv4 or IPv6 address.
2386
2387 =cut
2388
2389 sub ut_ip46 {
2390   my( $self, $field ) = @_;
2391   my $ip = NetAddr::IP->new($self->getfield($field))
2392     or return "Illegal (IP address) $field: ".$self->getfield($field);
2393   $self->setfield($field, lc($ip->addr));
2394   return '';
2395 }
2396
2397 =item ut_ip46n
2398
2399 Check/untaint IPv6 or IPv6 address.  May be null.
2400
2401 =cut
2402
2403 sub ut_ip46n {
2404   my( $self, $field ) = @_;
2405   if ( $self->getfield($field) =~ /^$/ ) {
2406     $self->setfield($field, '');
2407     return '';
2408   }
2409   $self->ut_ip46($field);
2410 }
2411
2412 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2413
2414 Check/untaint coordinates.
2415 Accepts the following forms:
2416 DDD.DDDDD
2417 -DDD.DDDDD
2418 DDD MM.MMM
2419 -DDD MM.MMM
2420 DDD MM SS
2421 -DDD MM SS
2422 DDD MM MMM
2423 -DDD MM MMM
2424
2425 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2426 The latter form (that is, the MMM are thousands of minutes) is
2427 assumed if the "MMM" is exactly three digits or two digits > 59.
2428
2429 To be safe, just use the DDD.DDDDD form.
2430
2431 If LOWER or UPPER are specified, then the coordinate is checked
2432 for lower and upper bounds, respectively.
2433
2434 =cut
2435
2436 sub ut_coord {
2437
2438   my ($self, $field) = (shift, shift);
2439
2440   my $lower = shift if scalar(@_);
2441   my $upper = shift if scalar(@_);
2442   my $coord = $self->getfield($field);
2443   my $neg = $coord =~ s/^(-)//;
2444
2445   my ($d, $m, $s) = (0, 0, 0);
2446
2447   if (
2448     (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2449     (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2450     (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2451   ) {
2452     $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2453     $m = $m / 60;
2454     if ($m > 59) {
2455       return "Invalid (coordinate with minutes > 59) $field: "
2456              . $self->getfield($field);
2457     }
2458
2459     $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2460
2461     if (defined($lower) and ($coord < $lower)) {
2462       return "Invalid (coordinate < $lower) $field: "
2463              . $self->getfield($field);;
2464     }
2465
2466     if (defined($upper) and ($coord > $upper)) {
2467       return "Invalid (coordinate > $upper) $field: "
2468              . $self->getfield($field);;
2469     }
2470
2471     $self->setfield($field, $coord);
2472     return '';
2473   }
2474
2475   return "Invalid (coordinate) $field: " . $self->getfield($field);
2476
2477 }
2478
2479 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2480
2481 Same as ut_coord, except optionally null.
2482
2483 =cut
2484
2485 sub ut_coordn {
2486
2487   my ($self, $field) = (shift, shift);
2488
2489   if ($self->getfield($field) =~ /^$/) {
2490     return '';
2491   } else {
2492     return $self->ut_coord($field, @_);
2493   }
2494
2495 }
2496
2497
2498 =item ut_domain COLUMN
2499
2500 Check/untaint host and domain names.
2501
2502 =cut
2503
2504 sub ut_domain {
2505   my( $self, $field ) = @_;
2506   #$self->getfield($field) =~/^(\w+\.)*\w+$/
2507   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2508     or return "Illegal (domain) $field: ". $self->getfield($field);
2509   $self->setfield($field,$1);
2510   '';
2511 }
2512
2513 =item ut_name COLUMN
2514
2515 Check/untaint proper names; allows alphanumerics, spaces and the following
2516 punctuation: , . - '
2517
2518 May not be null.
2519
2520 =cut
2521
2522 sub ut_name {
2523   my( $self, $field ) = @_;
2524 #  warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2525   #$self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2526   $self->getfield($field) =~ /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \,\.\-\']+)$/
2527     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2528   $self->setfield($field,$1);
2529   '';
2530 }
2531
2532 =item ut_zip COLUMN
2533
2534 Check/untaint zip codes.
2535
2536 =cut
2537
2538 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2539
2540 sub ut_zip {
2541   my( $self, $field, $country ) = @_;
2542
2543   if ( $country eq 'US' ) {
2544
2545     $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2546       or return gettext('illegal_zip'). " $field for country $country: ".
2547                 $self->getfield($field);
2548     $self->setfield($field, $1);
2549
2550   } elsif ( $country eq 'CA' ) {
2551
2552     $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2553       or return gettext('illegal_zip'). " $field for country $country: ".
2554                 $self->getfield($field);
2555     $self->setfield($field, "$1 $2");
2556
2557   } else {
2558
2559     if ( $self->getfield($field) =~ /^\s*$/
2560          && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2561        )
2562     {
2563       $self->setfield($field,'');
2564     } else {
2565       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2566         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2567       $self->setfield($field,$1);
2568     }
2569
2570   }
2571
2572   '';
2573 }
2574
2575 =item ut_country COLUMN
2576
2577 Check/untaint country codes.  Country names are changed to codes, if possible -
2578 see L<Locale::Country>.
2579
2580 =cut
2581
2582 sub ut_country {
2583   my( $self, $field ) = @_;
2584   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2585     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
2586          && country2code($1) ) {
2587       $self->setfield($field,uc(country2code($1)));
2588     }
2589   }
2590   $self->getfield($field) =~ /^(\w\w)$/
2591     or return "Illegal (country) $field: ". $self->getfield($field);
2592   $self->setfield($field,uc($1));
2593   '';
2594 }
2595
2596 =item ut_anything COLUMN
2597
2598 Untaints arbitrary data.  Be careful.
2599
2600 =cut
2601
2602 sub ut_anything {
2603   my( $self, $field ) = @_;
2604   $self->getfield($field) =~ /^(.*)$/s
2605     or return "Illegal $field: ". $self->getfield($field);
2606   $self->setfield($field,$1);
2607   '';
2608 }
2609
2610 =item ut_enum COLUMN CHOICES_ARRAYREF
2611
2612 Check/untaint a column, supplying all possible choices, like the "enum" type.
2613
2614 =cut
2615
2616 sub ut_enum {
2617   my( $self, $field, $choices ) = @_;
2618   foreach my $choice ( @$choices ) {
2619     if ( $self->getfield($field) eq $choice ) {
2620       $self->setfield($field, $choice);
2621       return '';
2622     }
2623   }
2624   return "Illegal (enum) field $field: ". $self->getfield($field);
2625 }
2626
2627 =item ut_enumn COLUMN CHOICES_ARRAYREF
2628
2629 Like ut_enum, except the null value is also allowed.
2630
2631 =cut
2632
2633 sub ut_enumn {
2634   my( $self, $field, $choices ) = @_;
2635   $self->getfield($field)
2636     ? $self->ut_enum($field, $choices)
2637     : '';
2638 }
2639
2640
2641 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2642
2643 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
2644 on the column first.
2645
2646 =cut
2647
2648 sub ut_foreign_key {
2649   my( $self, $field, $table, $foreign ) = @_;
2650   return '' if $no_check_foreign;
2651   qsearchs($table, { $foreign => $self->getfield($field) })
2652     or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2653               " in $table.$foreign";
2654   '';
2655 }
2656
2657 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2658
2659 Like ut_foreign_key, except the null value is also allowed.
2660
2661 =cut
2662
2663 sub ut_foreign_keyn {
2664   my( $self, $field, $table, $foreign ) = @_;
2665   $self->getfield($field)
2666     ? $self->ut_foreign_key($field, $table, $foreign)
2667     : '';
2668 }
2669
2670 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2671
2672 Checks this column as an agentnum, taking into account the current users's
2673 ACLs.  NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2674 right or rights allowing no agentnum.
2675
2676 =cut
2677
2678 sub ut_agentnum_acl {
2679   my( $self, $field ) = (shift, shift);
2680   my $null_acl = scalar(@_) ? shift : [];
2681   $null_acl = [ $null_acl ] unless ref($null_acl);
2682
2683   my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2684   return "Illegal agentnum: $error" if $error;
2685
2686   my $curuser = $FS::CurrentUser::CurrentUser;
2687
2688   if ( $self->$field() ) {
2689
2690     return "Access denied"
2691       unless $curuser->agentnum($self->$field());
2692
2693   } else {
2694
2695     return "Access denied"
2696       unless grep $curuser->access_right($_), @$null_acl;
2697
2698   }
2699
2700   '';
2701
2702 }
2703
2704 =item virtual_fields [ TABLE ]
2705
2706 Returns a list of virtual fields defined for the table.  This should not 
2707 be exported, and should only be called as an instance or class method.
2708
2709 =cut
2710
2711 sub virtual_fields {
2712   my $self = shift;
2713   my $table;
2714   $table = $self->table or confess "virtual_fields called on non-table";
2715
2716   confess "Unknown table $table" unless dbdef->table($table);
2717
2718   return () unless dbdef->table('part_virtual_field');
2719
2720   unless ( $virtual_fields_cache{$table} ) {
2721     my $query = 'SELECT name from part_virtual_field ' .
2722                 "WHERE dbtable = '$table'";
2723     my $dbh = dbh;
2724     my $result = $dbh->selectcol_arrayref($query);
2725     confess "Error executing virtual fields query: $query: ". $dbh->errstr
2726       if $dbh->err;
2727     $virtual_fields_cache{$table} = $result;
2728   }
2729
2730   @{$virtual_fields_cache{$table}};
2731
2732 }
2733
2734
2735 =item fields [ TABLE ]
2736
2737 This is a wrapper for real_fields and virtual_fields.  Code that called
2738 fields before should probably continue to call fields.
2739
2740 =cut
2741
2742 sub fields {
2743   my $something = shift;
2744   my $table;
2745   if($something->isa('FS::Record')) {
2746     $table = $something->table;
2747   } else {
2748     $table = $something;
2749     $something = "FS::$table";
2750   }
2751   return (real_fields($table), $something->virtual_fields());
2752 }
2753
2754 =item pvf FIELD_NAME
2755
2756 Returns the FS::part_virtual_field object corresponding to a field in the 
2757 record (specified by FIELD_NAME).
2758
2759 =cut
2760
2761 sub pvf {
2762   my ($self, $name) = (shift, shift);
2763
2764   if(grep /^$name$/, $self->virtual_fields) {
2765     return qsearchs('part_virtual_field', { dbtable => $self->table,
2766                                             name    => $name } );
2767   }
2768   ''
2769 }
2770
2771 =item vfieldpart_hashref TABLE
2772
2773 Returns a hashref of virtual field names and vfieldparts applicable to the given
2774 TABLE.
2775
2776 =cut
2777
2778 sub vfieldpart_hashref {
2779   my $self = shift;
2780   my $table = $self->table;
2781
2782   return {} unless dbdef->table('part_virtual_field');
2783
2784   my $dbh = dbh;
2785   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2786                   "dbtable = '$table'";
2787   my $sth = $dbh->prepare($statement);
2788   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2789   return { map { $_->{name}, $_->{vfieldpart} } 
2790     @{$sth->fetchall_arrayref({})} };
2791
2792 }
2793
2794 =item encrypt($value)
2795
2796 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2797
2798 Returns the encrypted string.
2799
2800 You should generally not have to worry about calling this, as the system handles this for you.
2801
2802 =cut
2803
2804 sub encrypt {
2805   my ($self, $value) = @_;
2806   my $encrypted;
2807
2808   if ($conf->exists('encryption')) {
2809     if ($self->is_encrypted($value)) {
2810       # Return the original value if it isn't plaintext.
2811       $encrypted = $value;
2812     } else {
2813       $self->loadRSA;
2814       if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2815         # RSA doesn't like the empty string so let's pack it up
2816         # The database doesn't like the RSA data so uuencode it
2817         my $length = length($value)+1;
2818         $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2819       } else {
2820         die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2821       }
2822     }
2823   }
2824   return $encrypted;
2825 }
2826
2827 =item is_encrypted($value)
2828
2829 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2830
2831 =cut
2832
2833
2834 sub is_encrypted {
2835   my ($self, $value) = @_;
2836   # Possible Bug - Some work may be required here....
2837
2838   if ($value =~ /^M/ && length($value) > 80) {
2839     return 1;
2840   } else {
2841     return 0;
2842   }
2843 }
2844
2845 =item decrypt($value)
2846
2847 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2848
2849 You should generally not have to worry about calling this, as the system handles this for you.
2850
2851 =cut
2852
2853 sub decrypt {
2854   my ($self,$value) = @_;
2855   my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2856   if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2857     $self->loadRSA;
2858     if (ref($rsa_decrypt) =~ /::RSA/) {
2859       my $encrypted = unpack ("u*", $value);
2860       $decrypted =  unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2861       if ($@) {warn "Decryption Failed"};
2862     }
2863   }
2864   return $decrypted;
2865 }
2866
2867 sub loadRSA {
2868     my $self = shift;
2869     #Initialize the Module
2870     $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2871
2872     if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2873       $rsa_module = $conf->config('encryptionmodule');
2874     }
2875
2876     if (!$rsa_loaded) {
2877         eval ("require $rsa_module"); # No need to import the namespace
2878         $rsa_loaded++;
2879     }
2880     # Initialize Encryption
2881     if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2882       my $public_key = join("\n",$conf->config('encryptionpublickey'));
2883       $rsa_encrypt = $rsa_module->new_public_key($public_key);
2884     }
2885     
2886     # Intitalize Decryption
2887     if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2888       my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2889       $rsa_decrypt = $rsa_module->new_private_key($private_key);
2890     }
2891 }
2892
2893 =item h_search ACTION
2894
2895 Given an ACTION, either "insert", or "delete", returns the appropriate history
2896 record corresponding to this record, if any.
2897
2898 =cut
2899
2900 sub h_search {
2901   my( $self, $action ) = @_;
2902
2903   my $table = $self->table;
2904   $table =~ s/^h_//;
2905
2906   my $primary_key = dbdef->table($table)->primary_key;
2907
2908   qsearchs({
2909     'table'   => "h_$table",
2910     'hashref' => { $primary_key     => $self->$primary_key(),
2911                    'history_action' => $action,
2912                  },
2913   });
2914
2915 }
2916
2917 =item h_date ACTION
2918
2919 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2920 appropriate history record corresponding to this record, if any.
2921
2922 =cut
2923
2924 sub h_date {
2925   my($self, $action) = @_;
2926   my $h = $self->h_search($action);
2927   $h ? $h->history_date : '';
2928 }
2929
2930 =item scalar_sql SQL [ PLACEHOLDER, ... ]
2931
2932 A class or object method.  Executes the sql statement represented by SQL and
2933 returns a scalar representing the result: the first column of the first row.
2934
2935 Dies on bogus SQL.  Returns an empty string if no row is returned.
2936
2937 Typically used for statments which return a single value such as "SELECT
2938 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
2939
2940 =cut
2941
2942 sub scalar_sql {
2943   my($self, $sql) = (shift, shift);
2944   my $sth = dbh->prepare($sql) or die dbh->errstr;
2945   $sth->execute(@_)
2946     or die "Unexpected error executing statement $sql: ". $sth->errstr;
2947   my $row = $sth->fetchrow_arrayref or return '';
2948   my $scalar = $row->[0];
2949   defined($scalar) ? $scalar : '';
2950 }
2951
2952 =back
2953
2954 =head1 SUBROUTINES
2955
2956 =over 4
2957
2958 =item real_fields [ TABLE ]
2959
2960 Returns a list of the real columns in the specified table.  Called only by 
2961 fields() and other subroutines elsewhere in FS::Record.
2962
2963 =cut
2964
2965 sub real_fields {
2966   my $table = shift;
2967
2968   my($table_obj) = dbdef->table($table);
2969   confess "Unknown table $table" unless $table_obj;
2970   $table_obj->columns;
2971 }
2972
2973 =item _quote VALUE, TABLE, COLUMN
2974
2975 This is an internal function used to construct SQL statements.  It returns
2976 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2977 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2978
2979 =cut
2980
2981 sub _quote {
2982   my($value, $table, $column) = @_;
2983   my $column_obj = dbdef->table($table)->column($column);
2984   my $column_type = $column_obj->type;
2985   my $nullable = $column_obj->null;
2986
2987   warn "  $table.$column: $value ($column_type".
2988        ( $nullable ? ' NULL' : ' NOT NULL' ).
2989        ")\n" if $DEBUG > 2;
2990
2991   if ( $value eq '' && $nullable ) {
2992     'NULL';
2993   } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2994     cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2995           "using 0 instead";
2996     0;
2997   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
2998             ! $column_type =~ /(char|binary|text)$/i ) {
2999     $value;
3000   } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3001            && driver_name eq 'Pg'
3002           )
3003   {
3004     no strict 'subs';
3005 #    dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3006     # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\, 
3007     # single-quote the whole mess, and put an "E" in front.
3008     return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3009   } else {
3010     dbh->quote($value);
3011   }
3012 }
3013
3014 =item hfields TABLE
3015
3016 This is deprecated.  Don't use it.
3017
3018 It returns a hash-type list with the fields of this record's table set true.
3019
3020 =cut
3021
3022 sub hfields {
3023   carp "warning: hfields is deprecated";
3024   my($table)=@_;
3025   my(%hash);
3026   foreach (fields($table)) {
3027     $hash{$_}=1;
3028   }
3029   \%hash;
3030 }
3031
3032 sub _dump {
3033   my($self)=@_;
3034   join("\n", map {
3035     "$_: ". $self->getfield($_). "|"
3036   } (fields($self->table)) );
3037 }
3038
3039 sub DESTROY { return; }
3040
3041 #sub DESTROY {
3042 #  my $self = shift;
3043 #  #use Carp qw(cluck);
3044 #  #cluck "DESTROYING $self";
3045 #  warn "DESTROYING $self";
3046 #}
3047
3048 #sub is_tainted {
3049 #             return ! eval { join('',@_), kill 0; 1; };
3050 #         }
3051
3052 =item str2time_sql [ DRIVER_NAME ]
3053
3054 Returns a function to convert to unix time based on database type, such as
3055 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql.  See
3056 the str2time_sql_closing method to return a closing string rather than just
3057 using a closing parenthesis as previously suggested.
3058
3059 You can pass an optional driver name such as "Pg", "mysql" or
3060 $dbh->{Driver}->{Name} to return a function for that database instead of
3061 the current database.
3062
3063 =cut
3064
3065 sub str2time_sql { 
3066   my $driver = shift || driver_name;
3067
3068   return 'UNIX_TIMESTAMP('      if $driver =~ /^mysql/i;
3069   return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3070
3071   warn "warning: unknown database type $driver; guessing how to convert ".
3072        "dates to UNIX timestamps";
3073   return 'EXTRACT(EPOCH FROM ';
3074
3075 }
3076
3077 =item str2time_sql_closing [ DRIVER_NAME ]
3078
3079 Returns the closing suffix of a function to convert to unix time based on
3080 database type, such as ")::integer" for Pg or ")" for mysql.
3081
3082 You can pass an optional driver name such as "Pg", "mysql" or
3083 $dbh->{Driver}->{Name} to return a function for that database instead of
3084 the current database.
3085
3086 =cut
3087
3088 sub str2time_sql_closing { 
3089   my $driver = shift || driver_name;
3090
3091   return ' )::INTEGER ' if $driver =~ /^Pg/i;
3092   return ' ) ';
3093 }
3094
3095 =item regexp_sql [ DRIVER_NAME ]
3096
3097 Returns the operator to do a regular expression comparison based on database
3098 type, such as '~' for Pg or 'REGEXP' for mysql.
3099
3100 You can pass an optional driver name such as "Pg", "mysql" or
3101 $dbh->{Driver}->{Name} to return a function for that database instead of
3102 the current database.
3103
3104 =cut
3105
3106 sub regexp_sql {
3107   my $driver = shift || driver_name;
3108
3109   return '~'      if $driver =~ /^Pg/i;
3110   return 'REGEXP' if $driver =~ /^mysql/i;
3111
3112   die "don't know how to use regular expressions in ". driver_name." databases";
3113
3114 }
3115
3116 =item not_regexp_sql [ DRIVER_NAME ]
3117
3118 Returns the operator to do a regular expression negation based on database
3119 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3120
3121 You can pass an optional driver name such as "Pg", "mysql" or
3122 $dbh->{Driver}->{Name} to return a function for that database instead of
3123 the current database.
3124
3125 =cut
3126
3127 sub not_regexp_sql {
3128   my $driver = shift || driver_name;
3129
3130   return '!~'         if $driver =~ /^Pg/i;
3131   return 'NOT REGEXP' if $driver =~ /^mysql/i;
3132
3133   die "don't know how to use regular expressions in ". driver_name." databases";
3134
3135 }
3136
3137 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3138
3139 Returns the items concatendated based on database type, using "CONCAT()" for
3140 mysql and " || " for Pg and other databases.
3141
3142 You can pass an optional driver name such as "Pg", "mysql" or
3143 $dbh->{Driver}->{Name} to return a function for that database instead of
3144 the current database.
3145
3146 =cut
3147
3148 sub concat_sql {
3149   my $driver = ref($_[0]) ? driver_name : shift;
3150   my $items = shift;
3151
3152   if ( $driver =~ /^mysql/i ) {
3153     'CONCAT('. join(',', @$items). ')';
3154   } else {
3155     join('||', @$items);
3156   }
3157
3158 }
3159
3160 =back
3161
3162 =head1 BUGS
3163
3164 This module should probably be renamed, since much of the functionality is
3165 of general use.  It is not completely unlike Adapter::DBI (see below).
3166
3167 Exported qsearch and qsearchs should be deprecated in favor of method calls
3168 (against an FS::Record object like the old search and searchs that qsearch
3169 and qsearchs were on top of.)
3170
3171 The whole fields / hfields mess should be removed.
3172
3173 The various WHERE clauses should be subroutined.
3174
3175 table string should be deprecated in favor of DBIx::DBSchema::Table.
3176
3177 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
3178 true maps to the database (and WHERE clauses) would also help.
3179
3180 The ut_ methods should ask the dbdef for a default length.
3181
3182 ut_sqltype (like ut_varchar) should all be defined
3183
3184 A fallback check method should be provided which uses the dbdef.
3185
3186 The ut_money method assumes money has two decimal digits.
3187
3188 The Pg money kludge in the new method only strips `$'.
3189
3190 The ut_phonen method only checks US-style phone numbers.
3191
3192 The _quote function should probably use ut_float instead of a regex.
3193
3194 All the subroutines probably should be methods, here or elsewhere.
3195
3196 Probably should borrow/use some dbdef methods where appropriate (like sub
3197 fields)
3198
3199 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3200 or allow it to be set.  Working around it is ugly any way around - DBI should
3201 be fixed.  (only affects RDBMS which return uppercase column names)
3202
3203 ut_zip should take an optional country like ut_phone.
3204
3205 =head1 SEE ALSO
3206
3207 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3208
3209 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
3210
3211 http://poop.sf.net/
3212
3213 =cut
3214
3215 1;
3216