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