Add cust_attachment stuff
[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_text COLUMN
1992
1993 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1994 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
1995 May not be null.  If there is an error, returns the error, otherwise returns
1996 false.
1997
1998 =cut
1999
2000 sub ut_text {
2001   my($self,$field)=@_;
2002   #warn "msgcat ". \&msgcat. "\n";
2003   #warn "notexist ". \&notexist. "\n";
2004   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2005   $self->getfield($field)
2006     =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
2007       or return gettext('illegal_or_empty_text'). " $field: ".
2008                  $self->getfield($field);
2009   $self->setfield($field,$1);
2010   '';
2011 }
2012
2013 =item ut_textn COLUMN
2014
2015 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
2016 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
2017 May be null.  If there is an error, returns the error, otherwise returns false.
2018
2019 =cut
2020
2021 sub ut_textn {
2022   my($self,$field)=@_;
2023   $self->getfield($field)
2024     =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
2025       or return gettext('illegal_text'). " $field: ". $self->getfield($field);
2026   $self->setfield($field,$1);
2027   '';
2028 }
2029
2030 =item ut_alpha COLUMN
2031
2032 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
2033 an error, returns the error, otherwise returns false.
2034
2035 =cut
2036
2037 sub ut_alpha {
2038   my($self,$field)=@_;
2039   $self->getfield($field) =~ /^(\w+)$/
2040     or return "Illegal or empty (alphanumeric) $field: ".
2041               $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 be null.  If there is an
2049 error, returns the error, otherwise returns false.
2050
2051 =cut
2052
2053 sub ut_alphan {
2054   my($self,$field)=@_;
2055   $self->getfield($field) =~ /^(\w*)$/ 
2056     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2057   $self->setfield($field,$1);
2058   '';
2059 }
2060
2061 =item ut_alpha_lower COLUMN
2062
2063 Check/untaint lowercase alphanumeric strings (no spaces).  May not be null.  If
2064 there is an error, returns the error, otherwise returns false.
2065
2066 =cut
2067
2068 sub ut_alpha_lower {
2069   my($self,$field)=@_;
2070   $self->getfield($field) =~ /[[:upper:]]/
2071     and return "Uppercase characters are not permitted in $field";
2072   $self->ut_alpha($field);
2073 }
2074
2075 =item ut_phonen COLUMN [ COUNTRY ]
2076
2077 Check/untaint phone numbers.  May be null.  If there is an error, returns
2078 the error, otherwise returns false.
2079
2080 Takes an optional two-letter ISO country code; without it or with unsupported
2081 countries, ut_phonen simply calls ut_alphan.
2082
2083 =cut
2084
2085 sub ut_phonen {
2086   my( $self, $field, $country ) = @_;
2087   return $self->ut_alphan($field) unless defined $country;
2088   my $phonen = $self->getfield($field);
2089   if ( $phonen eq '' ) {
2090     $self->setfield($field,'');
2091   } elsif ( $country eq 'US' || $country eq 'CA' ) {
2092     $phonen =~ s/\D//g;
2093     $phonen = $conf->config('cust_main-default_areacode').$phonen
2094       if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2095     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2096       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2097     $phonen = "$1-$2-$3";
2098     $phonen .= " x$4" if $4;
2099     $self->setfield($field,$phonen);
2100   } else {
2101     warn "warning: don't know how to check phone numbers for country $country";
2102     return $self->ut_textn($field);
2103   }
2104   '';
2105 }
2106
2107 =item ut_hex COLUMN
2108
2109 Check/untaint hexadecimal values.
2110
2111 =cut
2112
2113 sub ut_hex {
2114   my($self, $field) = @_;
2115   $self->getfield($field) =~ /^([\da-fA-F]+)$/
2116     or return "Illegal (hex) $field: ". $self->getfield($field);
2117   $self->setfield($field, uc($1));
2118   '';
2119 }
2120
2121 =item ut_hexn COLUMN
2122
2123 Check/untaint hexadecimal values.  May be null.
2124
2125 =cut
2126
2127 sub ut_hexn {
2128   my($self, $field) = @_;
2129   $self->getfield($field) =~ /^([\da-fA-F]*)$/
2130     or return "Illegal (hex) $field: ". $self->getfield($field);
2131   $self->setfield($field, uc($1));
2132   '';
2133 }
2134 =item ut_ip COLUMN
2135
2136 Check/untaint ip addresses.  IPv4 only for now.
2137
2138 =cut
2139
2140 sub ut_ip {
2141   my( $self, $field ) = @_;
2142   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2143     or return "Illegal (IP address) $field: ". $self->getfield($field);
2144   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2145   $self->setfield($field, "$1.$2.$3.$4");
2146   '';
2147 }
2148
2149 =item ut_ipn COLUMN
2150
2151 Check/untaint ip addresses.  IPv4 only for now.  May be null.
2152
2153 =cut
2154
2155 sub ut_ipn {
2156   my( $self, $field ) = @_;
2157   if ( $self->getfield($field) =~ /^()$/ ) {
2158     $self->setfield($field,'');
2159     '';
2160   } else {
2161     $self->ut_ip($field);
2162   }
2163 }
2164
2165 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2166
2167 Check/untaint coordinates.
2168 Accepts the following forms:
2169 DDD.DDDDD
2170 -DDD.DDDDD
2171 DDD MM.MMM
2172 -DDD MM.MMM
2173 DDD MM SS
2174 -DDD MM SS
2175 DDD MM MMM
2176 -DDD MM MMM
2177
2178 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2179 The latter form (that is, the MMM are thousands of minutes) is
2180 assumed if the "MMM" is exactly three digits or two digits > 59.
2181
2182 To be safe, just use the DDD.DDDDD form.
2183
2184 If LOWER or UPPER are specified, then the coordinate is checked
2185 for lower and upper bounds, respectively.
2186
2187 =cut
2188
2189 sub ut_coord {
2190
2191   my ($self, $field) = (shift, shift);
2192
2193   my $lower = shift if scalar(@_);
2194   my $upper = shift if scalar(@_);
2195   my $coord = $self->getfield($field);
2196   my $neg = $coord =~ s/^(-)//;
2197
2198   my ($d, $m, $s) = (0, 0, 0);
2199
2200   if (
2201     (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2202     (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2203     (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2204   ) {
2205     $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2206     $m = $m / 60;
2207     if ($m > 59) {
2208       return "Invalid (coordinate with minutes > 59) $field: "
2209              . $self->getfield($field);
2210     }
2211
2212     $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2213
2214     if (defined($lower) and ($coord < $lower)) {
2215       return "Invalid (coordinate < $lower) $field: "
2216              . $self->getfield($field);;
2217     }
2218
2219     if (defined($upper) and ($coord > $upper)) {
2220       return "Invalid (coordinate > $upper) $field: "
2221              . $self->getfield($field);;
2222     }
2223
2224     $self->setfield($field, $coord);
2225     return '';
2226   }
2227
2228   return "Invalid (coordinate) $field: " . $self->getfield($field);
2229
2230 }
2231
2232 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2233
2234 Same as ut_coord, except optionally null.
2235
2236 =cut
2237
2238 sub ut_coordn {
2239
2240   my ($self, $field) = (shift, shift);
2241
2242   if ($self->getfield($field) =~ /^$/) {
2243     return '';
2244   } else {
2245     return $self->ut_coord($field, @_);
2246   }
2247
2248 }
2249
2250
2251 =item ut_domain COLUMN
2252
2253 Check/untaint host and domain names.
2254
2255 =cut
2256
2257 sub ut_domain {
2258   my( $self, $field ) = @_;
2259   #$self->getfield($field) =~/^(\w+\.)*\w+$/
2260   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2261     or return "Illegal (domain) $field: ". $self->getfield($field);
2262   $self->setfield($field,$1);
2263   '';
2264 }
2265
2266 =item ut_name COLUMN
2267
2268 Check/untaint proper names; allows alphanumerics, spaces and the following
2269 punctuation: , . - '
2270
2271 May not be null.
2272
2273 =cut
2274
2275 sub ut_name {
2276   my( $self, $field ) = @_;
2277   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2278     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2279   $self->setfield($field,$1);
2280   '';
2281 }
2282
2283 =item ut_zip COLUMN
2284
2285 Check/untaint zip codes.
2286
2287 =cut
2288
2289 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2290
2291 sub ut_zip {
2292   my( $self, $field, $country ) = @_;
2293
2294   if ( $country eq 'US' ) {
2295
2296     $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2297       or return gettext('illegal_zip'). " $field for country $country: ".
2298                 $self->getfield($field);
2299     $self->setfield($field, $1);
2300
2301   } elsif ( $country eq 'CA' ) {
2302
2303     $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2304       or return gettext('illegal_zip'). " $field for country $country: ".
2305                 $self->getfield($field);
2306     $self->setfield($field, "$1 $2");
2307
2308   } else {
2309
2310     if ( $self->getfield($field) =~ /^\s*$/
2311          && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2312        )
2313     {
2314       $self->setfield($field,'');
2315     } else {
2316       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2317         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2318       $self->setfield($field,$1);
2319     }
2320
2321   }
2322
2323   '';
2324 }
2325
2326 =item ut_country COLUMN
2327
2328 Check/untaint country codes.  Country names are changed to codes, if possible -
2329 see L<Locale::Country>.
2330
2331 =cut
2332
2333 sub ut_country {
2334   my( $self, $field ) = @_;
2335   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2336     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
2337          && country2code($1) ) {
2338       $self->setfield($field,uc(country2code($1)));
2339     }
2340   }
2341   $self->getfield($field) =~ /^(\w\w)$/
2342     or return "Illegal (country) $field: ". $self->getfield($field);
2343   $self->setfield($field,uc($1));
2344   '';
2345 }
2346
2347 =item ut_anything COLUMN
2348
2349 Untaints arbitrary data.  Be careful.
2350
2351 =cut
2352
2353 sub ut_anything {
2354   my( $self, $field ) = @_;
2355   $self->getfield($field) =~ /^(.*)$/s
2356     or return "Illegal $field: ". $self->getfield($field);
2357   $self->setfield($field,$1);
2358   '';
2359 }
2360
2361 =item ut_enum COLUMN CHOICES_ARRAYREF
2362
2363 Check/untaint a column, supplying all possible choices, like the "enum" type.
2364
2365 =cut
2366
2367 sub ut_enum {
2368   my( $self, $field, $choices ) = @_;
2369   foreach my $choice ( @$choices ) {
2370     if ( $self->getfield($field) eq $choice ) {
2371       $self->setfield($field, $choice);
2372       return '';
2373     }
2374   }
2375   return "Illegal (enum) field $field: ". $self->getfield($field);
2376 }
2377
2378 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2379
2380 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
2381 on the column first.
2382
2383 =cut
2384
2385 sub ut_foreign_key {
2386   my( $self, $field, $table, $foreign ) = @_;
2387   return '' if $no_check_foreign;
2388   qsearchs($table, { $foreign => $self->getfield($field) })
2389     or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2390               " in $table.$foreign";
2391   '';
2392 }
2393
2394 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2395
2396 Like ut_foreign_key, except the null value is also allowed.
2397
2398 =cut
2399
2400 sub ut_foreign_keyn {
2401   my( $self, $field, $table, $foreign ) = @_;
2402   $self->getfield($field)
2403     ? $self->ut_foreign_key($field, $table, $foreign)
2404     : '';
2405 }
2406
2407 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2408
2409 Checks this column as an agentnum, taking into account the current users's
2410 ACLs.  NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2411 right or rights allowing no agentnum.
2412
2413 =cut
2414
2415 sub ut_agentnum_acl {
2416   my( $self, $field ) = (shift, shift);
2417   my $null_acl = scalar(@_) ? shift : [];
2418   $null_acl = [ $null_acl ] unless ref($null_acl);
2419
2420   my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2421   return "Illegal agentnum: $error" if $error;
2422
2423   my $curuser = $FS::CurrentUser::CurrentUser;
2424
2425   if ( $self->$field() ) {
2426
2427     return "Access denied"
2428       unless $curuser->agentnum($self->$field());
2429
2430   } else {
2431
2432     return "Access denied"
2433       unless grep $curuser->access_right($_), @$null_acl;
2434
2435   }
2436
2437   '';
2438
2439 }
2440
2441 =item virtual_fields [ TABLE ]
2442
2443 Returns a list of virtual fields defined for the table.  This should not 
2444 be exported, and should only be called as an instance or class method.
2445
2446 =cut
2447
2448 sub virtual_fields {
2449   my $self = shift;
2450   my $table;
2451   $table = $self->table or confess "virtual_fields called on non-table";
2452
2453   confess "Unknown table $table" unless dbdef->table($table);
2454
2455   return () unless dbdef->table('part_virtual_field');
2456
2457   unless ( $virtual_fields_cache{$table} ) {
2458     my $query = 'SELECT name from part_virtual_field ' .
2459                 "WHERE dbtable = '$table'";
2460     my $dbh = dbh;
2461     my $result = $dbh->selectcol_arrayref($query);
2462     confess "Error executing virtual fields query: $query: ". $dbh->errstr
2463       if $dbh->err;
2464     $virtual_fields_cache{$table} = $result;
2465   }
2466
2467   @{$virtual_fields_cache{$table}};
2468
2469 }
2470
2471
2472 =item fields [ TABLE ]
2473
2474 This is a wrapper for real_fields and virtual_fields.  Code that called
2475 fields before should probably continue to call fields.
2476
2477 =cut
2478
2479 sub fields {
2480   my $something = shift;
2481   my $table;
2482   if($something->isa('FS::Record')) {
2483     $table = $something->table;
2484   } else {
2485     $table = $something;
2486     $something = "FS::$table";
2487   }
2488   return (real_fields($table), $something->virtual_fields());
2489 }
2490
2491 =item pvf FIELD_NAME
2492
2493 Returns the FS::part_virtual_field object corresponding to a field in the 
2494 record (specified by FIELD_NAME).
2495
2496 =cut
2497
2498 sub pvf {
2499   my ($self, $name) = (shift, shift);
2500
2501   if(grep /^$name$/, $self->virtual_fields) {
2502     return qsearchs('part_virtual_field', { dbtable => $self->table,
2503                                             name    => $name } );
2504   }
2505   ''
2506 }
2507
2508 =item vfieldpart_hashref TABLE
2509
2510 Returns a hashref of virtual field names and vfieldparts applicable to the given
2511 TABLE.
2512
2513 =cut
2514
2515 sub vfieldpart_hashref {
2516   my $self = shift;
2517   my $table = $self->table;
2518
2519   return {} unless dbdef->table('part_virtual_field');
2520
2521   my $dbh = dbh;
2522   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2523                   "dbtable = '$table'";
2524   my $sth = $dbh->prepare($statement);
2525   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2526   return { map { $_->{name}, $_->{vfieldpart} } 
2527     @{$sth->fetchall_arrayref({})} };
2528
2529 }
2530
2531 =item encrypt($value)
2532
2533 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2534
2535 Returns the encrypted string.
2536
2537 You should generally not have to worry about calling this, as the system handles this for you.
2538
2539 =cut
2540
2541 sub encrypt {
2542   my ($self, $value) = @_;
2543   my $encrypted;
2544
2545   if ($conf->exists('encryption')) {
2546     if ($self->is_encrypted($value)) {
2547       # Return the original value if it isn't plaintext.
2548       $encrypted = $value;
2549     } else {
2550       $self->loadRSA;
2551       if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2552         # RSA doesn't like the empty string so let's pack it up
2553         # The database doesn't like the RSA data so uuencode it
2554         my $length = length($value)+1;
2555         $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2556       } else {
2557         die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2558       }
2559     }
2560   }
2561   return $encrypted;
2562 }
2563
2564 =item is_encrypted($value)
2565
2566 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2567
2568 =cut
2569
2570
2571 sub is_encrypted {
2572   my ($self, $value) = @_;
2573   # Possible Bug - Some work may be required here....
2574
2575   if ($value =~ /^M/ && length($value) > 80) {
2576     return 1;
2577   } else {
2578     return 0;
2579   }
2580 }
2581
2582 =item decrypt($value)
2583
2584 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2585
2586 You should generally not have to worry about calling this, as the system handles this for you.
2587
2588 =cut
2589
2590 sub decrypt {
2591   my ($self,$value) = @_;
2592   my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2593   if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2594     $self->loadRSA;
2595     if (ref($rsa_decrypt) =~ /::RSA/) {
2596       my $encrypted = unpack ("u*", $value);
2597       $decrypted =  unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2598       if ($@) {warn "Decryption Failed"};
2599     }
2600   }
2601   return $decrypted;
2602 }
2603
2604 sub loadRSA {
2605     my $self = shift;
2606     #Initialize the Module
2607     $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2608
2609     if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2610       $rsa_module = $conf->config('encryptionmodule');
2611     }
2612
2613     if (!$rsa_loaded) {
2614         eval ("require $rsa_module"); # No need to import the namespace
2615         $rsa_loaded++;
2616     }
2617     # Initialize Encryption
2618     if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2619       my $public_key = join("\n",$conf->config('encryptionpublickey'));
2620       $rsa_encrypt = $rsa_module->new_public_key($public_key);
2621     }
2622     
2623     # Intitalize Decryption
2624     if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2625       my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2626       $rsa_decrypt = $rsa_module->new_private_key($private_key);
2627     }
2628 }
2629
2630 =item h_search ACTION
2631
2632 Given an ACTION, either "insert", or "delete", returns the appropriate history
2633 record corresponding to this record, if any.
2634
2635 =cut
2636
2637 sub h_search {
2638   my( $self, $action ) = @_;
2639
2640   my $table = $self->table;
2641   $table =~ s/^h_//;
2642
2643   my $primary_key = dbdef->table($table)->primary_key;
2644
2645   qsearchs({
2646     'table'   => "h_$table",
2647     'hashref' => { $primary_key     => $self->$primary_key(),
2648                    'history_action' => $action,
2649                  },
2650   });
2651
2652 }
2653
2654 =item h_date ACTION
2655
2656 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2657 appropriate history record corresponding to this record, if any.
2658
2659 =cut
2660
2661 sub h_date {
2662   my($self, $action) = @_;
2663   my $h = $self->h_search($action);
2664   $h ? $h->history_date : '';
2665 }
2666
2667 =back
2668
2669 =head1 SUBROUTINES
2670
2671 =over 4
2672
2673 =item real_fields [ TABLE ]
2674
2675 Returns a list of the real columns in the specified table.  Called only by 
2676 fields() and other subroutines elsewhere in FS::Record.
2677
2678 =cut
2679
2680 sub real_fields {
2681   my $table = shift;
2682
2683   my($table_obj) = dbdef->table($table);
2684   confess "Unknown table $table" unless $table_obj;
2685   $table_obj->columns;
2686 }
2687
2688 =item _quote VALUE, TABLE, COLUMN
2689
2690 This is an internal function used to construct SQL statements.  It returns
2691 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2692 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2693
2694 =cut
2695
2696 sub _quote {
2697   my($value, $table, $column) = @_;
2698   my $column_obj = dbdef->table($table)->column($column);
2699   my $column_type = $column_obj->type;
2700   my $nullable = $column_obj->null;
2701
2702   warn "  $table.$column: $value ($column_type".
2703        ( $nullable ? ' NULL' : ' NOT NULL' ).
2704        ")\n" if $DEBUG > 2;
2705
2706   if ( $value eq '' && $nullable ) {
2707     'NULL';
2708   } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2709     cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2710           "using 0 instead";
2711     0;
2712   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
2713             ! $column_type =~ /(char|binary|text)$/i ) {
2714     $value;
2715   } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
2716            && driver_name eq 'Pg'
2717           )
2718   {
2719     no strict 'subs';
2720 #    dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
2721     # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\, 
2722     # single-quote the whole mess, and put an "E" in front.
2723     return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
2724   } else {
2725     dbh->quote($value);
2726   }
2727 }
2728
2729 =item hfields TABLE
2730
2731 This is deprecated.  Don't use it.
2732
2733 It returns a hash-type list with the fields of this record's table set true.
2734
2735 =cut
2736
2737 sub hfields {
2738   carp "warning: hfields is deprecated";
2739   my($table)=@_;
2740   my(%hash);
2741   foreach (fields($table)) {
2742     $hash{$_}=1;
2743   }
2744   \%hash;
2745 }
2746
2747 sub _dump {
2748   my($self)=@_;
2749   join("\n", map {
2750     "$_: ". $self->getfield($_). "|"
2751   } (fields($self->table)) );
2752 }
2753
2754 sub DESTROY { return; }
2755
2756 #sub DESTROY {
2757 #  my $self = shift;
2758 #  #use Carp qw(cluck);
2759 #  #cluck "DESTROYING $self";
2760 #  warn "DESTROYING $self";
2761 #}
2762
2763 #sub is_tainted {
2764 #             return ! eval { join('',@_), kill 0; 1; };
2765 #         }
2766
2767 =item str2time_sql [ DRIVER_NAME ]
2768
2769 Returns a function to convert to unix time based on database type, such as
2770 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql.  See
2771 the str2time_sql_closing method to return a closing string rather than just
2772 using a closing parenthesis as previously suggested.
2773
2774 You can pass an optional driver name such as "Pg", "mysql" or
2775 $dbh->{Driver}->{Name} to return a function for that database instead of
2776 the current database.
2777
2778 =cut
2779
2780 sub str2time_sql { 
2781   my $driver = shift || driver_name;
2782
2783   return 'UNIX_TIMESTAMP('      if $driver =~ /^mysql/i;
2784   return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2785
2786   warn "warning: unknown database type $driver; guessing how to convert ".
2787        "dates to UNIX timestamps";
2788   return 'EXTRACT(EPOCH FROM ';
2789
2790 }
2791
2792 =item str2time_sql_closing [ DRIVER_NAME ]
2793
2794 Returns the closing suffix of a function to convert to unix time based on
2795 database type, such as ")::integer" for Pg or ")" for mysql.
2796
2797 You can pass an optional driver name such as "Pg", "mysql" or
2798 $dbh->{Driver}->{Name} to return a function for that database instead of
2799 the current database.
2800
2801 =cut
2802
2803 sub str2time_sql_closing { 
2804   my $driver = shift || driver_name;
2805
2806   return ' )::INTEGER ' if $driver =~ /^Pg/i;
2807   return ' ) ';
2808 }
2809
2810 =back
2811
2812 =head1 BUGS
2813
2814 This module should probably be renamed, since much of the functionality is
2815 of general use.  It is not completely unlike Adapter::DBI (see below).
2816
2817 Exported qsearch and qsearchs should be deprecated in favor of method calls
2818 (against an FS::Record object like the old search and searchs that qsearch
2819 and qsearchs were on top of.)
2820
2821 The whole fields / hfields mess should be removed.
2822
2823 The various WHERE clauses should be subroutined.
2824
2825 table string should be deprecated in favor of DBIx::DBSchema::Table.
2826
2827 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
2828 true maps to the database (and WHERE clauses) would also help.
2829
2830 The ut_ methods should ask the dbdef for a default length.
2831
2832 ut_sqltype (like ut_varchar) should all be defined
2833
2834 A fallback check method should be provided which uses the dbdef.
2835
2836 The ut_money method assumes money has two decimal digits.
2837
2838 The Pg money kludge in the new method only strips `$'.
2839
2840 The ut_phonen method only checks US-style phone numbers.
2841
2842 The _quote function should probably use ut_float instead of a regex.
2843
2844 All the subroutines probably should be methods, here or elsewhere.
2845
2846 Probably should borrow/use some dbdef methods where appropriate (like sub
2847 fields)
2848
2849 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2850 or allow it to be set.  Working around it is ugly any way around - DBI should
2851 be fixed.  (only affects RDBMS which return uppercase column names)
2852
2853 ut_zip should take an optional country like ut_phone.
2854
2855 =head1 SEE ALSO
2856
2857 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2858
2859 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
2860
2861 http://poop.sf.net/
2862
2863 =cut
2864
2865 1;
2866