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