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