2 use base qw( Exporter );
7 $money_char $lat_lower $lon_upper
9 use Carp qw(carp cluck croak confess);
10 use Scalar::Util qw( blessed );
11 use File::Slurp qw( slurp );
12 use File::CounterFile;
14 use DBI qw(:sql_types);
15 use DBIx::DBSchema 0.43; #0.43 for foreign keys
18 use NetAddr::IP; # for validation
19 use FS::UID qw(dbh datasrc driver_name);
21 use FS::Schema qw(dbdef);
23 use FS::Msgcat qw(gettext);
24 #use FS::Conf; #dependency loop bs, in install_callback below instead
26 use FS::part_virtual_field;
30 our @encrypt_payby = qw( CARD DCRD CHEK DCHK );
32 #export dbdef for now... everything else expects to find it here
34 dbh fields hfields qsearch qsearchs dbdef jsearch
35 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql concat_sql
40 our $me = '[FS::Record]';
42 our $nowarn_identical = 0;
43 our $nowarn_classload = 0;
44 our $no_update_diff = 0;
46 our $no_check_foreign = 1; #well, not inefficiently in perl by default anymore
54 our $conf_encryption = '';
55 FS::UID->install_callback( sub {
59 $conf = FS::Conf->new;
60 $conf_encryption = $conf->exists('encryption');
61 $money_char = $conf->config('money_char') || '$';
62 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
63 $lat_lower = $nw_coords ? 1 : -90;
64 $lon_upper = $nw_coords ? -1 : 180;
66 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
68 if ( driver_name eq 'Pg' ) {
69 eval "use DBD::Pg ':pg_types'";
72 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
79 FS::Record - Database record objects
84 use FS::Record qw(dbh fields qsearch qsearchs);
86 $record = new FS::Record 'table', \%hash;
87 $record = new FS::Record 'table', { 'column' => 'value', ... };
89 $record = qsearchs FS::Record 'table', \%hash;
90 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
91 @records = qsearch FS::Record 'table', \%hash;
92 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
94 $table = $record->table;
95 $dbdef_table = $record->dbdef_table;
97 $value = $record->get('column');
98 $value = $record->getfield('column');
99 $value = $record->column;
101 $record->set( 'column' => 'value' );
102 $record->setfield( 'column' => 'value' );
103 $record->column('value');
105 %hash = $record->hash;
107 $hashref = $record->hashref;
109 $error = $record->insert;
111 $error = $record->delete;
113 $error = $new_record->replace($old_record);
115 # external use deprecated - handled by the database (at least for Pg, mysql)
116 $value = $record->unique('column');
118 $error = $record->ut_float('column');
119 $error = $record->ut_floatn('column');
120 $error = $record->ut_number('column');
121 $error = $record->ut_numbern('column');
122 $error = $record->ut_snumber('column');
123 $error = $record->ut_snumbern('column');
124 $error = $record->ut_money('column');
125 $error = $record->ut_text('column');
126 $error = $record->ut_textn('column');
127 $error = $record->ut_alpha('column');
128 $error = $record->ut_alphan('column');
129 $error = $record->ut_phonen('column');
130 $error = $record->ut_anything('column');
131 $error = $record->ut_name('column');
133 $quoted_value = _quote($value,'table','field');
136 $fields = hfields('table');
137 if ( $fields->{Field} ) { # etc.
139 @fields = fields 'table'; #as a subroutine
140 @fields = $record->fields; #as a method call
145 (Mostly) object-oriented interface to database records. Records are currently
146 implemented on top of DBI. FS::Record is intended as a base class for
147 table-specific classes to inherit from, i.e. FS::cust_main.
153 =item new [ TABLE, ] HASHREF
155 Creates a new record. It doesn't store it in the database, though. See
156 L<"insert"> for that.
158 Note that the object stores this hash reference, not a distinct copy of the
159 hash it points to. You can ask the object for a copy with the I<hash>
162 TABLE can only be omitted when a dervived class overrides the table method.
168 my $class = ref($proto) || $proto;
170 bless ($self, $class);
172 unless ( defined ( $self->table ) ) {
173 $self->{'Table'} = shift;
174 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
175 unless $nowarn_classload;
178 $self->{'Hash'} = shift;
180 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
181 $self->{'Hash'}{$field}='';
184 $self->_rebless if $self->can('_rebless');
186 $self->{'modified'} = 0;
188 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
195 my $class = ref($proto) || $proto;
197 bless ($self, $class);
199 $self->{'Table'} = shift unless defined ( $self->table );
201 my $hashref = $self->{'Hash'} = shift;
203 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
204 my $obj = $cache->cache->{$hashref->{$cache->key}};
205 $obj->_cache($hashref, $cache) if $obj->can('_cache');
208 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
215 my $class = ref($proto) || $proto;
217 bless ($self, $class);
218 if ( defined $self->table ) {
219 cluck "create constructor is deprecated, use new!";
222 croak "FS::Record::create called (not from a subclass)!";
226 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
228 Searches the database for all records matching (at least) the key/value pairs
229 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
230 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
233 The preferred usage is to pass a hash reference of named parameters:
235 @records = qsearch( {
236 'table' => 'table_name',
237 'hashref' => { 'field' => 'value'
238 'field' => { 'op' => '<',
243 #these are optional...
245 'extra_sql' => 'AND field = ? AND intfield = ?',
246 'extra_param' => [ 'value', [ 5, 'int' ] ],
247 'order_by' => 'ORDER BY something',
248 #'cache_obj' => '', #optional
249 'addl_from' => 'LEFT JOIN othtable USING ( field )',
254 Much code still uses old-style positional parameters, this is also probably
255 fine in the common case where there are only two parameters:
257 my @records = qsearch( 'table', { 'field' => 'value' } );
259 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
260 the individual PARAMS_HASHREF queries
262 ###oops, argh, FS::Record::new only lets us create database fields.
263 #Normal behaviour if SELECT is not specified is `*', as in
264 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
265 #feature where you can specify SELECT - remember, the objects returned,
266 #although blessed into the appropriate `FS::TABLE' package, will only have the
267 #fields you specify. This might have unwanted results if you then go calling
268 #regular FS::TABLE methods
273 my %TYPE = (); #for debugging
276 my($type, $value) = @_;
278 my $bind_type = { TYPE => SQL_VARCHAR };
280 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
282 $bind_type = { TYPE => SQL_INTEGER };
284 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
286 if ( driver_name eq 'Pg' ) {
288 $bind_type = { pg_type => PG_BYTEA };
290 # $bind_type = ? #SQL_VARCHAR could be fine?
293 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
294 #fixed by DBD::Pg 2.11.8
295 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
296 #(make a Tron test first)
297 } elsif ( _is_fs_float( $type, $value ) ) {
299 $bind_type = { TYPE => SQL_DECIMAL };
308 my($type, $value) = @_;
309 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
310 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
318 my( @stable, @record, @cache );
319 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
321 my %union_options = ();
322 if ( ref($_[0]) eq 'ARRAY' ) {
325 foreach my $href ( @$optlist ) {
326 push @stable, ( $href->{'table'} or die "table name is required" );
327 push @record, ( $href->{'hashref'} || {} );
328 push @select, ( $href->{'select'} || '*' );
329 push @extra_sql, ( $href->{'extra_sql'} || '' );
330 push @extra_param, ( $href->{'extra_param'} || [] );
331 push @order_by, ( $href->{'order_by'} || '' );
332 push @cache, ( $href->{'cache_obj'} || '' );
333 push @addl_from, ( $href->{'addl_from'} || '' );
334 push @debug, ( $href->{'debug'} || '' );
336 die "at least one hashref is required" unless scalar(@stable);
337 } elsif ( ref($_[0]) eq 'HASH' ) {
339 $stable[0] = $opt->{'table'} or die "table name is required";
340 $record[0] = $opt->{'hashref'} || {};
341 $select[0] = $opt->{'select'} || '*';
342 $extra_sql[0] = $opt->{'extra_sql'} || '';
343 $extra_param[0] = $opt->{'extra_param'} || [];
344 $order_by[0] = $opt->{'order_by'} || '';
345 $cache[0] = $opt->{'cache_obj'} || '';
346 $addl_from[0] = $opt->{'addl_from'} || '';
347 $debug[0] = $opt->{'debug'} || '';
358 my $cache = $cache[0];
364 foreach my $stable ( @stable ) {
365 #stop altering the caller's hashref
366 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
367 my $select = shift @select;
368 my $extra_sql = shift @extra_sql;
369 my $extra_param = shift @extra_param;
370 my $order_by = shift @order_by;
371 my $cache = shift @cache;
372 my $addl_from = shift @addl_from;
373 my $debug = shift @debug;
375 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
377 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
380 my $table = $cache ? $cache->table : $stable;
381 my $dbdef_table = dbdef->table($table)
382 or die "No schema for table $table found - ".
383 "do you need to run freeside-upgrade?";
384 my $pkey = $dbdef_table->primary_key;
386 my @real_fields = grep exists($record->{$_}), real_fields($table);
388 my $statement .= "SELECT $select FROM $stable";
389 $statement .= " $addl_from" if $addl_from;
390 if ( @real_fields ) {
391 $statement .= ' WHERE '. join(' AND ',
392 get_real_fields($table, $record, \@real_fields));
395 $statement .= " $extra_sql" if defined($extra_sql);
396 $statement .= " $order_by" if defined($order_by);
398 push @statement, $statement;
400 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
404 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
407 my $value = $record->{$field};
408 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
409 $value = $value->{'value'} if ref($value);
410 my $type = dbdef->table($table)->column($field)->type;
412 my $bind_type = _bind_type($type, $value);
416 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
418 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
422 push @bind_type, $bind_type;
426 foreach my $param ( @$extra_param ) {
427 my $bind_type = { TYPE => SQL_VARCHAR };
430 $value = $param->[0];
431 my $type = $param->[1];
432 $bind_type = _bind_type($type, $value);
435 push @bind_type, $bind_type;
439 my $statement = join( ' ) UNION ( ', @statement );
440 $statement = "( $statement )" if scalar(@statement) > 1;
441 $statement .= " $union_options{order_by}" if $union_options{order_by};
443 my $sth = $dbh->prepare($statement)
444 or croak "$dbh->errstr doing $statement";
447 foreach my $value ( @value ) {
448 my $bind_type = shift @bind_type;
449 $sth->bind_param($bind++, $value, $bind_type );
452 # $sth->execute( map $record->{$_},
453 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
454 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
456 my $ok = $sth->execute;
458 my $error = "Error executing \"$statement\"";
459 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
460 $error .= ': '. $sth->errstr;
464 my $table = $stable[0];
466 $table = '' if grep { $_ ne $table } @stable;
467 $pkey = dbdef->table($table)->primary_key if $table;
470 tie %result, "Tie::IxHash";
471 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
472 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
473 %result = map { $_->{$pkey}, $_ } @stuff;
475 @result{@stuff} = @stuff;
481 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
482 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
483 #derivied class didn't override new method, so this optimization is safe
486 new_or_cached( "FS::$table", { %{$_} }, $cache )
490 new( "FS::$table", { %{$_} } )
494 #okay, its been tested
495 # warn "untested code (class FS::$table uses custom new method)";
497 eval 'FS::'. $table. '->new( { %{$_} } )';
501 # Check for encrypted fields and decrypt them.
502 ## only in the local copy, not the cached object
503 if ( $conf_encryption
504 && eval '@FS::'. $table . '::encrypted_fields' ) {
505 foreach my $record (@return) {
506 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
507 next if $field eq 'payinfo'
508 && ($record->isa('FS::payinfo_transaction_Mixin')
509 || $record->isa('FS::payinfo_Mixin') )
511 && !grep { $record->payby eq $_ } @encrypt_payby;
512 # Set it directly... This may cause a problem in the future...
513 $record->setfield($field, $record->decrypt($record->getfield($field)));
518 cluck "warning: FS::$table not loaded; returning FS::Record objects"
519 unless $nowarn_classload;
521 FS::Record->new( $table, { %{$_} } );
529 Construct the SQL statement and parameter-binding list for qsearch. Takes
530 the qsearch parameters.
532 Returns a hash containing:
533 'table': The primary table name (if there is one).
534 'statement': The SQL statement itself.
535 'bind_type': An arrayref of bind types.
536 'value': An arrayref of parameter values.
537 'cache': The cache object, if one was passed.
542 my( @stable, @record, @cache );
543 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
546 my %union_options = ();
547 if ( ref($_[0]) eq 'ARRAY' ) {
550 foreach my $href ( @$optlist ) {
551 push @stable, ( $href->{'table'} or die "table name is required" );
552 push @record, ( $href->{'hashref'} || {} );
553 push @select, ( $href->{'select'} || '*' );
554 push @extra_sql, ( $href->{'extra_sql'} || '' );
555 push @extra_param, ( $href->{'extra_param'} || [] );
556 push @order_by, ( $href->{'order_by'} || '' );
557 push @cache, ( $href->{'cache_obj'} || '' );
558 push @addl_from, ( $href->{'addl_from'} || '' );
559 push @debug, ( $href->{'debug'} || '' );
561 die "at least one hashref is required" unless scalar(@stable);
562 } elsif ( ref($_[0]) eq 'HASH' ) {
564 $stable[0] = $opt->{'table'} or die "table name is required";
565 $record[0] = $opt->{'hashref'} || {};
566 $select[0] = $opt->{'select'} || '*';
567 $extra_sql[0] = $opt->{'extra_sql'} || '';
568 $extra_param[0] = $opt->{'extra_param'} || [];
569 $order_by[0] = $opt->{'order_by'} || '';
570 $cache[0] = $opt->{'cache_obj'} || '';
571 $addl_from[0] = $opt->{'addl_from'} || '';
572 $debug[0] = $opt->{'debug'} || '';
583 my $cache = $cache[0];
589 my $result_table = $stable[0];
590 foreach my $stable ( @stable ) {
591 #stop altering the caller's hashref
592 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
593 my $select = shift @select;
594 my $extra_sql = shift @extra_sql;
595 my $extra_param = shift @extra_param;
596 my $order_by = shift @order_by;
597 my $cache = shift @cache;
598 my $addl_from = shift @addl_from;
599 my $debug = shift @debug;
601 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
603 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
606 $result_table = '' if $result_table ne $stable;
608 my $table = $cache ? $cache->table : $stable;
609 my $dbdef_table = dbdef->table($table)
610 or die "No schema for table $table found - ".
611 "do you need to run freeside-upgrade?";
612 my $pkey = $dbdef_table->primary_key;
614 my @real_fields = grep exists($record->{$_}), real_fields($table);
616 my $statement .= "SELECT $select FROM $stable";
617 $statement .= " $addl_from" if $addl_from;
618 if ( @real_fields ) {
619 $statement .= ' WHERE '. join(' AND ',
620 get_real_fields($table, $record, \@real_fields));
623 $statement .= " $extra_sql" if defined($extra_sql);
624 $statement .= " $order_by" if defined($order_by);
626 push @statement, $statement;
628 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
632 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
635 my $value = $record->{$field};
636 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
637 $value = $value->{'value'} if ref($value);
638 my $type = dbdef->table($table)->column($field)->type;
640 my $bind_type = _bind_type($type, $value);
644 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
646 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
650 push @bind_type, $bind_type;
654 foreach my $param ( @$extra_param ) {
655 my $bind_type = { TYPE => SQL_VARCHAR };
658 $value = $param->[0];
659 my $type = $param->[1];
660 $bind_type = _bind_type($type, $value);
663 push @bind_type, $bind_type;
667 my $statement = join( ' ) UNION ( ', @statement );
668 $statement = "( $statement )" if scalar(@statement) > 1;
669 $statement .= " $union_options{order_by}" if $union_options{order_by};
672 statement => $statement,
673 bind_type => \@bind_type,
675 table => $result_table,
680 # qsearch should eventually use this
682 my ($table, $cache, @hashrefs) = @_;
684 # XXX get rid of these string evals at some point
685 # (when we have time to test it)
686 # my $class = "FS::$table" if $table;
687 # if ( $class and $class->isa('FS::Record') )
688 # if ( $class->can('new') eq \&new )
690 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
691 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
692 #derivied class didn't override new method, so this optimization is safe
695 new_or_cached( "FS::$table", { %{$_} }, $cache )
699 new( "FS::$table", { %{$_} } )
703 #okay, its been tested
704 # warn "untested code (class FS::$table uses custom new method)";
706 eval 'FS::'. $table. '->new( { %{$_} } )';
710 # Check for encrypted fields and decrypt them.
711 ## only in the local copy, not the cached object
712 if ( $conf_encryption
713 && eval '@FS::'. $table . '::encrypted_fields' ) {
714 foreach my $record (@return) {
715 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
716 next if $field eq 'payinfo'
717 && ($record->isa('FS::payinfo_transaction_Mixin')
718 || $record->isa('FS::payinfo_Mixin') )
720 && !grep { $record->payby eq $_ } @encrypt_payby;
721 # Set it directly... This may cause a problem in the future...
722 $record->setfield($field, $record->decrypt($record->getfield($field)));
727 cluck "warning: FS::$table not loaded; returning FS::Record objects"
728 unless $nowarn_classload;
730 FS::Record->new( $table, { %{$_} } );
736 ## makes this easier to read
738 sub get_real_fields {
741 my $real_fields = shift;
743 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
749 my $type = dbdef->table($table)->column($column)->type;
750 my $value = $record->{$column};
751 $value = $value->{'value'} if ref($value);
752 if ( ref($record->{$_}) ) {
753 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
754 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
755 if ( uc($op) eq 'ILIKE' ) {
757 $record->{$_}{'value'} = lc($record->{$_}{'value'});
758 $column = "LOWER($_)";
760 $record->{$_} = $record->{$_}{'value'}
763 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
765 if ( driver_name eq 'Pg' ) {
766 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
767 qq-( $column IS NULL )-;
769 qq-( $column IS NULL OR $column = '' )-;
772 qq-( $column IS NULL OR $column = "" )-;
774 } elsif ( $op eq '!=' ) {
775 if ( driver_name eq 'Pg' ) {
776 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
777 qq-( $column IS NOT NULL )-;
779 qq-( $column IS NOT NULL AND $column != '' )-;
782 qq-( $column IS NOT NULL AND $column != "" )-;
785 if ( driver_name eq 'Pg' ) {
786 qq-( $column $op '' )-;
788 qq-( $column $op "" )-;
791 } elsif ( $op eq '!=' ) {
792 qq-( $column IS NULL OR $column != ? )-;
793 #if this needs to be re-enabled, it needs to use a custom op like
794 #"APPROX=" or something (better name?, not '=', to avoid affecting other
796 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
797 # ( "$column <= ?", "$column >= ?" );
801 } @{ $real_fields } );
804 =item by_key PRIMARY_KEY_VALUE
806 This is a class method that returns the record with the given primary key
807 value. This method is only useful in FS::Record subclasses. For example:
809 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
813 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
818 my ($class, $pkey_value) = @_;
820 my $table = $class->table
821 or croak "No table for $class found";
823 my $dbdef_table = dbdef->table($table)
824 or die "No schema for table $table found - ".
825 "do you need to create it or run dbdef-create?";
826 my $pkey = $dbdef_table->primary_key
827 or die "No primary key for table $table";
829 return qsearchs($table, { $pkey => $pkey_value });
832 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
834 Experimental JOINed search method. Using this method, you can execute a
835 single SELECT spanning multiple tables, and cache the results for subsequent
836 method calls. Interface will almost definately change in an incompatible
844 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
845 my $cache = FS::SearchCache->new( $ptable, $pkey );
848 grep { !$saw{$_->getfield($pkey)}++ }
849 qsearch($table, $record, $select, $extra_sql, $cache )
853 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
855 Same as qsearch, except that if more than one record matches, it B<carp>s but
856 returns the first. If this happens, you either made a logic error in asking
857 for a single item, or your data is corrupted.
861 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
863 my(@result) = qsearch(@_);
864 cluck "warning: Multiple records in scalar search ($table)"
865 if scalar(@result) > 1;
866 #should warn more vehemently if the search was on a primary key?
867 scalar(@result) ? ($result[0]) : ();
878 Returns the table name.
883 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
890 Returns the DBIx::DBSchema::Table object for the table.
896 my($table)=$self->table;
897 dbdef->table($table);
902 Returns the primary key for the table.
908 my $pkey = $self->dbdef_table->primary_key;
911 =item get, getfield COLUMN
913 Returns the value of the column/field/key COLUMN.
918 my($self,$field) = @_;
919 # to avoid "Use of unitialized value" errors
920 if ( defined ( $self->{Hash}->{$field} ) ) {
921 $self->{Hash}->{$field};
931 =item set, setfield COLUMN, VALUE
933 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
938 my($self,$field,$value) = @_;
939 $self->{'modified'} = 1;
940 $self->{'Hash'}->{$field} = $value;
949 Returns true if the column/field/key COLUMN exists.
954 my($self,$field) = @_;
955 exists($self->{Hash}->{$field});
958 =item AUTLOADED METHODS
960 $record->column is a synonym for $record->get('column');
962 $record->column('value') is a synonym for $record->set('column','value');
969 my($field)=$AUTOLOAD;
971 if ( defined($value) ) {
972 confess "errant AUTOLOAD $field for $self (arg $value)"
973 unless blessed($self) && $self->can('setfield');
974 $self->setfield($field,$value);
976 confess "errant AUTOLOAD $field for $self (no args)"
977 unless blessed($self) && $self->can('getfield');
978 $self->getfield($field);
984 # my $field = $AUTOLOAD;
986 # if ( defined($_[1]) ) {
987 # $_[0]->setfield($field, $_[1]);
989 # $_[0]->getfield($field);
995 Returns a list of the column/value pairs, usually for assigning to a new hash.
997 To make a distinct duplicate of an FS::Record object, you can do:
999 $new = new FS::Record ( $old->table, { $old->hash } );
1005 confess $self. ' -> hash: Hash attribute is undefined'
1006 unless defined($self->{'Hash'});
1007 %{ $self->{'Hash'} };
1012 Returns a reference to the column/value hash. This may be deprecated in the
1013 future; if there's a reason you can't just use the autoloaded or get/set
1025 Returns true if any of this object's values have been modified with set (or via
1026 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1033 $self->{'modified'};
1036 =item select_for_update
1038 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1043 sub select_for_update {
1045 my $primary_key = $self->primary_key;
1048 'table' => $self->table,
1049 'hashref' => { $primary_key => $self->$primary_key() },
1050 'extra_sql' => 'FOR UPDATE',
1056 Locks this table with a database-driver specific lock method. This is used
1057 as a mutex in order to do a duplicate search.
1059 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1061 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1063 Errors are fatal; no useful return value.
1065 Note: To use this method for new tables other than svc_acct and svc_phone,
1066 edit freeside-upgrade and add those tables to the duplicate_lock list.
1072 my $table = $self->table;
1074 warn "$me locking $table table\n" if $DEBUG;
1076 if ( driver_name =~ /^Pg/i ) {
1078 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1081 } elsif ( driver_name =~ /^mysql/i ) {
1083 dbh->do("SELECT * FROM duplicate_lock
1084 WHERE lockname = '$table'
1086 ) or die dbh->errstr;
1090 die "unknown database ". driver_name. "; don't know how to lock table";
1094 warn "$me acquired $table table lock\n" if $DEBUG;
1100 Inserts this record to the database. If there is an error, returns the error,
1101 otherwise returns false.
1109 warn "$self -> insert" if $DEBUG;
1111 my $error = $self->check;
1112 return $error if $error;
1114 #single-field non-null unique keys are given a value if empty
1115 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1116 foreach ( $self->dbdef_table->unique_singles) {
1117 next if $self->getfield($_);
1118 next if $self->dbdef_table->column($_)->null eq 'NULL';
1122 #and also the primary key, if the database isn't going to
1123 my $primary_key = $self->dbdef_table->primary_key;
1125 if ( $primary_key ) {
1126 my $col = $self->dbdef_table->column($primary_key);
1129 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1130 || ( driver_name eq 'Pg'
1131 && defined($col->default)
1132 && $col->quoted_default =~ /^nextval\(/i
1134 || ( driver_name eq 'mysql'
1135 && defined($col->local)
1136 && $col->local =~ /AUTO_INCREMENT/i
1138 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1141 my $table = $self->table;
1143 # Encrypt before the database
1144 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
1145 && scalar( eval '@FS::'. $table . '::encrypted_fields')
1146 && $conf->exists('encryption')
1148 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1149 next if $field eq 'payinfo'
1150 && ($self->isa('FS::payinfo_transaction_Mixin')
1151 || $self->isa('FS::payinfo_Mixin') )
1153 && !grep { $self->payby eq $_ } @encrypt_payby;
1154 $saved->{$field} = $self->getfield($field);
1155 $self->setfield($field, $self->encrypt($self->getfield($field)));
1159 #false laziness w/delete
1161 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1164 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1167 my $statement = "INSERT INTO $table ";
1168 if ( @real_fields ) {
1171 join( ', ', @real_fields ).
1173 join( ', ', @values ).
1177 $statement .= 'DEFAULT VALUES';
1179 warn "[debug]$me $statement\n" if $DEBUG > 1;
1180 my $sth = dbh->prepare($statement) or return dbh->errstr;
1182 local $SIG{HUP} = 'IGNORE';
1183 local $SIG{INT} = 'IGNORE';
1184 local $SIG{QUIT} = 'IGNORE';
1185 local $SIG{TERM} = 'IGNORE';
1186 local $SIG{TSTP} = 'IGNORE';
1187 local $SIG{PIPE} = 'IGNORE';
1189 $sth->execute or return $sth->errstr;
1191 # get inserted id from the database, if applicable & needed
1192 if ( $db_seq && ! $self->getfield($primary_key) ) {
1193 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1197 if ( driver_name eq 'Pg' ) {
1199 #my $oid = $sth->{'pg_oid_status'};
1200 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1202 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1203 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1204 dbh->rollback if $FS::UID::AutoCommit;
1205 return "can't parse $table.$primary_key default value".
1206 " for sequence name: $default";
1210 my $i_sql = "SELECT currval('$sequence')";
1211 my $i_sth = dbh->prepare($i_sql) or do {
1212 dbh->rollback if $FS::UID::AutoCommit;
1215 $i_sth->execute() or do { #$i_sth->execute($oid)
1216 dbh->rollback if $FS::UID::AutoCommit;
1217 return $i_sth->errstr;
1219 $insertid = $i_sth->fetchrow_arrayref->[0];
1221 } elsif ( driver_name eq 'mysql' ) {
1223 $insertid = dbh->{'mysql_insertid'};
1224 # work around mysql_insertid being null some of the time, ala RT :/
1225 unless ( $insertid ) {
1226 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1227 "using SELECT LAST_INSERT_ID();";
1228 my $i_sql = "SELECT LAST_INSERT_ID()";
1229 my $i_sth = dbh->prepare($i_sql) or do {
1230 dbh->rollback if $FS::UID::AutoCommit;
1233 $i_sth->execute or do {
1234 dbh->rollback if $FS::UID::AutoCommit;
1235 return $i_sth->errstr;
1237 $insertid = $i_sth->fetchrow_arrayref->[0];
1242 dbh->rollback if $FS::UID::AutoCommit;
1243 return "don't know how to retreive inserted ids from ". driver_name.
1244 ", try using counterfiles (maybe run dbdef-create?)";
1248 $self->setfield($primary_key, $insertid);
1253 if ( defined dbdef->table('h_'. $table) ) {
1254 my $h_statement = $self->_h_statement('insert');
1255 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1256 $h_sth = dbh->prepare($h_statement) or do {
1257 dbh->rollback if $FS::UID::AutoCommit;
1263 $h_sth->execute or return $h_sth->errstr if $h_sth;
1265 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1267 # Now that it has been saved, reset the encrypted fields so that $new
1268 # can still be used.
1269 foreach my $field (keys %{$saved}) {
1270 $self->setfield($field, $saved->{$field});
1278 Depriciated (use insert instead).
1283 cluck "warning: FS::Record::add deprecated!";
1284 insert @_; #call method in this scope
1289 Delete this record from the database. If there is an error, returns the error,
1290 otherwise returns false.
1297 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1299 $self->getfield($_) eq ''
1300 #? "( $_ IS NULL OR $_ = \"\" )"
1301 ? ( driver_name eq 'Pg'
1303 : "( $_ IS NULL OR $_ = \"\" )"
1305 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1306 } ( $self->dbdef_table->primary_key )
1307 ? ( $self->dbdef_table->primary_key)
1308 : real_fields($self->table)
1310 warn "[debug]$me $statement\n" if $DEBUG > 1;
1311 my $sth = dbh->prepare($statement) or return dbh->errstr;
1314 if ( defined dbdef->table('h_'. $self->table) ) {
1315 my $h_statement = $self->_h_statement('delete');
1316 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1317 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1322 my $primary_key = $self->dbdef_table->primary_key;
1324 local $SIG{HUP} = 'IGNORE';
1325 local $SIG{INT} = 'IGNORE';
1326 local $SIG{QUIT} = 'IGNORE';
1327 local $SIG{TERM} = 'IGNORE';
1328 local $SIG{TSTP} = 'IGNORE';
1329 local $SIG{PIPE} = 'IGNORE';
1331 my $rc = $sth->execute or return $sth->errstr;
1332 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1333 $h_sth->execute or return $h_sth->errstr if $h_sth;
1335 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1337 #no need to needlessly destoy the data either (causes problems actually)
1338 #undef $self; #no need to keep object!
1345 Depriciated (use delete instead).
1350 cluck "warning: FS::Record::del deprecated!";
1351 &delete(@_); #call method in this scope
1354 =item replace OLD_RECORD
1356 Replace the OLD_RECORD with this one in the database. If there is an error,
1357 returns the error, otherwise returns false.
1362 my ($new, $old) = (shift, shift);
1364 $old = $new->replace_old unless defined($old);
1366 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1368 if ( $new->can('replace_check') ) {
1369 my $error = $new->replace_check($old);
1370 return $error if $error;
1373 return "Records not in same table!" unless $new->table eq $old->table;
1375 my $primary_key = $old->dbdef_table->primary_key;
1376 return "Can't change primary key $primary_key ".
1377 'from '. $old->getfield($primary_key).
1378 ' to ' . $new->getfield($primary_key)
1380 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1382 my $error = $new->check;
1383 return $error if $error;
1385 # Encrypt for replace
1387 if ( $conf->exists('encryption')
1388 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1389 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1391 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1392 next if $field eq 'payinfo'
1393 && ($new->isa('FS::payinfo_transaction_Mixin')
1394 || $new->isa('FS::payinfo_Mixin') )
1396 && !grep { $new->payby eq $_ } @encrypt_payby;
1397 $saved->{$field} = $new->getfield($field);
1398 $new->setfield($field, $new->encrypt($new->getfield($field)));
1402 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1403 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1404 ? ($_, $new->getfield($_)) : () } $old->fields;
1406 unless (keys(%diff) || $no_update_diff ) {
1407 carp "[warning]$me ". ref($new)."->replace ".
1408 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1409 ": records identical"
1410 unless $nowarn_identical;
1414 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1416 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1417 } real_fields($old->table)
1422 if ( $old->getfield($_) eq '' ) {
1424 #false laziness w/qsearch
1425 if ( driver_name eq 'Pg' ) {
1426 my $type = $old->dbdef_table->column($_)->type;
1427 if ( $type =~ /(int|(big)?serial)/i ) {
1430 qq-( $_ IS NULL OR $_ = '' )-;
1433 qq-( $_ IS NULL OR $_ = "" )-;
1437 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1440 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1443 warn "[debug]$me $statement\n" if $DEBUG > 1;
1444 my $sth = dbh->prepare($statement) or return dbh->errstr;
1447 if ( defined dbdef->table('h_'. $old->table) ) {
1448 my $h_old_statement = $old->_h_statement('replace_old');
1449 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1450 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1456 if ( defined dbdef->table('h_'. $new->table) ) {
1457 my $h_new_statement = $new->_h_statement('replace_new');
1458 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1459 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1464 local $SIG{HUP} = 'IGNORE';
1465 local $SIG{INT} = 'IGNORE';
1466 local $SIG{QUIT} = 'IGNORE';
1467 local $SIG{TERM} = 'IGNORE';
1468 local $SIG{TSTP} = 'IGNORE';
1469 local $SIG{PIPE} = 'IGNORE';
1471 my $rc = $sth->execute or return $sth->errstr;
1472 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1473 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1474 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1476 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1478 # Now that it has been saved, reset the encrypted fields so that $new
1479 # can still be used.
1480 foreach my $field (keys %{$saved}) {
1481 $new->setfield($field, $saved->{$field});
1489 my( $self ) = shift;
1490 warn "[$me] replace called with no arguments; autoloading old record\n"
1493 my $primary_key = $self->dbdef_table->primary_key;
1494 if ( $primary_key ) {
1495 $self->by_key( $self->$primary_key() ) #this is what's returned
1496 or croak "can't find ". $self->table. ".$primary_key ".
1497 $self->$primary_key();
1499 croak $self->table. " has no primary key; pass old record as argument";
1506 Depriciated (use replace instead).
1511 cluck "warning: FS::Record::rep deprecated!";
1512 replace @_; #call method in this scope
1517 Checks custom fields. Subclasses should still provide a check method to validate
1518 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1524 foreach my $field ($self->virtual_fields) {
1525 my $error = $self->ut_textn($field);
1526 return $error if $error;
1531 =item virtual_fields [ TABLE ]
1533 Returns a list of virtual fields defined for the table. This should not
1534 be exported, and should only be called as an instance or class method.
1538 sub virtual_fields {
1541 $table = $self->table or confess "virtual_fields called on non-table";
1543 confess "Unknown table $table" unless dbdef->table($table);
1545 return () unless dbdef->table('part_virtual_field');
1547 unless ( $virtual_fields_cache{$table} ) {
1548 my $concat = [ "'cf_'", "name" ];
1549 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1550 "WHERE dbtable = '$table'";
1552 my $result = $dbh->selectcol_arrayref($query);
1553 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1555 $virtual_fields_cache{$table} = $result;
1558 @{$virtual_fields_cache{$table}};
1562 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1564 Processes a batch import as a queued JSRPC job
1566 JOB is an FS::queue entry.
1568 OPTIONS_HASHREF can have the following keys:
1574 Table name (required).
1578 Listref of field names for static fields. They will be given values from the
1579 PARAMS hashref and passed as a "params" hashref to batch_import.
1583 Formats hashref. Keys are field names, values are listrefs that define the
1586 Each listref value can be a column name or a code reference. Coderefs are run
1587 with the row object, data and a FS::Conf object as the three parameters.
1588 For example, this coderef does the same thing as using the "columnname" string:
1591 my( $record, $data, $conf ) = @_;
1592 $record->columnname( $data );
1595 Coderefs are run after all "column name" fields are assigned.
1599 Optional format hashref of types. Keys are field names, values are "csv",
1600 "xls" or "fixedlength". Overrides automatic determination of file type
1603 =item format_headers
1605 Optional format hashref of header lines. Keys are field names, values are 0
1606 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1609 =item format_sep_chars
1611 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1612 CSV separation character.
1614 =item format_fixedlenth_formats
1616 Optional format hashref of fixed length format defintiions. Keys are field
1617 names, values Parse::FixedLength listrefs of field definitions.
1621 Set true to default to CSV file type if the filename does not contain a
1622 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1627 PARAMS is a base64-encoded Storable string containing the POSTed data as
1628 a hash ref. It normally contains at least one field, "uploaded files",
1629 generated by /elements/file-upload.html and containing the list of uploaded
1630 files. Currently only supports a single file named "file".
1634 use Storable qw(thaw);
1637 sub process_batch_import {
1638 my($job, $opt) = ( shift, shift );
1640 my $table = $opt->{table};
1641 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1642 my %formats = %{ $opt->{formats} };
1644 my $param = thaw(decode_base64(shift));
1645 warn Dumper($param) if $DEBUG;
1647 my $files = $param->{'uploaded_files'}
1648 or die "No files provided.\n";
1650 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1652 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1653 my $file = $dir. $files{'file'};
1658 formats => \%formats,
1659 format_types => $opt->{format_types},
1660 format_headers => $opt->{format_headers},
1661 format_sep_chars => $opt->{format_sep_chars},
1662 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1663 format_xml_formats => $opt->{format_xml_formats},
1664 format_asn_formats => $opt->{format_asn_formats},
1665 format_row_callbacks => $opt->{format_row_callbacks},
1670 format => $param->{format},
1671 params => { map { $_ => $param->{$_} } @pass_params },
1673 default_csv => $opt->{default_csv},
1674 postinsert_callback => $opt->{postinsert_callback},
1677 if ( $opt->{'batch_namecol'} ) {
1678 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1679 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1682 my $error = FS::Record::batch_import( \%iopt );
1686 die "$error\n" if $error;
1689 =item batch_import PARAM_HASHREF
1691 Class method for batch imports. Available params:
1697 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1703 =item format_headers
1705 =item format_sep_chars
1707 =item format_fixedlength_formats
1709 =item format_row_callbacks
1711 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1713 =item preinsert_callback
1715 =item postinsert_callback
1721 FS::queue object, will be updated with progress
1727 csv, xls, fixedlength, xml
1739 warn "$me batch_import call with params: \n". Dumper($param)
1742 my $table = $param->{table};
1744 my $job = $param->{job};
1745 my $file = $param->{file};
1746 my $params = $param->{params} || {};
1748 my( $type, $header, $sep_char,
1749 $fixedlength_format, $xml_format, $asn_format,
1750 $row_callback, @fields );
1752 my $postinsert_callback = '';
1753 $postinsert_callback = $param->{'postinsert_callback'}
1754 if $param->{'postinsert_callback'};
1755 my $preinsert_callback = '';
1756 $preinsert_callback = $param->{'preinsert_callback'}
1757 if $param->{'preinsert_callback'};
1759 if ( $param->{'format'} ) {
1761 my $format = $param->{'format'};
1762 my $formats = $param->{formats};
1763 die "unknown format $format" unless exists $formats->{ $format };
1765 $type = $param->{'format_types'}
1766 ? $param->{'format_types'}{ $format }
1767 : $param->{type} || 'csv';
1770 $header = $param->{'format_headers'}
1771 ? $param->{'format_headers'}{ $param->{'format'} }
1774 $sep_char = $param->{'format_sep_chars'}
1775 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1778 $fixedlength_format =
1779 $param->{'format_fixedlength_formats'}
1780 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1784 $param->{'format_xml_formats'}
1785 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1789 $param->{'format_asn_formats'}
1790 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1794 $param->{'format_row_callbacks'}
1795 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1798 @fields = @{ $formats->{ $format } };
1800 } elsif ( $param->{'fields'} ) {
1802 $type = ''; #infer from filename
1805 $fixedlength_format = '';
1807 @fields = @{ $param->{'fields'} };
1810 die "neither format nor fields specified";
1813 #my $file = $param->{file};
1816 if ( $file =~ /\.(\w+)$/i ) {
1820 warn "can't parse file type from filename $file; defaulting to CSV";
1824 if $param->{'default_csv'} && $type ne 'xls';
1832 my $asn_header_buffer;
1833 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1835 if ( $type eq 'csv' ) {
1837 my %attr = ( 'binary' => 1, );
1838 $attr{sep_char} = $sep_char if $sep_char;
1839 $parser = new Text::CSV_XS \%attr;
1841 } elsif ( $type eq 'fixedlength' ) {
1843 eval "use Parse::FixedLength;";
1845 $parser = Parse::FixedLength->new($fixedlength_format);
1849 die "Unknown file type $type\n";
1852 @buffer = split(/\r?\n/, slurp($file) );
1853 splice(@buffer, 0, ($header || 0) );
1854 $count = scalar(@buffer);
1856 } elsif ( $type eq 'xls' ) {
1858 eval "use Spreadsheet::ParseExcel;";
1861 eval "use DateTime::Format::Excel;";
1862 #for now, just let the error be thrown if it is used, since only CDR
1863 # formats bill_west and troop use it, not other excel-parsing things
1866 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1868 $parser = $excel->{Worksheet}[0]; #first sheet
1870 $count = $parser->{MaxRow} || $parser->{MinRow};
1873 $row = $header || 0;
1875 } elsif ( $type eq 'xml' ) {
1878 eval "use XML::Simple;";
1880 my $xmlrow = $xml_format->{'xmlrow'};
1881 $parser = $xml_format->{'xmlkeys'};
1882 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1883 my $data = XML::Simple::XMLin(
1885 'SuppressEmpty' => '', #sets empty values to ''
1889 $rows = $rows->{$_} foreach @$xmlrow;
1890 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1891 $count = @buffer = @$rows;
1893 } elsif ( $type eq 'asn.1' ) {
1895 eval "use Convert::ASN1";
1898 my $asn = Convert::ASN1->new;
1899 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1901 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1903 my $data = slurp($file);
1904 my $asn_output = $parser->decode( $data )
1905 or return "No ". $asn_format->{'macro'}. " found\n";
1907 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1909 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1910 $count = @buffer = @$rows;
1913 die "Unknown file type $type\n";
1918 local $SIG{HUP} = 'IGNORE';
1919 local $SIG{INT} = 'IGNORE';
1920 local $SIG{QUIT} = 'IGNORE';
1921 local $SIG{TERM} = 'IGNORE';
1922 local $SIG{TSTP} = 'IGNORE';
1923 local $SIG{PIPE} = 'IGNORE';
1925 my $oldAutoCommit = $FS::UID::AutoCommit;
1926 local $FS::UID::AutoCommit = 0;
1929 #my $params = $param->{params} || {};
1930 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1931 my $batch_col = $param->{'batch_keycol'};
1933 my $batch_class = 'FS::'. $param->{'batch_table'};
1934 my $batch = $batch_class->new({
1935 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1937 my $error = $batch->insert;
1939 $dbh->rollback if $oldAutoCommit;
1940 return "can't insert batch record: $error";
1942 #primary key via dbdef? (so the column names don't have to match)
1943 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1945 $params->{ $batch_col } = $batch_value;
1948 #my $job = $param->{job};
1951 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1955 my %hash = %$params;
1956 if ( $type eq 'csv' ) {
1958 last unless scalar(@buffer);
1959 $line = shift(@buffer);
1961 next if $line =~ /^\s*$/; #skip empty lines
1963 $line = &{$row_callback}($line) if $row_callback;
1965 next if $line =~ /^\s*$/; #skip empty lines
1967 $parser->parse($line) or do {
1968 $dbh->rollback if $oldAutoCommit;
1969 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
1971 @columns = $parser->fields();
1973 } elsif ( $type eq 'fixedlength' ) {
1975 last unless scalar(@buffer);
1976 $line = shift(@buffer);
1978 @columns = $parser->parse($line);
1980 } elsif ( $type eq 'xls' ) {
1982 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1983 || ! $parser->{Cells}[$row];
1985 my @row = @{ $parser->{Cells}[$row] };
1986 @columns = map $_->{Val}, @row;
1989 #warn $z++. ": $_\n" for @columns;
1991 } elsif ( $type eq 'xml' ) {
1993 # $parser = [ 'Column0Key', 'Column1Key' ... ]
1994 last unless scalar(@buffer);
1995 my $row = shift @buffer;
1996 @columns = @{ $row }{ @$parser };
1998 } elsif ( $type eq 'asn.1' ) {
2000 last unless scalar(@buffer);
2001 my $row = shift @buffer;
2002 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2003 if $asn_format->{row_callback};
2004 foreach my $key ( keys %{ $asn_format->{map} } ) {
2005 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2009 die "Unknown file type $type\n";
2014 foreach my $field ( @fields ) {
2016 my $value = shift @columns;
2018 if ( ref($field) eq 'CODE' ) {
2019 #&{$field}(\%hash, $value);
2020 push @later, $field, $value;
2022 #??? $hash{$field} = $value if length($value);
2023 $hash{$field} = $value if defined($value) && length($value);
2028 #my $table = $param->{table};
2029 my $class = "FS::$table";
2031 my $record = $class->new( \%hash );
2034 while ( scalar(@later) ) {
2035 my $sub = shift @later;
2036 my $data = shift @later;
2038 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2041 $dbh->rollback if $oldAutoCommit;
2042 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2044 last if exists( $param->{skiprow} );
2046 next if exists( $param->{skiprow} );
2048 if ( $preinsert_callback ) {
2049 my $error = &{$preinsert_callback}($record, $param);
2051 $dbh->rollback if $oldAutoCommit;
2052 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2055 next if exists $param->{skiprow} && $param->{skiprow};
2058 my $error = $record->insert;
2061 $dbh->rollback if $oldAutoCommit;
2062 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2068 if ( $postinsert_callback ) {
2069 my $error = &{$postinsert_callback}($record, $param);
2071 $dbh->rollback if $oldAutoCommit;
2072 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2077 if ( $job && time - $min_sec > $last ) { #progress bar
2078 $job->update_statustext( int(100 * $imported / $count) );
2084 unless ( $imported || $param->{empty_ok} ) {
2085 $dbh->rollback if $oldAutoCommit;
2086 return "Empty file!";
2089 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2096 my( $self, $action, $time ) = @_;
2100 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2103 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2104 real_fields($self->table);
2107 # If we're encrypting then don't store the payinfo in the history
2108 if ( $conf && $conf->exists('encryption') && $self->table ne 'banned_pay' ) {
2109 @fields = grep { $_ ne 'payinfo' } @fields;
2112 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2114 "INSERT INTO h_". $self->table. " ( ".
2115 join(', ', qw(history_date history_usernum history_action), @fields ).
2118 $FS::CurrentUser::CurrentUser->usernum,
2119 dbh->quote($action),
2128 B<Warning>: External use is B<deprecated>.
2130 Replaces COLUMN in record with a unique number, using counters in the
2131 filesystem. Used by the B<insert> method on single-field unique columns
2132 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2133 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2135 Returns the new value.
2140 my($self,$field) = @_;
2141 my($table)=$self->table;
2143 croak "Unique called on field $field, but it is ",
2144 $self->getfield($field),
2146 if $self->getfield($field);
2148 #warn "table $table is tainted" if is_tainted($table);
2149 #warn "field $field is tainted" if is_tainted($field);
2151 my($counter) = new File::CounterFile "$table.$field",0;
2153 my $index = $counter->inc;
2154 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2156 $index =~ /^(\d*)$/;
2159 $self->setfield($field,$index);
2163 =item ut_float COLUMN
2165 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2166 null. If there is an error, returns the error, otherwise returns false.
2171 my($self,$field)=@_ ;
2172 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2173 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2174 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2175 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2176 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2177 $self->setfield($field,$1);
2180 =item ut_floatn COLUMN
2182 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2183 null. If there is an error, returns the error, otherwise returns false.
2187 #false laziness w/ut_ipn
2189 my( $self, $field ) = @_;
2190 if ( $self->getfield($field) =~ /^()$/ ) {
2191 $self->setfield($field,'');
2194 $self->ut_float($field);
2198 =item ut_sfloat COLUMN
2200 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2201 May not be null. If there is an error, returns the error, otherwise returns
2207 my($self,$field)=@_ ;
2208 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2209 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2210 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2211 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2212 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2213 $self->setfield($field,$1);
2216 =item ut_sfloatn COLUMN
2218 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2219 null. If there is an error, returns the error, otherwise returns false.
2224 my( $self, $field ) = @_;
2225 if ( $self->getfield($field) =~ /^()$/ ) {
2226 $self->setfield($field,'');
2229 $self->ut_sfloat($field);
2233 =item ut_snumber COLUMN
2235 Check/untaint signed numeric data (whole numbers). If there is an error,
2236 returns the error, otherwise returns false.
2241 my($self, $field) = @_;
2242 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2243 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2244 $self->setfield($field, "$1$2");
2248 =item ut_snumbern COLUMN
2250 Check/untaint signed numeric data (whole numbers). If there is an error,
2251 returns the error, otherwise returns false.
2256 my($self, $field) = @_;
2257 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2258 or return "Illegal (numeric) $field: ". $self->getfield($field);
2260 return "Illegal (numeric) $field: ". $self->getfield($field)
2263 $self->setfield($field, "$1$2");
2267 =item ut_number COLUMN
2269 Check/untaint simple numeric data (whole numbers). May not be null. If there
2270 is an error, returns the error, otherwise returns false.
2275 my($self,$field)=@_;
2276 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2277 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2278 $self->setfield($field,$1);
2282 =item ut_numbern COLUMN
2284 Check/untaint simple numeric data (whole numbers). May be null. If there is
2285 an error, returns the error, otherwise returns false.
2290 my($self,$field)=@_;
2291 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2292 or return "Illegal (numeric) $field: ". $self->getfield($field);
2293 $self->setfield($field,$1);
2297 =item ut_money COLUMN
2299 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2300 is an error, returns the error, otherwise returns false.
2305 my($self,$field)=@_;
2307 if ( $self->getfield($field) eq '' ) {
2308 $self->setfield($field, 0);
2309 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2310 #handle one decimal place without barfing out
2311 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2312 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2313 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2315 return "Illegal (money) $field: ". $self->getfield($field);
2321 =item ut_moneyn COLUMN
2323 Check/untaint monetary numbers. May be negative. If there
2324 is an error, returns the error, otherwise returns false.
2329 my($self,$field)=@_;
2330 if ($self->getfield($field) eq '') {
2331 $self->setfield($field, '');
2334 $self->ut_money($field);
2337 =item ut_currencyn COLUMN
2339 Check/untaint currency indicators, such as USD or EUR. May be null. If there
2340 is an error, returns the error, otherwise returns false.
2345 my($self, $field) = @_;
2346 if ($self->getfield($field) eq '') { #can be null
2347 $self->setfield($field, '');
2350 $self->ut_currency($field);
2353 =item ut_currency COLUMN
2355 Check/untaint currency indicators, such as USD or EUR. May not be null. If
2356 there is an error, returns the error, otherwise returns false.
2361 my($self, $field) = @_;
2362 my $value = uc( $self->getfield($field) );
2363 if ( code2currency($value) ) {
2364 $self->setfield($value);
2366 return "Unknown currency $value";
2372 =item ut_text COLUMN
2374 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2375 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2376 May not be null. If there is an error, returns the error, otherwise returns
2382 my($self,$field)=@_;
2383 #warn "msgcat ". \&msgcat. "\n";
2384 #warn "notexist ". \¬exist. "\n";
2385 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2386 $self->getfield($field)
2387 =~ /^([\wô \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2388 or return gettext('illegal_or_empty_text'). " $field: ".
2389 $self->getfield($field);
2390 $self->setfield($field,$1);
2394 =item ut_textn COLUMN
2396 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2397 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2398 May be null. If there is an error, returns the error, otherwise returns false.
2403 my($self,$field)=@_;
2404 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2405 $self->ut_text($field);
2408 =item ut_alpha COLUMN
2410 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2411 an error, returns the error, otherwise returns false.
2416 my($self,$field)=@_;
2417 $self->getfield($field) =~ /^(\w+)$/
2418 or return "Illegal or empty (alphanumeric) $field: ".
2419 $self->getfield($field);
2420 $self->setfield($field,$1);
2424 =item ut_alphan COLUMN
2426 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2427 error, returns the error, otherwise returns false.
2432 my($self,$field)=@_;
2433 $self->getfield($field) =~ /^(\w*)$/
2434 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2435 $self->setfield($field,$1);
2439 =item ut_alphasn COLUMN
2441 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2442 an error, returns the error, otherwise returns false.
2447 my($self,$field)=@_;
2448 $self->getfield($field) =~ /^([\w ]*)$/
2449 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2450 $self->setfield($field,$1);
2455 =item ut_alpha_lower COLUMN
2457 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2458 there is an error, returns the error, otherwise returns false.
2462 sub ut_alpha_lower {
2463 my($self,$field)=@_;
2464 $self->getfield($field) =~ /[[:upper:]]/
2465 and return "Uppercase characters are not permitted in $field";
2466 $self->ut_alpha($field);
2469 =item ut_phonen COLUMN [ COUNTRY ]
2471 Check/untaint phone numbers. May be null. If there is an error, returns
2472 the error, otherwise returns false.
2474 Takes an optional two-letter ISO country code; without it or with unsupported
2475 countries, ut_phonen simply calls ut_alphan.
2480 my( $self, $field, $country ) = @_;
2481 return $self->ut_alphan($field) unless defined $country;
2482 my $phonen = $self->getfield($field);
2483 if ( $phonen eq '' ) {
2484 $self->setfield($field,'');
2485 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2487 $phonen = $conf->config('cust_main-default_areacode').$phonen
2488 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2489 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2490 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2491 $phonen = "$1-$2-$3";
2492 $phonen .= " x$4" if $4;
2493 $self->setfield($field,$phonen);
2495 warn "warning: don't know how to check phone numbers for country $country";
2496 return $self->ut_textn($field);
2503 Check/untaint hexadecimal values.
2508 my($self, $field) = @_;
2509 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2510 or return "Illegal (hex) $field: ". $self->getfield($field);
2511 $self->setfield($field, uc($1));
2515 =item ut_hexn COLUMN
2517 Check/untaint hexadecimal values. May be null.
2522 my($self, $field) = @_;
2523 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2524 or return "Illegal (hex) $field: ". $self->getfield($field);
2525 $self->setfield($field, uc($1));
2529 =item ut_mac_addr COLUMN
2531 Check/untaint mac addresses. May be null.
2536 my($self, $field) = @_;
2538 my $mac = $self->get($field);
2541 $self->set($field, $mac);
2543 my $e = $self->ut_hex($field);
2546 return "Illegal (mac address) $field: ". $self->getfield($field)
2547 unless length($self->getfield($field)) == 12;
2553 =item ut_mac_addrn COLUMN
2555 Check/untaint mac addresses. May be null.
2560 my($self, $field) = @_;
2561 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2566 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2572 my( $self, $field ) = @_;
2573 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2574 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2575 or return "Illegal (IP address) $field: ". $self->getfield($field);
2576 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2577 $self->setfield($field, "$1.$2.$3.$4");
2583 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2584 to 127.0.0.1. May be null.
2589 my( $self, $field ) = @_;
2590 if ( $self->getfield($field) =~ /^()$/ ) {
2591 $self->setfield($field,'');
2594 $self->ut_ip($field);
2598 =item ut_ip46 COLUMN
2600 Check/untaint IPv4 or IPv6 address.
2605 my( $self, $field ) = @_;
2606 my $ip = NetAddr::IP->new($self->getfield($field))
2607 or return "Illegal (IP address) $field: ".$self->getfield($field);
2608 $self->setfield($field, lc($ip->addr));
2614 Check/untaint IPv6 or IPv6 address. May be null.
2619 my( $self, $field ) = @_;
2620 if ( $self->getfield($field) =~ /^$/ ) {
2621 $self->setfield($field, '');
2624 $self->ut_ip46($field);
2627 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2629 Check/untaint coordinates.
2630 Accepts the following forms:
2640 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2641 The latter form (that is, the MMM are thousands of minutes) is
2642 assumed if the "MMM" is exactly three digits or two digits > 59.
2644 To be safe, just use the DDD.DDDDD form.
2646 If LOWER or UPPER are specified, then the coordinate is checked
2647 for lower and upper bounds, respectively.
2652 my ($self, $field) = (shift, shift);
2655 if ( $field =~ /latitude/ ) {
2656 $lower = $lat_lower;
2658 } elsif ( $field =~ /longitude/ ) {
2660 $upper = $lon_upper;
2663 my $coord = $self->getfield($field);
2664 my $neg = $coord =~ s/^(-)//;
2666 my ($d, $m, $s) = (0, 0, 0);
2669 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2670 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2671 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2673 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2676 return "Invalid (coordinate with minutes > 59) $field: "
2677 . $self->getfield($field);
2680 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2682 if (defined($lower) and ($coord < $lower)) {
2683 return "Invalid (coordinate < $lower) $field: "
2684 . $self->getfield($field);;
2687 if (defined($upper) and ($coord > $upper)) {
2688 return "Invalid (coordinate > $upper) $field: "
2689 . $self->getfield($field);;
2692 $self->setfield($field, $coord);
2696 return "Invalid (coordinate) $field: " . $self->getfield($field);
2700 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2702 Same as ut_coord, except optionally null.
2708 my ($self, $field) = (shift, shift);
2710 if ($self->getfield($field) =~ /^\s*$/) {
2713 return $self->ut_coord($field, @_);
2718 =item ut_domain COLUMN
2720 Check/untaint host and domain names. May not be null.
2725 my( $self, $field ) = @_;
2726 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2727 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2728 or return "Illegal (hostname) $field: ". $self->getfield($field);
2729 $self->setfield($field,$1);
2733 =item ut_domainn COLUMN
2735 Check/untaint host and domain names. May be null.
2740 my( $self, $field ) = @_;
2741 if ( $self->getfield($field) =~ /^()$/ ) {
2742 $self->setfield($field,'');
2745 $self->ut_domain($field);
2749 =item ut_name COLUMN
2751 Check/untaint proper names; allows alphanumerics, spaces and the following
2752 punctuation: , . - '
2759 my( $self, $field ) = @_;
2760 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2761 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2762 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2767 $self->setfield($field, $name);
2771 =item ut_namen COLUMN
2773 Check/untaint proper names; allows alphanumerics, spaces and the following
2774 punctuation: , . - '
2781 my( $self, $field ) = @_;
2782 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2783 $self->ut_name($field);
2788 Check/untaint zip codes.
2792 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2795 my( $self, $field, $country ) = @_;
2797 if ( $country eq 'US' ) {
2799 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2800 or return gettext('illegal_zip'). " $field for country $country: ".
2801 $self->getfield($field);
2802 $self->setfield($field, $1);
2804 } elsif ( $country eq 'CA' ) {
2806 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2807 or return gettext('illegal_zip'). " $field for country $country: ".
2808 $self->getfield($field);
2809 $self->setfield($field, "$1 $2");
2813 if ( $self->getfield($field) =~ /^\s*$/
2814 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2817 $self->setfield($field,'');
2819 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2820 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2821 $self->setfield($field,$1);
2829 =item ut_country COLUMN
2831 Check/untaint country codes. Country names are changed to codes, if possible -
2832 see L<Locale::Country>.
2837 my( $self, $field ) = @_;
2838 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2839 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2840 && country2code($1) ) {
2841 $self->setfield($field,uc(country2code($1)));
2844 $self->getfield($field) =~ /^(\w\w)$/
2845 or return "Illegal (country) $field: ". $self->getfield($field);
2846 $self->setfield($field,uc($1));
2850 =item ut_anything COLUMN
2852 Untaints arbitrary data. Be careful.
2857 my( $self, $field ) = @_;
2858 $self->getfield($field) =~ /^(.*)$/s
2859 or return "Illegal $field: ". $self->getfield($field);
2860 $self->setfield($field,$1);
2864 =item ut_enum COLUMN CHOICES_ARRAYREF
2866 Check/untaint a column, supplying all possible choices, like the "enum" type.
2871 my( $self, $field, $choices ) = @_;
2872 foreach my $choice ( @$choices ) {
2873 if ( $self->getfield($field) eq $choice ) {
2874 $self->setfield($field, $choice);
2878 return "Illegal (enum) field $field: ". $self->getfield($field);
2881 =item ut_enumn COLUMN CHOICES_ARRAYREF
2883 Like ut_enum, except the null value is also allowed.
2888 my( $self, $field, $choices ) = @_;
2889 $self->getfield($field)
2890 ? $self->ut_enum($field, $choices)
2894 =item ut_flag COLUMN
2896 Check/untaint a column if it contains either an empty string or 'Y'. This
2897 is the standard form for boolean flags in Freeside.
2902 my( $self, $field ) = @_;
2903 my $value = uc($self->getfield($field));
2904 if ( $value eq '' or $value eq 'Y' ) {
2905 $self->setfield($field, $value);
2908 return "Illegal (flag) field $field: $value";
2911 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2913 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2914 on the column first.
2918 sub ut_foreign_key {
2919 my( $self, $field, $table, $foreign ) = @_;
2920 return '' if $no_check_foreign;
2921 qsearchs($table, { $foreign => $self->getfield($field) })
2922 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2923 " in $table.$foreign";
2927 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2929 Like ut_foreign_key, except the null value is also allowed.
2933 sub ut_foreign_keyn {
2934 my( $self, $field, $table, $foreign ) = @_;
2935 $self->getfield($field)
2936 ? $self->ut_foreign_key($field, $table, $foreign)
2940 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2942 Checks this column as an agentnum, taking into account the current users's
2943 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2944 right or rights allowing no agentnum.
2948 sub ut_agentnum_acl {
2949 my( $self, $field ) = (shift, shift);
2950 my $null_acl = scalar(@_) ? shift : [];
2951 $null_acl = [ $null_acl ] unless ref($null_acl);
2953 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2954 return "Illegal agentnum: $error" if $error;
2956 my $curuser = $FS::CurrentUser::CurrentUser;
2958 if ( $self->$field() ) {
2960 return "Access denied"
2961 unless $curuser->agentnum($self->$field());
2965 return "Access denied"
2966 unless grep $curuser->access_right($_), @$null_acl;
2974 =item fields [ TABLE ]
2976 This is a wrapper for real_fields. Code that called
2977 fields before should probably continue to call fields.
2982 my $something = shift;
2984 if($something->isa('FS::Record')) {
2985 $table = $something->table;
2987 $table = $something;
2988 $something = "FS::$table";
2990 return (real_fields($table));
2994 =item encrypt($value)
2996 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2998 Returns the encrypted string.
3000 You should generally not have to worry about calling this, as the system handles this for you.
3005 my ($self, $value) = @_;
3008 if ($conf->exists('encryption')) {
3009 if ($self->is_encrypted($value)) {
3010 # Return the original value if it isn't plaintext.
3011 $encrypted = $value;
3014 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3015 # RSA doesn't like the empty string so let's pack it up
3016 # The database doesn't like the RSA data so uuencode it
3017 my $length = length($value)+1;
3018 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3020 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3027 =item is_encrypted($value)
3029 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3035 my ($self, $value) = @_;
3036 # could be more precise about it, but this will do for now
3037 $value =~ /^M/ && length($value) > 80;
3040 =item decrypt($value)
3042 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3044 You should generally not have to worry about calling this, as the system handles this for you.
3049 my ($self,$value) = @_;
3050 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3051 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
3053 if (ref($rsa_decrypt) =~ /::RSA/) {
3054 my $encrypted = unpack ("u*", $value);
3055 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3056 if ($@) {warn "Decryption Failed"};
3064 #Initialize the Module
3065 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3067 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
3068 $rsa_module = $conf->config('encryptionmodule');
3072 eval ("require $rsa_module"); # No need to import the namespace
3075 # Initialize Encryption
3076 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
3077 my $public_key = join("\n",$conf->config('encryptionpublickey'));
3078 $rsa_encrypt = $rsa_module->new_public_key($public_key);
3081 # Intitalize Decryption
3082 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
3083 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
3084 $rsa_decrypt = $rsa_module->new_private_key($private_key);
3088 =item h_search ACTION
3090 Given an ACTION, either "insert", or "delete", returns the appropriate history
3091 record corresponding to this record, if any.
3096 my( $self, $action ) = @_;
3098 my $table = $self->table;
3101 my $primary_key = dbdef->table($table)->primary_key;
3104 'table' => "h_$table",
3105 'hashref' => { $primary_key => $self->$primary_key(),
3106 'history_action' => $action,
3114 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3115 appropriate history record corresponding to this record, if any.
3120 my($self, $action) = @_;
3121 my $h = $self->h_search($action);
3122 $h ? $h->history_date : '';
3125 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3127 A class or object method. Executes the sql statement represented by SQL and
3128 returns a scalar representing the result: the first column of the first row.
3130 Dies on bogus SQL. Returns an empty string if no row is returned.
3132 Typically used for statments which return a single value such as "SELECT
3133 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3138 my($self, $sql) = (shift, shift);
3139 my $sth = dbh->prepare($sql) or die dbh->errstr;
3141 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3142 my $row = $sth->fetchrow_arrayref or return '';
3143 my $scalar = $row->[0];
3144 defined($scalar) ? $scalar : '';
3147 =item count [ WHERE ]
3149 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3150 with optional WHERE. Must be called as method on a class with an
3156 my($self, $where) = (shift, shift);
3157 my $table = $self->table or die 'count called on object of class '.ref($self);
3158 my $sql = "SELECT COUNT(*) FROM $table";
3159 $sql .= " WHERE $where" if $where;
3160 $self->scalar_sql($sql);
3169 =item real_fields [ TABLE ]
3171 Returns a list of the real columns in the specified table. Called only by
3172 fields() and other subroutines elsewhere in FS::Record.
3179 my($table_obj) = dbdef->table($table);
3180 confess "Unknown table $table" unless $table_obj;
3181 $table_obj->columns;
3184 =item pvf FIELD_NAME
3186 Returns the FS::part_virtual_field object corresponding to a field in the
3187 record (specified by FIELD_NAME).
3192 my ($self, $name) = (shift, shift);
3194 if(grep /^$name$/, $self->virtual_fields) {
3196 my $concat = [ "'cf_'", "name" ];
3197 return qsearchs({ table => 'part_virtual_field',
3198 hashref => { dbtable => $self->table,
3201 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3207 =item _quote VALUE, TABLE, COLUMN
3209 This is an internal function used to construct SQL statements. It returns
3210 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3211 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3216 my($value, $table, $column) = @_;
3217 my $column_obj = dbdef->table($table)->column($column);
3218 my $column_type = $column_obj->type;
3219 my $nullable = $column_obj->null;
3221 warn " $table.$column: $value ($column_type".
3222 ( $nullable ? ' NULL' : ' NOT NULL' ).
3223 ")\n" if $DEBUG > 2;
3225 if ( $value eq '' && $nullable ) {
3227 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3228 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3231 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3232 ! $column_type =~ /(char|binary|text)$/i ) {
3234 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3235 && driver_name eq 'Pg'
3239 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3240 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3241 # single-quote the whole mess, and put an "E" in front.
3242 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3250 This is deprecated. Don't use it.
3252 It returns a hash-type list with the fields of this record's table set true.
3257 carp "warning: hfields is deprecated";
3260 foreach (fields($table)) {
3269 "$_: ". $self->getfield($_). "|"
3270 } (fields($self->table)) );
3273 sub DESTROY { return; }
3277 # #use Carp qw(cluck);
3278 # #cluck "DESTROYING $self";
3279 # warn "DESTROYING $self";
3283 # return ! eval { join('',@_), kill 0; 1; };
3286 =item str2time_sql [ DRIVER_NAME ]
3288 Returns a function to convert to unix time based on database type, such as
3289 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3290 the str2time_sql_closing method to return a closing string rather than just
3291 using a closing parenthesis as previously suggested.
3293 You can pass an optional driver name such as "Pg", "mysql" or
3294 $dbh->{Driver}->{Name} to return a function for that database instead of
3295 the current database.
3300 my $driver = shift || driver_name;
3302 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3303 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3305 warn "warning: unknown database type $driver; guessing how to convert ".
3306 "dates to UNIX timestamps";
3307 return 'EXTRACT(EPOCH FROM ';
3311 =item str2time_sql_closing [ DRIVER_NAME ]
3313 Returns the closing suffix of a function to convert to unix time based on
3314 database type, such as ")::integer" for Pg or ")" for mysql.
3316 You can pass an optional driver name such as "Pg", "mysql" or
3317 $dbh->{Driver}->{Name} to return a function for that database instead of
3318 the current database.
3322 sub str2time_sql_closing {
3323 my $driver = shift || driver_name;
3325 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3329 =item regexp_sql [ DRIVER_NAME ]
3331 Returns the operator to do a regular expression comparison based on database
3332 type, such as '~' for Pg or 'REGEXP' for mysql.
3334 You can pass an optional driver name such as "Pg", "mysql" or
3335 $dbh->{Driver}->{Name} to return a function for that database instead of
3336 the current database.
3341 my $driver = shift || driver_name;
3343 return '~' if $driver =~ /^Pg/i;
3344 return 'REGEXP' if $driver =~ /^mysql/i;
3346 die "don't know how to use regular expressions in ". driver_name." databases";
3350 =item not_regexp_sql [ DRIVER_NAME ]
3352 Returns the operator to do a regular expression negation based on database
3353 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3355 You can pass an optional driver name such as "Pg", "mysql" or
3356 $dbh->{Driver}->{Name} to return a function for that database instead of
3357 the current database.
3361 sub not_regexp_sql {
3362 my $driver = shift || driver_name;
3364 return '!~' if $driver =~ /^Pg/i;
3365 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3367 die "don't know how to use regular expressions in ". driver_name." databases";
3371 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3373 Returns the items concatenated based on database type, using "CONCAT()" for
3374 mysql and " || " for Pg and other databases.
3376 You can pass an optional driver name such as "Pg", "mysql" or
3377 $dbh->{Driver}->{Name} to return a function for that database instead of
3378 the current database.
3383 my $driver = ref($_[0]) ? driver_name : shift;
3386 if ( $driver =~ /^mysql/i ) {
3387 'CONCAT('. join(',', @$items). ')';
3389 join('||', @$items);
3394 =item midnight_sql DATE
3396 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3397 on that day in the system timezone, using the default driver name.
3402 my $driver = driver_name;
3404 if ( $driver =~ /^mysql/i ) {
3405 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3408 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3416 This module should probably be renamed, since much of the functionality is
3417 of general use. It is not completely unlike Adapter::DBI (see below).
3419 Exported qsearch and qsearchs should be deprecated in favor of method calls
3420 (against an FS::Record object like the old search and searchs that qsearch
3421 and qsearchs were on top of.)
3423 The whole fields / hfields mess should be removed.
3425 The various WHERE clauses should be subroutined.
3427 table string should be deprecated in favor of DBIx::DBSchema::Table.
3429 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3430 true maps to the database (and WHERE clauses) would also help.
3432 The ut_ methods should ask the dbdef for a default length.
3434 ut_sqltype (like ut_varchar) should all be defined
3436 A fallback check method should be provided which uses the dbdef.
3438 The ut_money method assumes money has two decimal digits.
3440 The Pg money kludge in the new method only strips `$'.
3442 The ut_phonen method only checks US-style phone numbers.
3444 The _quote function should probably use ut_float instead of a regex.
3446 All the subroutines probably should be methods, here or elsewhere.
3448 Probably should borrow/use some dbdef methods where appropriate (like sub
3451 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3452 or allow it to be set. Working around it is ugly any way around - DBI should
3453 be fixed. (only affects RDBMS which return uppercase column names)
3455 ut_zip should take an optional country like ut_phone.
3459 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3461 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.