4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 $conf $conf_encryption $money_char $lat_lower $lon_upper
8 $nowarn_identical $nowarn_classload
9 $no_update_diff $no_history $no_check_foreign
13 use Carp qw(carp cluck croak confess);
14 use Scalar::Util qw( blessed );
15 use File::CounterFile;
18 use File::Slurp qw( slurp );
19 use DBI qw(:sql_types);
20 use DBIx::DBSchema 0.38;
21 use FS::UID qw(dbh getotaker datasrc driver_name);
23 use FS::Schema qw(dbdef);
25 use FS::Msgcat qw(gettext);
26 use NetAddr::IP; # for validation
28 #use FS::Conf; #dependency loop bs, in install_callback below instead
30 use FS::part_virtual_field;
36 @encrypt_payby = qw( CARD DCRD CHEK DCHK );
38 #export dbdef for now... everything else expects to find it here
40 dbh fields hfields qsearch qsearchs dbdef jsearch
41 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql concat_sql
48 $nowarn_identical = 0;
49 $nowarn_classload = 0;
52 $no_check_foreign = 0;
60 $conf_encryption = '';
61 FS::UID->install_callback( sub {
65 $conf = FS::Conf->new;
66 $conf_encryption = $conf->exists('encryption');
67 $money_char = $conf->config('money_char') || '$';
68 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
69 $lat_lower = $nw_coords ? 1 : -90;
70 $lon_upper = $nw_coords ? -1 : 180;
72 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
74 if ( driver_name eq 'Pg' ) {
75 eval "use DBD::Pg ':pg_types'";
78 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
85 FS::Record - Database record objects
90 use FS::Record qw(dbh fields qsearch qsearchs);
92 $record = new FS::Record 'table', \%hash;
93 $record = new FS::Record 'table', { 'column' => 'value', ... };
95 $record = qsearchs FS::Record 'table', \%hash;
96 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
97 @records = qsearch FS::Record 'table', \%hash;
98 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
100 $table = $record->table;
101 $dbdef_table = $record->dbdef_table;
103 $value = $record->get('column');
104 $value = $record->getfield('column');
105 $value = $record->column;
107 $record->set( 'column' => 'value' );
108 $record->setfield( 'column' => 'value' );
109 $record->column('value');
111 %hash = $record->hash;
113 $hashref = $record->hashref;
115 $error = $record->insert;
117 $error = $record->delete;
119 $error = $new_record->replace($old_record);
121 # external use deprecated - handled by the database (at least for Pg, mysql)
122 $value = $record->unique('column');
124 $error = $record->ut_float('column');
125 $error = $record->ut_floatn('column');
126 $error = $record->ut_number('column');
127 $error = $record->ut_numbern('column');
128 $error = $record->ut_snumber('column');
129 $error = $record->ut_snumbern('column');
130 $error = $record->ut_money('column');
131 $error = $record->ut_text('column');
132 $error = $record->ut_textn('column');
133 $error = $record->ut_alpha('column');
134 $error = $record->ut_alphan('column');
135 $error = $record->ut_phonen('column');
136 $error = $record->ut_anything('column');
137 $error = $record->ut_name('column');
139 $quoted_value = _quote($value,'table','field');
142 $fields = hfields('table');
143 if ( $fields->{Field} ) { # etc.
145 @fields = fields 'table'; #as a subroutine
146 @fields = $record->fields; #as a method call
151 (Mostly) object-oriented interface to database records. Records are currently
152 implemented on top of DBI. FS::Record is intended as a base class for
153 table-specific classes to inherit from, i.e. FS::cust_main.
159 =item new [ TABLE, ] HASHREF
161 Creates a new record. It doesn't store it in the database, though. See
162 L<"insert"> for that.
164 Note that the object stores this hash reference, not a distinct copy of the
165 hash it points to. You can ask the object for a copy with the I<hash>
168 TABLE can only be omitted when a dervived class overrides the table method.
174 my $class = ref($proto) || $proto;
176 bless ($self, $class);
178 unless ( defined ( $self->table ) ) {
179 $self->{'Table'} = shift;
180 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
181 unless $nowarn_classload;
184 $self->{'Hash'} = shift;
186 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
187 $self->{'Hash'}{$field}='';
190 $self->_rebless if $self->can('_rebless');
192 $self->{'modified'} = 0;
194 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
201 my $class = ref($proto) || $proto;
203 bless ($self, $class);
205 $self->{'Table'} = shift unless defined ( $self->table );
207 my $hashref = $self->{'Hash'} = shift;
209 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
210 my $obj = $cache->cache->{$hashref->{$cache->key}};
211 $obj->_cache($hashref, $cache) if $obj->can('_cache');
214 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
221 my $class = ref($proto) || $proto;
223 bless ($self, $class);
224 if ( defined $self->table ) {
225 cluck "create constructor is deprecated, use new!";
228 croak "FS::Record::create called (not from a subclass)!";
232 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
234 Searches the database for all records matching (at least) the key/value pairs
235 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
236 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
239 The preferred usage is to pass a hash reference of named parameters:
241 @records = qsearch( {
242 'table' => 'table_name',
243 'hashref' => { 'field' => 'value'
244 'field' => { 'op' => '<',
249 #these are optional...
251 'extra_sql' => 'AND field = ? AND intfield = ?',
252 'extra_param' => [ 'value', [ 5, 'int' ] ],
253 'order_by' => 'ORDER BY something',
254 #'cache_obj' => '', #optional
255 'addl_from' => 'LEFT JOIN othtable USING ( field )',
260 Much code still uses old-style positional parameters, this is also probably
261 fine in the common case where there are only two parameters:
263 my @records = qsearch( 'table', { 'field' => 'value' } );
265 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
266 the individual PARAMS_HASHREF queries
268 ###oops, argh, FS::Record::new only lets us create database fields.
269 #Normal behaviour if SELECT is not specified is `*', as in
270 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
271 #feature where you can specify SELECT - remember, the objects returned,
272 #although blessed into the appropriate `FS::TABLE' package, will only have the
273 #fields you specify. This might have unwanted results if you then go calling
274 #regular FS::TABLE methods
279 my %TYPE = (); #for debugging
282 my($type, $value) = @_;
284 my $bind_type = { TYPE => SQL_VARCHAR };
286 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
288 $bind_type = { TYPE => SQL_INTEGER };
290 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
292 if ( driver_name eq 'Pg' ) {
294 $bind_type = { pg_type => PG_BYTEA };
296 # $bind_type = ? #SQL_VARCHAR could be fine?
299 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
300 #fixed by DBD::Pg 2.11.8
301 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
302 #(make a Tron test first)
303 } elsif ( _is_fs_float( $type, $value ) ) {
305 $bind_type = { TYPE => SQL_DECIMAL };
314 my($type, $value) = @_;
315 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
316 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
324 my( @stable, @record, @cache );
325 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
327 my %union_options = ();
328 if ( ref($_[0]) eq 'ARRAY' ) {
331 foreach my $href ( @$optlist ) {
332 push @stable, ( $href->{'table'} or die "table name is required" );
333 push @record, ( $href->{'hashref'} || {} );
334 push @select, ( $href->{'select'} || '*' );
335 push @extra_sql, ( $href->{'extra_sql'} || '' );
336 push @extra_param, ( $href->{'extra_param'} || [] );
337 push @order_by, ( $href->{'order_by'} || '' );
338 push @cache, ( $href->{'cache_obj'} || '' );
339 push @addl_from, ( $href->{'addl_from'} || '' );
340 push @debug, ( $href->{'debug'} || '' );
342 die "at least one hashref is required" unless scalar(@stable);
343 } elsif ( ref($_[0]) eq 'HASH' ) {
345 $stable[0] = $opt->{'table'} or die "table name is required";
346 $record[0] = $opt->{'hashref'} || {};
347 $select[0] = $opt->{'select'} || '*';
348 $extra_sql[0] = $opt->{'extra_sql'} || '';
349 $extra_param[0] = $opt->{'extra_param'} || [];
350 $order_by[0] = $opt->{'order_by'} || '';
351 $cache[0] = $opt->{'cache_obj'} || '';
352 $addl_from[0] = $opt->{'addl_from'} || '';
353 $debug[0] = $opt->{'debug'} || '';
364 my $cache = $cache[0];
370 foreach my $stable ( @stable ) {
371 #stop altering the caller's hashref
372 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
373 my $select = shift @select;
374 my $extra_sql = shift @extra_sql;
375 my $extra_param = shift @extra_param;
376 my $order_by = shift @order_by;
377 my $cache = shift @cache;
378 my $addl_from = shift @addl_from;
379 my $debug = shift @debug;
381 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
383 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
386 my $table = $cache ? $cache->table : $stable;
387 my $dbdef_table = dbdef->table($table)
388 or die "No schema for table $table found - ".
389 "do you need to run freeside-upgrade?";
390 my $pkey = $dbdef_table->primary_key;
392 my @real_fields = grep exists($record->{$_}), real_fields($table);
394 my $statement .= "SELECT $select FROM $stable";
395 $statement .= " $addl_from" if $addl_from;
396 if ( @real_fields ) {
397 $statement .= ' WHERE '. join(' AND ',
398 get_real_fields($table, $record, \@real_fields));
401 $statement .= " $extra_sql" if defined($extra_sql);
402 $statement .= " $order_by" if defined($order_by);
404 push @statement, $statement;
406 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
410 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
413 my $value = $record->{$field};
414 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
415 $value = $value->{'value'} if ref($value);
416 my $type = dbdef->table($table)->column($field)->type;
418 my $bind_type = _bind_type($type, $value);
422 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
424 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
428 push @bind_type, $bind_type;
432 foreach my $param ( @$extra_param ) {
433 my $bind_type = { TYPE => SQL_VARCHAR };
436 $value = $param->[0];
437 my $type = $param->[1];
438 $bind_type = _bind_type($type, $value);
441 push @bind_type, $bind_type;
445 my $statement = join( ' ) UNION ( ', @statement );
446 $statement = "( $statement )" if scalar(@statement) > 1;
447 $statement .= " $union_options{order_by}" if $union_options{order_by};
449 my $sth = $dbh->prepare($statement)
450 or croak "$dbh->errstr doing $statement";
453 foreach my $value ( @value ) {
454 my $bind_type = shift @bind_type;
455 $sth->bind_param($bind++, $value, $bind_type );
458 # $sth->execute( map $record->{$_},
459 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
460 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
462 my $ok = $sth->execute;
464 my $error = "Error executing \"$statement\"";
465 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
466 $error .= ': '. $sth->errstr;
470 my $table = $stable[0];
472 $table = '' if grep { $_ ne $table } @stable;
473 $pkey = dbdef->table($table)->primary_key if $table;
476 tie %result, "Tie::IxHash";
477 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
478 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
479 %result = map { $_->{$pkey}, $_ } @stuff;
481 @result{@stuff} = @stuff;
487 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
488 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
489 #derivied class didn't override new method, so this optimization is safe
492 new_or_cached( "FS::$table", { %{$_} }, $cache )
496 new( "FS::$table", { %{$_} } )
500 #okay, its been tested
501 # warn "untested code (class FS::$table uses custom new method)";
503 eval 'FS::'. $table. '->new( { %{$_} } )';
507 # Check for encrypted fields and decrypt them.
508 ## only in the local copy, not the cached object
509 if ( $conf_encryption
510 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
511 foreach my $record (@return) {
512 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
513 next if $field eq 'payinfo'
514 && ($record->isa('FS::payinfo_transaction_Mixin')
515 || $record->isa('FS::payinfo_Mixin') )
517 && !grep { $record->payby eq $_ } @encrypt_payby;
518 # Set it directly... This may cause a problem in the future...
519 $record->setfield($field, $record->decrypt($record->getfield($field)));
524 cluck "warning: FS::$table not loaded; returning FS::Record objects"
525 unless $nowarn_classload;
527 FS::Record->new( $table, { %{$_} } );
535 Construct the SQL statement and parameter-binding list for qsearch. Takes
536 the qsearch parameters.
538 Returns a hash containing:
539 'table': The primary table name (if there is one).
540 'statement': The SQL statement itself.
541 'bind_type': An arrayref of bind types.
542 'value': An arrayref of parameter values.
543 'cache': The cache object, if one was passed.
548 my( @stable, @record, @cache );
549 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
552 my %union_options = ();
553 if ( ref($_[0]) eq 'ARRAY' ) {
556 foreach my $href ( @$optlist ) {
557 push @stable, ( $href->{'table'} or die "table name is required" );
558 push @record, ( $href->{'hashref'} || {} );
559 push @select, ( $href->{'select'} || '*' );
560 push @extra_sql, ( $href->{'extra_sql'} || '' );
561 push @extra_param, ( $href->{'extra_param'} || [] );
562 push @order_by, ( $href->{'order_by'} || '' );
563 push @cache, ( $href->{'cache_obj'} || '' );
564 push @addl_from, ( $href->{'addl_from'} || '' );
565 push @debug, ( $href->{'debug'} || '' );
567 die "at least one hashref is required" unless scalar(@stable);
568 } elsif ( ref($_[0]) eq 'HASH' ) {
570 $stable[0] = $opt->{'table'} or die "table name is required";
571 $record[0] = $opt->{'hashref'} || {};
572 $select[0] = $opt->{'select'} || '*';
573 $extra_sql[0] = $opt->{'extra_sql'} || '';
574 $extra_param[0] = $opt->{'extra_param'} || [];
575 $order_by[0] = $opt->{'order_by'} || '';
576 $cache[0] = $opt->{'cache_obj'} || '';
577 $addl_from[0] = $opt->{'addl_from'} || '';
578 $debug[0] = $opt->{'debug'} || '';
589 my $cache = $cache[0];
595 my $result_table = $stable[0];
596 foreach my $stable ( @stable ) {
597 #stop altering the caller's hashref
598 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
599 my $select = shift @select;
600 my $extra_sql = shift @extra_sql;
601 my $extra_param = shift @extra_param;
602 my $order_by = shift @order_by;
603 my $cache = shift @cache;
604 my $addl_from = shift @addl_from;
605 my $debug = shift @debug;
607 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
609 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
612 $result_table = '' if $result_table ne $stable;
614 my $table = $cache ? $cache->table : $stable;
615 my $dbdef_table = dbdef->table($table)
616 or die "No schema for table $table found - ".
617 "do you need to run freeside-upgrade?";
618 my $pkey = $dbdef_table->primary_key;
620 my @real_fields = grep exists($record->{$_}), real_fields($table);
622 my $statement .= "SELECT $select FROM $stable";
623 $statement .= " $addl_from" if $addl_from;
624 if ( @real_fields ) {
625 $statement .= ' WHERE '. join(' AND ',
626 get_real_fields($table, $record, \@real_fields));
629 $statement .= " $extra_sql" if defined($extra_sql);
630 $statement .= " $order_by" if defined($order_by);
632 push @statement, $statement;
634 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
638 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
641 my $value = $record->{$field};
642 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
643 $value = $value->{'value'} if ref($value);
644 my $type = dbdef->table($table)->column($field)->type;
646 my $bind_type = _bind_type($type, $value);
650 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
652 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
656 push @bind_type, $bind_type;
660 foreach my $param ( @$extra_param ) {
661 my $bind_type = { TYPE => SQL_VARCHAR };
664 $value = $param->[0];
665 my $type = $param->[1];
666 $bind_type = _bind_type($type, $value);
669 push @bind_type, $bind_type;
673 my $statement = join( ' ) UNION ( ', @statement );
674 $statement = "( $statement )" if scalar(@statement) > 1;
675 $statement .= " $union_options{order_by}" if $union_options{order_by};
678 statement => $statement,
679 bind_type => \@bind_type,
681 table => $result_table,
686 # qsearch should eventually use this
688 my ($table, $cache, @hashrefs) = @_;
690 # XXX get rid of these string evals at some point
691 # (when we have time to test it)
692 # my $class = "FS::$table" if $table;
693 # if ( $class and $class->isa('FS::Record') )
694 # if ( $class->can('new') eq \&new )
696 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
697 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
698 #derivied class didn't override new method, so this optimization is safe
701 new_or_cached( "FS::$table", { %{$_} }, $cache )
705 new( "FS::$table", { %{$_} } )
709 #okay, its been tested
710 # warn "untested code (class FS::$table uses custom new method)";
712 eval 'FS::'. $table. '->new( { %{$_} } )';
716 # Check for encrypted fields and decrypt them.
717 ## only in the local copy, not the cached object
718 if ( $conf_encryption
719 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
720 foreach my $record (@return) {
721 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
722 next if $field eq 'payinfo'
723 && ($record->isa('FS::payinfo_transaction_Mixin')
724 || $record->isa('FS::payinfo_Mixin') )
726 && !grep { $record->payby eq $_ } @encrypt_payby;
727 # Set it directly... This may cause a problem in the future...
728 $record->setfield($field, $record->decrypt($record->getfield($field)));
733 cluck "warning: FS::$table not loaded; returning FS::Record objects"
734 unless $nowarn_classload;
736 FS::Record->new( $table, { %{$_} } );
742 ## makes this easier to read
744 sub get_real_fields {
747 my $real_fields = shift;
749 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
755 my $type = dbdef->table($table)->column($column)->type;
756 my $value = $record->{$column};
757 $value = $value->{'value'} if ref($value);
758 if ( ref($record->{$_}) ) {
759 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
760 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
761 if ( uc($op) eq 'ILIKE' ) {
763 $record->{$_}{'value'} = lc($record->{$_}{'value'});
764 $column = "LOWER($_)";
766 $record->{$_} = $record->{$_}{'value'}
769 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
771 if ( driver_name eq 'Pg' ) {
772 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
773 qq-( $column IS NULL )-;
775 qq-( $column IS NULL OR $column = '' )-;
778 qq-( $column IS NULL OR $column = "" )-;
780 } elsif ( $op eq '!=' ) {
781 if ( driver_name eq 'Pg' ) {
782 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
783 qq-( $column IS NOT NULL )-;
785 qq-( $column IS NOT NULL AND $column != '' )-;
788 qq-( $column IS NOT NULL AND $column != "" )-;
791 if ( driver_name eq 'Pg' ) {
792 qq-( $column $op '' )-;
794 qq-( $column $op "" )-;
797 } elsif ( $op eq '!=' ) {
798 qq-( $column IS NULL OR $column != ? )-;
799 #if this needs to be re-enabled, it needs to use a custom op like
800 #"APPROX=" or something (better name?, not '=', to avoid affecting other
802 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
803 # ( "$column <= ?", "$column >= ?" );
807 } @{ $real_fields } );
810 =item by_key PRIMARY_KEY_VALUE
812 This is a class method that returns the record with the given primary key
813 value. This method is only useful in FS::Record subclasses. For example:
815 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
819 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
824 my ($class, $pkey_value) = @_;
826 my $table = $class->table
827 or croak "No table for $class found";
829 my $dbdef_table = dbdef->table($table)
830 or die "No schema for table $table found - ".
831 "do you need to create it or run dbdef-create?";
832 my $pkey = $dbdef_table->primary_key
833 or die "No primary key for table $table";
835 return qsearchs($table, { $pkey => $pkey_value });
838 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
840 Experimental JOINed search method. Using this method, you can execute a
841 single SELECT spanning multiple tables, and cache the results for subsequent
842 method calls. Interface will almost definately change in an incompatible
850 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
851 my $cache = FS::SearchCache->new( $ptable, $pkey );
854 grep { !$saw{$_->getfield($pkey)}++ }
855 qsearch($table, $record, $select, $extra_sql, $cache )
859 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
861 Same as qsearch, except that if more than one record matches, it B<carp>s but
862 returns the first. If this happens, you either made a logic error in asking
863 for a single item, or your data is corrupted.
867 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
869 my(@result) = qsearch(@_);
870 cluck "warning: Multiple records in scalar search ($table)"
871 if scalar(@result) > 1;
872 #should warn more vehemently if the search was on a primary key?
873 scalar(@result) ? ($result[0]) : ();
884 Returns the table name.
889 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
896 Returns the DBIx::DBSchema::Table object for the table.
902 my($table)=$self->table;
903 dbdef->table($table);
908 Returns the primary key for the table.
914 my $pkey = $self->dbdef_table->primary_key;
917 =item get, getfield COLUMN
919 Returns the value of the column/field/key COLUMN.
924 my($self,$field) = @_;
925 # to avoid "Use of unitialized value" errors
926 if ( defined ( $self->{Hash}->{$field} ) ) {
927 $self->{Hash}->{$field};
937 =item set, setfield COLUMN, VALUE
939 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
944 my($self,$field,$value) = @_;
945 $self->{'modified'} = 1;
946 $self->{'Hash'}->{$field} = $value;
955 Returns true if the column/field/key COLUMN exists.
960 my($self,$field) = @_;
961 exists($self->{Hash}->{$field});
964 =item AUTLOADED METHODS
966 $record->column is a synonym for $record->get('column');
968 $record->column('value') is a synonym for $record->set('column','value');
975 my($field)=$AUTOLOAD;
977 if ( defined($value) ) {
978 confess "errant AUTOLOAD $field for $self (arg $value)"
979 unless blessed($self) && $self->can('setfield');
980 $self->setfield($field,$value);
982 confess "errant AUTOLOAD $field for $self (no args)"
983 unless blessed($self) && $self->can('getfield');
984 $self->getfield($field);
990 # my $field = $AUTOLOAD;
992 # if ( defined($_[1]) ) {
993 # $_[0]->setfield($field, $_[1]);
995 # $_[0]->getfield($field);
1001 Returns a list of the column/value pairs, usually for assigning to a new hash.
1003 To make a distinct duplicate of an FS::Record object, you can do:
1005 $new = new FS::Record ( $old->table, { $old->hash } );
1011 confess $self. ' -> hash: Hash attribute is undefined'
1012 unless defined($self->{'Hash'});
1013 %{ $self->{'Hash'} };
1018 Returns a reference to the column/value hash. This may be deprecated in the
1019 future; if there's a reason you can't just use the autoloaded or get/set
1031 Returns true if any of this object's values have been modified with set (or via
1032 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1039 $self->{'modified'};
1042 =item select_for_update
1044 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1049 sub select_for_update {
1051 my $primary_key = $self->primary_key;
1054 'table' => $self->table,
1055 'hashref' => { $primary_key => $self->$primary_key() },
1056 'extra_sql' => 'FOR UPDATE',
1062 Locks this table with a database-driver specific lock method. This is used
1063 as a mutex in order to do a duplicate search.
1065 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1067 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1069 Errors are fatal; no useful return value.
1071 Note: To use this method for new tables other than svc_acct and svc_phone,
1072 edit freeside-upgrade and add those tables to the duplicate_lock list.
1078 my $table = $self->table;
1080 warn "$me locking $table table\n" if $DEBUG;
1082 if ( driver_name =~ /^Pg/i ) {
1084 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1087 } elsif ( driver_name =~ /^mysql/i ) {
1089 dbh->do("SELECT * FROM duplicate_lock
1090 WHERE lockname = '$table'
1092 ) or die dbh->errstr;
1096 die "unknown database ". driver_name. "; don't know how to lock table";
1100 warn "$me acquired $table table lock\n" if $DEBUG;
1106 Inserts this record to the database. If there is an error, returns the error,
1107 otherwise returns false.
1115 warn "$self -> insert" if $DEBUG;
1117 my $error = $self->check;
1118 return $error if $error;
1120 #single-field non-null unique keys are given a value if empty
1121 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1122 foreach ( $self->dbdef_table->unique_singles) {
1123 next if $self->getfield($_);
1124 next if $self->dbdef_table->column($_)->null eq 'NULL';
1128 #and also the primary key, if the database isn't going to
1129 my $primary_key = $self->dbdef_table->primary_key;
1131 if ( $primary_key ) {
1132 my $col = $self->dbdef_table->column($primary_key);
1135 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1136 || ( driver_name eq 'Pg'
1137 && defined($col->default)
1138 && $col->quoted_default =~ /^nextval\(/i
1140 || ( driver_name eq 'mysql'
1141 && defined($col->local)
1142 && $col->local =~ /AUTO_INCREMENT/i
1144 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1147 my $table = $self->table;
1149 # Encrypt before the database
1150 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
1151 && scalar( eval '@FS::'. $table . '::encrypted_fields')
1152 && $conf->exists('encryption')
1154 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1155 next if $field eq 'payinfo'
1156 && ($self->isa('FS::payinfo_transaction_Mixin')
1157 || $self->isa('FS::payinfo_Mixin') )
1159 && !grep { $self->payby eq $_ } @encrypt_payby;
1160 $saved->{$field} = $self->getfield($field);
1161 $self->setfield($field, $self->encrypt($self->getfield($field)));
1165 #false laziness w/delete
1167 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1170 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1173 my $statement = "INSERT INTO $table ";
1174 if ( @real_fields ) {
1177 join( ', ', @real_fields ).
1179 join( ', ', @values ).
1183 $statement .= 'DEFAULT VALUES';
1185 warn "[debug]$me $statement\n" if $DEBUG > 1;
1186 my $sth = dbh->prepare($statement) or return dbh->errstr;
1188 local $SIG{HUP} = 'IGNORE';
1189 local $SIG{INT} = 'IGNORE';
1190 local $SIG{QUIT} = 'IGNORE';
1191 local $SIG{TERM} = 'IGNORE';
1192 local $SIG{TSTP} = 'IGNORE';
1193 local $SIG{PIPE} = 'IGNORE';
1195 $sth->execute or return $sth->errstr;
1197 # get inserted id from the database, if applicable & needed
1198 if ( $db_seq && ! $self->getfield($primary_key) ) {
1199 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1203 if ( driver_name eq 'Pg' ) {
1205 #my $oid = $sth->{'pg_oid_status'};
1206 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1208 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1209 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1210 dbh->rollback if $FS::UID::AutoCommit;
1211 return "can't parse $table.$primary_key default value".
1212 " for sequence name: $default";
1216 my $i_sql = "SELECT currval('$sequence')";
1217 my $i_sth = dbh->prepare($i_sql) or do {
1218 dbh->rollback if $FS::UID::AutoCommit;
1221 $i_sth->execute() or do { #$i_sth->execute($oid)
1222 dbh->rollback if $FS::UID::AutoCommit;
1223 return $i_sth->errstr;
1225 $insertid = $i_sth->fetchrow_arrayref->[0];
1227 } elsif ( driver_name eq 'mysql' ) {
1229 $insertid = dbh->{'mysql_insertid'};
1230 # work around mysql_insertid being null some of the time, ala RT :/
1231 unless ( $insertid ) {
1232 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1233 "using SELECT LAST_INSERT_ID();";
1234 my $i_sql = "SELECT LAST_INSERT_ID()";
1235 my $i_sth = dbh->prepare($i_sql) or do {
1236 dbh->rollback if $FS::UID::AutoCommit;
1239 $i_sth->execute or do {
1240 dbh->rollback if $FS::UID::AutoCommit;
1241 return $i_sth->errstr;
1243 $insertid = $i_sth->fetchrow_arrayref->[0];
1248 dbh->rollback if $FS::UID::AutoCommit;
1249 return "don't know how to retreive inserted ids from ". driver_name.
1250 ", try using counterfiles (maybe run dbdef-create?)";
1254 $self->setfield($primary_key, $insertid);
1259 if ( defined( dbdef->table('h_'. $table) ) && ! $no_history ) {
1260 my $h_statement = $self->_h_statement('insert');
1261 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1262 $h_sth = dbh->prepare($h_statement) or do {
1263 dbh->rollback if $FS::UID::AutoCommit;
1269 $h_sth->execute or return $h_sth->errstr if $h_sth;
1271 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1273 # Now that it has been saved, reset the encrypted fields so that $new
1274 # can still be used.
1275 foreach my $field (keys %{$saved}) {
1276 $self->setfield($field, $saved->{$field});
1284 Depriciated (use insert instead).
1289 cluck "warning: FS::Record::add deprecated!";
1290 insert @_; #call method in this scope
1295 Delete this record from the database. If there is an error, returns the error,
1296 otherwise returns false.
1303 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1305 $self->getfield($_) eq ''
1306 #? "( $_ IS NULL OR $_ = \"\" )"
1307 ? ( driver_name eq 'Pg'
1309 : "( $_ IS NULL OR $_ = \"\" )"
1311 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1312 } ( $self->dbdef_table->primary_key )
1313 ? ( $self->dbdef_table->primary_key)
1314 : real_fields($self->table)
1316 warn "[debug]$me $statement\n" if $DEBUG > 1;
1317 my $sth = dbh->prepare($statement) or return dbh->errstr;
1320 if ( defined dbdef->table('h_'. $self->table) ) {
1321 my $h_statement = $self->_h_statement('delete');
1322 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1323 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1328 my $primary_key = $self->dbdef_table->primary_key;
1330 local $SIG{HUP} = 'IGNORE';
1331 local $SIG{INT} = 'IGNORE';
1332 local $SIG{QUIT} = 'IGNORE';
1333 local $SIG{TERM} = 'IGNORE';
1334 local $SIG{TSTP} = 'IGNORE';
1335 local $SIG{PIPE} = 'IGNORE';
1337 my $rc = $sth->execute or return $sth->errstr;
1338 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1339 $h_sth->execute or return $h_sth->errstr if $h_sth;
1341 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1343 #no need to needlessly destoy the data either (causes problems actually)
1344 #undef $self; #no need to keep object!
1351 Depriciated (use delete instead).
1356 cluck "warning: FS::Record::del deprecated!";
1357 &delete(@_); #call method in this scope
1360 =item replace OLD_RECORD
1362 Replace the OLD_RECORD with this one in the database. If there is an error,
1363 returns the error, otherwise returns false.
1368 my ($new, $old) = (shift, shift);
1370 $old = $new->replace_old unless defined($old);
1372 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1374 if ( $new->can('replace_check') ) {
1375 my $error = $new->replace_check($old);
1376 return $error if $error;
1379 return "Records not in same table!" unless $new->table eq $old->table;
1381 my $primary_key = $old->dbdef_table->primary_key;
1382 return "Can't change primary key $primary_key ".
1383 'from '. $old->getfield($primary_key).
1384 ' to ' . $new->getfield($primary_key)
1386 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1388 my $error = $new->check;
1389 return $error if $error;
1391 # Encrypt for replace
1393 if ( $conf->exists('encryption')
1394 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1395 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1397 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1398 next if $field eq 'payinfo'
1399 && ($new->isa('FS::payinfo_transaction_Mixin')
1400 || $new->isa('FS::payinfo_Mixin') )
1402 && !grep { $new->payby eq $_ } @encrypt_payby;
1403 $saved->{$field} = $new->getfield($field);
1404 $new->setfield($field, $new->encrypt($new->getfield($field)));
1408 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1409 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1410 ? ($_, $new->getfield($_)) : () } $old->fields;
1412 unless (keys(%diff) || $no_update_diff ) {
1413 carp "[warning]$me ". ref($new)."->replace ".
1414 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1415 ": records identical"
1416 unless $nowarn_identical;
1420 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1422 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1423 } real_fields($old->table)
1428 if ( $old->getfield($_) eq '' ) {
1430 #false laziness w/qsearch
1431 if ( driver_name eq 'Pg' ) {
1432 my $type = $old->dbdef_table->column($_)->type;
1433 if ( $type =~ /(int|(big)?serial)/i ) {
1436 qq-( $_ IS NULL OR $_ = '' )-;
1439 qq-( $_ IS NULL OR $_ = "" )-;
1443 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1446 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1449 warn "[debug]$me $statement\n" if $DEBUG > 1;
1450 my $sth = dbh->prepare($statement) or return dbh->errstr;
1453 if ( defined dbdef->table('h_'. $old->table) ) {
1454 my $h_old_statement = $old->_h_statement('replace_old');
1455 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1456 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1462 if ( defined dbdef->table('h_'. $new->table) ) {
1463 my $h_new_statement = $new->_h_statement('replace_new');
1464 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1465 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1470 local $SIG{HUP} = 'IGNORE';
1471 local $SIG{INT} = 'IGNORE';
1472 local $SIG{QUIT} = 'IGNORE';
1473 local $SIG{TERM} = 'IGNORE';
1474 local $SIG{TSTP} = 'IGNORE';
1475 local $SIG{PIPE} = 'IGNORE';
1477 my $rc = $sth->execute or return $sth->errstr;
1478 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1479 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1480 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1482 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1484 # Now that it has been saved, reset the encrypted fields so that $new
1485 # can still be used.
1486 foreach my $field (keys %{$saved}) {
1487 $new->setfield($field, $saved->{$field});
1495 my( $self ) = shift;
1496 warn "[$me] replace called with no arguments; autoloading old record\n"
1499 my $primary_key = $self->dbdef_table->primary_key;
1500 if ( $primary_key ) {
1501 $self->by_key( $self->$primary_key() ) #this is what's returned
1502 or croak "can't find ". $self->table. ".$primary_key ".
1503 $self->$primary_key();
1505 croak $self->table. " has no primary key; pass old record as argument";
1512 Depriciated (use replace instead).
1517 cluck "warning: FS::Record::rep deprecated!";
1518 replace @_; #call method in this scope
1523 Checks custom fields. Subclasses should still provide a check method to validate
1524 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1530 foreach my $field ($self->virtual_fields) {
1531 my $error = $self->ut_textn($field);
1532 return $error if $error;
1537 =item virtual_fields [ TABLE ]
1539 Returns a list of virtual fields defined for the table. This should not
1540 be exported, and should only be called as an instance or class method.
1544 sub virtual_fields {
1547 $table = $self->table or confess "virtual_fields called on non-table";
1549 confess "Unknown table $table" unless dbdef->table($table);
1551 return () unless dbdef->table('part_virtual_field');
1553 unless ( $virtual_fields_cache{$table} ) {
1554 my $concat = [ "'cf_'", "name" ];
1555 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1556 "WHERE dbtable = '$table'";
1558 my $result = $dbh->selectcol_arrayref($query);
1559 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1561 $virtual_fields_cache{$table} = $result;
1564 @{$virtual_fields_cache{$table}};
1568 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1570 Processes a batch import as a queued JSRPC job
1572 JOB is an FS::queue entry.
1574 OPTIONS_HASHREF can have the following keys:
1580 Table name (required).
1584 Listref of field names for static fields. They will be given values from the
1585 PARAMS hashref and passed as a "params" hashref to batch_import.
1589 Formats hashref. Keys are field names, values are listrefs that define the
1592 Each listref value can be a column name or a code reference. Coderefs are run
1593 with the row object, data and a FS::Conf object as the three parameters.
1594 For example, this coderef does the same thing as using the "columnname" string:
1597 my( $record, $data, $conf ) = @_;
1598 $record->columnname( $data );
1601 Coderefs are run after all "column name" fields are assigned.
1605 Optional format hashref of types. Keys are field names, values are "csv",
1606 "xls" or "fixedlength". Overrides automatic determination of file type
1609 =item format_headers
1611 Optional format hashref of header lines. Keys are field names, values are 0
1612 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1615 =item format_sep_chars
1617 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1618 CSV separation character.
1620 =item format_fixedlenth_formats
1622 Optional format hashref of fixed length format defintiions. Keys are field
1623 names, values Parse::FixedLength listrefs of field definitions.
1627 Set true to default to CSV file type if the filename does not contain a
1628 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1633 PARAMS is a base64-encoded Storable string containing the POSTed data as
1634 a hash ref. It normally contains at least one field, "uploaded files",
1635 generated by /elements/file-upload.html and containing the list of uploaded
1636 files. Currently only supports a single file named "file".
1640 use Storable qw(thaw);
1643 sub process_batch_import {
1644 my($job, $opt) = ( shift, shift );
1646 my $table = $opt->{table};
1647 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1648 my %formats = %{ $opt->{formats} };
1650 my $param = thaw(decode_base64(shift));
1651 warn Dumper($param) if $DEBUG;
1653 my $files = $param->{'uploaded_files'}
1654 or die "No files provided.\n";
1656 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1658 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1659 my $file = $dir. $files{'file'};
1664 formats => \%formats,
1665 format_types => $opt->{format_types},
1666 format_headers => $opt->{format_headers},
1667 format_sep_chars => $opt->{format_sep_chars},
1668 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1669 format_xml_formats => $opt->{format_xml_formats},
1670 format_asn_formats => $opt->{format_asn_formats},
1671 format_row_callbacks => $opt->{format_row_callbacks},
1676 format => $param->{format},
1677 params => { map { $_ => $param->{$_} } @pass_params },
1679 default_csv => $opt->{default_csv},
1680 postinsert_callback => $opt->{postinsert_callback},
1683 if ( $opt->{'batch_namecol'} ) {
1684 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1685 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1688 my $error = FS::Record::batch_import( \%iopt );
1692 die "$error\n" if $error;
1695 =item batch_import PARAM_HASHREF
1697 Class method for batch imports. Available params:
1703 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1709 =item format_headers
1711 =item format_sep_chars
1713 =item format_fixedlength_formats
1715 =item format_row_callbacks
1717 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1719 =item preinsert_callback
1721 =item postinsert_callback
1727 FS::queue object, will be updated with progress
1733 csv, xls, fixedlength, xml
1744 warn "$me batch_import call with params: \n". Dumper($param)
1747 my $table = $param->{table};
1749 my $job = $param->{job};
1750 my $file = $param->{file};
1751 my $params = $param->{params} || {};
1753 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1754 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1756 my( $type, $header, $sep_char,
1757 $fixedlength_format, $xml_format, $asn_format,
1758 $parser_opt, $row_callback, @fields );
1760 my $postinsert_callback = '';
1761 $postinsert_callback = $param->{'postinsert_callback'}
1762 if $param->{'postinsert_callback'};
1763 my $preinsert_callback = '';
1764 $preinsert_callback = $param->{'preinsert_callback'}
1765 if $param->{'preinsert_callback'};
1767 if ( $param->{'format'} ) {
1769 my $format = $param->{'format'};
1770 my $formats = $param->{formats};
1771 die "unknown format $format" unless exists $formats->{ $format };
1773 $type = $param->{'format_types'}
1774 ? $param->{'format_types'}{ $format }
1775 : $param->{type} || 'csv';
1778 $header = $param->{'format_headers'}
1779 ? $param->{'format_headers'}{ $param->{'format'} }
1782 $sep_char = $param->{'format_sep_chars'}
1783 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1786 $fixedlength_format =
1787 $param->{'format_fixedlength_formats'}
1788 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1792 $param->{'format_parser_opts'}
1793 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1797 $param->{'format_xml_formats'}
1798 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1802 $param->{'format_asn_formats'}
1803 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1807 $param->{'format_row_callbacks'}
1808 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1811 @fields = @{ $formats->{ $format } };
1813 } elsif ( $param->{'fields'} ) {
1815 $type = ''; #infer from filename
1818 $fixedlength_format = '';
1820 @fields = @{ $param->{'fields'} };
1823 die "neither format nor fields specified";
1826 #my $file = $param->{file};
1829 if ( $file =~ /\.(\w+)$/i ) {
1833 warn "can't parse file type from filename $file; defaulting to CSV";
1837 if $param->{'default_csv'} && $type ne 'xls';
1845 my $asn_header_buffer;
1846 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1848 if ( $type eq 'csv' ) {
1850 $parser_opt->{'binary'} = 1;
1851 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
1852 $parser = Text::CSV_XS->new($parser_opt);
1854 } elsif ( $type eq 'fixedlength' ) {
1856 eval "use Parse::FixedLength;";
1858 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
1861 die "Unknown file type $type\n";
1864 @buffer = split(/\r?\n/, slurp($file) );
1865 splice(@buffer, 0, ($header || 0) );
1866 $count = scalar(@buffer);
1868 } elsif ( $type eq 'xls' ) {
1870 eval "use Spreadsheet::ParseExcel;";
1873 eval "use DateTime::Format::Excel;";
1874 #for now, just let the error be thrown if it is used, since only CDR
1875 # formats bill_west and troop use it, not other excel-parsing things
1878 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1880 $parser = $excel->{Worksheet}[0]; #first sheet
1882 $count = $parser->{MaxRow} || $parser->{MinRow};
1885 $row = $header || 0;
1887 } elsif ( $type eq 'xml' ) {
1890 eval "use XML::Simple;";
1892 my $xmlrow = $xml_format->{'xmlrow'};
1893 $parser = $xml_format->{'xmlkeys'};
1894 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1895 my $data = XML::Simple::XMLin(
1897 'SuppressEmpty' => '', #sets empty values to ''
1901 $rows = $rows->{$_} foreach @$xmlrow;
1902 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1903 $count = @buffer = @$rows;
1905 } elsif ( $type eq 'asn.1' ) {
1907 eval "use Convert::ASN1";
1910 my $asn = Convert::ASN1->new;
1911 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1913 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1915 my $data = slurp($file);
1916 my $asn_output = $parser->decode( $data )
1917 or return "No ". $asn_format->{'macro'}. " found\n";
1919 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1921 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1922 $count = @buffer = @$rows;
1925 die "Unknown file type $type\n";
1930 local $SIG{HUP} = 'IGNORE';
1931 local $SIG{INT} = 'IGNORE';
1932 local $SIG{QUIT} = 'IGNORE';
1933 local $SIG{TERM} = 'IGNORE';
1934 local $SIG{TSTP} = 'IGNORE';
1935 local $SIG{PIPE} = 'IGNORE';
1937 my $oldAutoCommit = $FS::UID::AutoCommit;
1938 local $FS::UID::AutoCommit = 0;
1941 #my $params = $param->{params} || {};
1942 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1943 my $batch_col = $param->{'batch_keycol'};
1945 my $batch_class = 'FS::'. $param->{'batch_table'};
1946 my $batch = $batch_class->new({
1947 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1949 my $error = $batch->insert;
1951 $dbh->rollback if $oldAutoCommit;
1952 return "can't insert batch record: $error";
1954 #primary key via dbdef? (so the column names don't have to match)
1955 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1957 $params->{ $batch_col } = $batch_value;
1960 #my $job = $param->{job};
1963 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1967 my %hash = %$params;
1968 if ( $type eq 'csv' ) {
1970 last unless scalar(@buffer);
1971 $line = shift(@buffer);
1973 next if $line =~ /^\s*$/; #skip empty lines
1975 $line = &{$row_callback}($line) if $row_callback;
1977 next if $line =~ /^\s*$/; #skip empty lines
1979 $parser->parse($line) or do {
1980 $dbh->rollback if $oldAutoCommit;
1981 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
1983 @columns = $parser->fields();
1985 } elsif ( $type eq 'fixedlength' ) {
1987 last unless scalar(@buffer);
1988 $line = shift(@buffer);
1990 @columns = $parser->parse($line);
1992 } elsif ( $type eq 'xls' ) {
1994 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1995 || ! $parser->{Cells}[$row];
1997 my @row = @{ $parser->{Cells}[$row] };
1998 @columns = map $_->{Val}, @row;
2001 #warn $z++. ": $_\n" for @columns;
2003 } elsif ( $type eq 'xml' ) {
2005 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2006 last unless scalar(@buffer);
2007 my $row = shift @buffer;
2008 @columns = @{ $row }{ @$parser };
2010 } elsif ( $type eq 'asn.1' ) {
2012 last unless scalar(@buffer);
2013 my $row = shift @buffer;
2014 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2015 if $asn_format->{row_callback};
2016 foreach my $key ( keys %{ $asn_format->{map} } ) {
2017 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2021 die "Unknown file type $type\n";
2026 foreach my $field ( @fields ) {
2028 my $value = shift @columns;
2030 if ( ref($field) eq 'CODE' ) {
2031 #&{$field}(\%hash, $value);
2032 push @later, $field, $value;
2034 #??? $hash{$field} = $value if length($value);
2035 $hash{$field} = $value if defined($value) && length($value);
2040 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2041 && length($1) == $custnum_length ) {
2042 $hash{custnum} = $2;
2045 #my $table = $param->{table};
2046 my $class = "FS::$table";
2048 my $record = $class->new( \%hash );
2051 while ( scalar(@later) ) {
2052 my $sub = shift @later;
2053 my $data = shift @later;
2055 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2058 $dbh->rollback if $oldAutoCommit;
2059 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2061 last if exists( $param->{skiprow} );
2063 next if exists( $param->{skiprow} );
2065 if ( $preinsert_callback ) {
2066 my $error = &{$preinsert_callback}($record, $param);
2068 $dbh->rollback if $oldAutoCommit;
2069 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2072 next if exists $param->{skiprow} && $param->{skiprow};
2075 my $error = $record->insert;
2078 $dbh->rollback if $oldAutoCommit;
2079 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2085 if ( $postinsert_callback ) {
2086 my $error = &{$postinsert_callback}($record, $param);
2088 $dbh->rollback if $oldAutoCommit;
2089 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2094 if ( $job && time - $min_sec > $last ) { #progress bar
2095 $job->update_statustext( int(100 * $imported / $count) );
2101 unless ( $imported || $param->{empty_ok} ) {
2102 $dbh->rollback if $oldAutoCommit;
2103 return "Empty file!";
2106 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2113 my( $self, $action, $time ) = @_;
2117 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2120 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2121 real_fields($self->table);
2124 # If we're encrypting then don't store the payinfo in the history
2125 if ( $conf && $conf->exists('encryption') && $self->table ne 'banned_pay' ) {
2126 @fields = grep { $_ ne 'payinfo' } @fields;
2129 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2131 "INSERT INTO h_". $self->table. " ( ".
2132 join(', ', qw(history_date history_user history_action), @fields ).
2134 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
2141 B<Warning>: External use is B<deprecated>.
2143 Replaces COLUMN in record with a unique number, using counters in the
2144 filesystem. Used by the B<insert> method on single-field unique columns
2145 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2146 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2148 Returns the new value.
2153 my($self,$field) = @_;
2154 my($table)=$self->table;
2156 croak "Unique called on field $field, but it is ",
2157 $self->getfield($field),
2159 if $self->getfield($field);
2161 #warn "table $table is tainted" if is_tainted($table);
2162 #warn "field $field is tainted" if is_tainted($field);
2164 my($counter) = new File::CounterFile "$table.$field",0;
2166 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2168 # my($counter) = new File::CounterFile "$user/$table.$field",0;
2171 my $index = $counter->inc;
2172 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2174 $index =~ /^(\d*)$/;
2177 $self->setfield($field,$index);
2181 =item ut_float COLUMN
2183 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2184 null. If there is an error, returns the error, otherwise returns false.
2189 my($self,$field)=@_ ;
2190 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2191 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2192 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2193 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2194 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2195 $self->setfield($field,$1);
2198 =item ut_floatn COLUMN
2200 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2201 null. If there is an error, returns the error, otherwise returns false.
2205 #false laziness w/ut_ipn
2207 my( $self, $field ) = @_;
2208 if ( $self->getfield($field) =~ /^()$/ ) {
2209 $self->setfield($field,'');
2212 $self->ut_float($field);
2216 =item ut_sfloat COLUMN
2218 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2219 May not be null. If there is an error, returns the error, otherwise returns
2225 my($self,$field)=@_ ;
2226 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2227 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2228 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2229 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2230 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2231 $self->setfield($field,$1);
2234 =item ut_sfloatn COLUMN
2236 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2237 null. If there is an error, returns the error, otherwise returns false.
2242 my( $self, $field ) = @_;
2243 if ( $self->getfield($field) =~ /^()$/ ) {
2244 $self->setfield($field,'');
2247 $self->ut_sfloat($field);
2251 =item ut_snumber COLUMN
2253 Check/untaint signed numeric data (whole numbers). If there is an error,
2254 returns the error, otherwise returns false.
2259 my($self, $field) = @_;
2260 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2261 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2262 $self->setfield($field, "$1$2");
2266 =item ut_snumbern COLUMN
2268 Check/untaint signed numeric data (whole numbers). If there is an error,
2269 returns the error, otherwise returns false.
2274 my($self, $field) = @_;
2275 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2276 or return "Illegal (numeric) $field: ". $self->getfield($field);
2278 return "Illegal (numeric) $field: ". $self->getfield($field)
2281 $self->setfield($field, "$1$2");
2285 =item ut_number COLUMN
2287 Check/untaint simple numeric data (whole numbers). May not be null. If there
2288 is an error, returns the error, otherwise returns false.
2293 my($self,$field)=@_;
2294 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2295 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2296 $self->setfield($field,$1);
2300 =item ut_numbern COLUMN
2302 Check/untaint simple numeric data (whole numbers). May be null. If there is
2303 an error, returns the error, otherwise returns false.
2308 my($self,$field)=@_;
2309 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2310 or return "Illegal (numeric) $field: ". $self->getfield($field);
2311 $self->setfield($field,$1);
2315 =item ut_money COLUMN
2317 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2318 is an error, returns the error, otherwise returns false.
2323 my($self,$field)=@_;
2325 if ( $self->getfield($field) eq '' ) {
2326 $self->setfield($field, 0);
2327 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2328 #handle one decimal place without barfing out
2329 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2330 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2331 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2333 return "Illegal (money) $field: ". $self->getfield($field);
2339 =item ut_moneyn COLUMN
2341 Check/untaint monetary numbers. May be negative. If there
2342 is an error, returns the error, otherwise returns false.
2347 my($self,$field)=@_;
2348 if ($self->getfield($field) eq '') {
2349 $self->setfield($field, '');
2352 $self->ut_money($field);
2355 =item ut_text COLUMN
2357 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2358 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2359 May not be null. If there is an error, returns the error, otherwise returns
2365 my($self,$field)=@_;
2366 #warn "msgcat ". \&msgcat. "\n";
2367 #warn "notexist ". \¬exist. "\n";
2368 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2369 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2370 # see perldoc perluniprops
2371 $self->getfield($field)
2372 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2373 or return gettext('illegal_or_empty_text'). " $field: ".
2374 $self->getfield($field);
2375 $self->setfield($field,$1);
2379 =item ut_textn COLUMN
2381 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2382 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2383 May be null. If there is an error, returns the error, otherwise returns false.
2388 my($self,$field)=@_;
2389 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2390 $self->ut_text($field);
2393 =item ut_alpha COLUMN
2395 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2396 an error, returns the error, otherwise returns false.
2401 my($self,$field)=@_;
2402 $self->getfield($field) =~ /^(\w+)$/
2403 or return "Illegal or empty (alphanumeric) $field: ".
2404 $self->getfield($field);
2405 $self->setfield($field,$1);
2409 =item ut_alphan COLUMN
2411 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2412 error, returns the error, otherwise returns false.
2417 my($self,$field)=@_;
2418 $self->getfield($field) =~ /^(\w*)$/
2419 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2420 $self->setfield($field,$1);
2424 =item ut_alphasn COLUMN
2426 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2427 an 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);
2440 =item ut_alpha_lower COLUMN
2442 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2443 there is an error, returns the error, otherwise returns false.
2447 sub ut_alpha_lower {
2448 my($self,$field)=@_;
2449 $self->getfield($field) =~ /[[:upper:]]/
2450 and return "Uppercase characters are not permitted in $field";
2451 $self->ut_alpha($field);
2454 =item ut_phonen COLUMN [ COUNTRY ]
2456 Check/untaint phone numbers. May be null. If there is an error, returns
2457 the error, otherwise returns false.
2459 Takes an optional two-letter ISO country code; without it or with unsupported
2460 countries, ut_phonen simply calls ut_alphan.
2465 my( $self, $field, $country ) = @_;
2466 return $self->ut_alphan($field) unless defined $country;
2467 my $phonen = $self->getfield($field);
2468 if ( $phonen eq '' ) {
2469 $self->setfield($field,'');
2470 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2472 $phonen = $conf->config('cust_main-default_areacode').$phonen
2473 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2474 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2475 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2476 $phonen = "$1-$2-$3";
2477 $phonen .= " x$4" if $4;
2478 $self->setfield($field,$phonen);
2480 warn "warning: don't know how to check phone numbers for country $country";
2481 return $self->ut_textn($field);
2488 Check/untaint hexadecimal values.
2493 my($self, $field) = @_;
2494 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2495 or return "Illegal (hex) $field: ". $self->getfield($field);
2496 $self->setfield($field, uc($1));
2500 =item ut_hexn COLUMN
2502 Check/untaint hexadecimal values. May be null.
2507 my($self, $field) = @_;
2508 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2509 or return "Illegal (hex) $field: ". $self->getfield($field);
2510 $self->setfield($field, uc($1));
2514 =item ut_mac_addr COLUMN
2516 Check/untaint mac addresses. May be null.
2521 my($self, $field) = @_;
2523 my $mac = $self->get($field);
2526 $self->set($field, $mac);
2528 my $e = $self->ut_hex($field);
2531 return "Illegal (mac address) $field: ". $self->getfield($field)
2532 unless length($self->getfield($field)) == 12;
2538 =item ut_mac_addrn COLUMN
2540 Check/untaint mac addresses. May be null.
2545 my($self, $field) = @_;
2546 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2551 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2557 my( $self, $field ) = @_;
2558 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2559 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2560 or return "Illegal (IP address) $field: ". $self->getfield($field);
2561 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2562 $self->setfield($field, "$1.$2.$3.$4");
2568 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2569 to 127.0.0.1. May be null.
2574 my( $self, $field ) = @_;
2575 if ( $self->getfield($field) =~ /^()$/ ) {
2576 $self->setfield($field,'');
2579 $self->ut_ip($field);
2583 =item ut_ip46 COLUMN
2585 Check/untaint IPv4 or IPv6 address.
2590 my( $self, $field ) = @_;
2591 my $ip = NetAddr::IP->new($self->getfield($field))
2592 or return "Illegal (IP address) $field: ".$self->getfield($field);
2593 $self->setfield($field, lc($ip->addr));
2599 Check/untaint IPv6 or IPv6 address. May be null.
2604 my( $self, $field ) = @_;
2605 if ( $self->getfield($field) =~ /^$/ ) {
2606 $self->setfield($field, '');
2609 $self->ut_ip46($field);
2612 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2614 Check/untaint coordinates.
2615 Accepts the following forms:
2625 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2626 The latter form (that is, the MMM are thousands of minutes) is
2627 assumed if the "MMM" is exactly three digits or two digits > 59.
2629 To be safe, just use the DDD.DDDDD form.
2631 If LOWER or UPPER are specified, then the coordinate is checked
2632 for lower and upper bounds, respectively.
2637 my ($self, $field) = (shift, shift);
2640 if ( $field =~ /latitude/ ) {
2641 $lower = $lat_lower;
2643 } elsif ( $field =~ /longitude/ ) {
2645 $upper = $lon_upper;
2648 my $coord = $self->getfield($field);
2649 my $neg = $coord =~ s/^(-)//;
2651 my ($d, $m, $s) = (0, 0, 0);
2654 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2655 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2656 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2658 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2661 return "Invalid (coordinate with minutes > 59) $field: "
2662 . $self->getfield($field);
2665 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2667 if (defined($lower) and ($coord < $lower)) {
2668 return "Invalid (coordinate < $lower) $field: "
2669 . $self->getfield($field);;
2672 if (defined($upper) and ($coord > $upper)) {
2673 return "Invalid (coordinate > $upper) $field: "
2674 . $self->getfield($field);;
2677 $self->setfield($field, $coord);
2681 return "Invalid (coordinate) $field: " . $self->getfield($field);
2685 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2687 Same as ut_coord, except optionally null.
2693 my ($self, $field) = (shift, shift);
2695 if ($self->getfield($field) =~ /^\s*$/) {
2698 return $self->ut_coord($field, @_);
2703 =item ut_domain COLUMN
2705 Check/untaint host and domain names. May not be null.
2710 my( $self, $field ) = @_;
2711 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2712 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2713 or return "Illegal (hostname) $field: ". $self->getfield($field);
2714 $self->setfield($field,$1);
2718 =item ut_domainn COLUMN
2720 Check/untaint host and domain names. May be null.
2725 my( $self, $field ) = @_;
2726 if ( $self->getfield($field) =~ /^()$/ ) {
2727 $self->setfield($field,'');
2730 $self->ut_domain($field);
2734 =item ut_name COLUMN
2736 Check/untaint proper names; allows alphanumerics, spaces and the following
2737 punctuation: , . - '
2744 my( $self, $field ) = @_;
2745 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2746 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
2747 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2752 $self->setfield($field, $name);
2756 =item ut_namen COLUMN
2758 Check/untaint proper names; allows alphanumerics, spaces and the following
2759 punctuation: , . - '
2766 my( $self, $field ) = @_;
2767 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2768 $self->ut_name($field);
2773 Check/untaint zip codes.
2777 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2780 my( $self, $field, $country ) = @_;
2782 if ( $country eq 'US' ) {
2784 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2785 or return gettext('illegal_zip'). " $field for country $country: ".
2786 $self->getfield($field);
2787 $self->setfield($field, $1);
2789 } elsif ( $country eq 'CA' ) {
2791 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2792 or return gettext('illegal_zip'). " $field for country $country: ".
2793 $self->getfield($field);
2794 $self->setfield($field, "$1 $2");
2798 if ( $self->getfield($field) =~ /^\s*$/
2799 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2802 $self->setfield($field,'');
2804 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2805 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2806 $self->setfield($field,$1);
2814 =item ut_country COLUMN
2816 Check/untaint country codes. Country names are changed to codes, if possible -
2817 see L<Locale::Country>.
2822 my( $self, $field ) = @_;
2823 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2824 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2825 && country2code($1) ) {
2826 $self->setfield($field,uc(country2code($1)));
2829 $self->getfield($field) =~ /^(\w\w)$/
2830 or return "Illegal (country) $field: ". $self->getfield($field);
2831 $self->setfield($field,uc($1));
2835 =item ut_anything COLUMN
2837 Untaints arbitrary data. Be careful.
2842 my( $self, $field ) = @_;
2843 $self->getfield($field) =~ /^(.*)$/s
2844 or return "Illegal $field: ". $self->getfield($field);
2845 $self->setfield($field,$1);
2849 =item ut_enum COLUMN CHOICES_ARRAYREF
2851 Check/untaint a column, supplying all possible choices, like the "enum" type.
2856 my( $self, $field, $choices ) = @_;
2857 foreach my $choice ( @$choices ) {
2858 if ( $self->getfield($field) eq $choice ) {
2859 $self->setfield($field, $choice);
2863 return "Illegal (enum) field $field: ". $self->getfield($field);
2866 =item ut_enumn COLUMN CHOICES_ARRAYREF
2868 Like ut_enum, except the null value is also allowed.
2873 my( $self, $field, $choices ) = @_;
2874 $self->getfield($field)
2875 ? $self->ut_enum($field, $choices)
2879 =item ut_flag COLUMN
2881 Check/untaint a column if it contains either an empty string or 'Y'. This
2882 is the standard form for boolean flags in Freeside.
2887 my( $self, $field ) = @_;
2888 my $value = uc($self->getfield($field));
2889 if ( $value eq '' or $value eq 'Y' ) {
2890 $self->setfield($field, $value);
2893 return "Illegal (flag) field $field: $value";
2896 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2898 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2899 on the column first.
2903 sub ut_foreign_key {
2904 my( $self, $field, $table, $foreign ) = @_;
2905 return '' if $no_check_foreign;
2906 qsearchs($table, { $foreign => $self->getfield($field) })
2907 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2908 " in $table.$foreign";
2912 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2914 Like ut_foreign_key, except the null value is also allowed.
2918 sub ut_foreign_keyn {
2919 my( $self, $field, $table, $foreign ) = @_;
2920 $self->getfield($field)
2921 ? $self->ut_foreign_key($field, $table, $foreign)
2925 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2927 Checks this column as an agentnum, taking into account the current users's
2928 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2929 right or rights allowing no agentnum.
2933 sub ut_agentnum_acl {
2934 my( $self, $field ) = (shift, shift);
2935 my $null_acl = scalar(@_) ? shift : [];
2936 $null_acl = [ $null_acl ] unless ref($null_acl);
2938 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2939 return "Illegal agentnum: $error" if $error;
2941 my $curuser = $FS::CurrentUser::CurrentUser;
2943 if ( $self->$field() ) {
2945 return "Access denied"
2946 unless $curuser->agentnum($self->$field());
2950 return "Access denied"
2951 unless grep $curuser->access_right($_), @$null_acl;
2959 =item fields [ TABLE ]
2961 This is a wrapper for real_fields. Code that called
2962 fields before should probably continue to call fields.
2967 my $something = shift;
2969 if($something->isa('FS::Record')) {
2970 $table = $something->table;
2972 $table = $something;
2973 $something = "FS::$table";
2975 return (real_fields($table));
2979 =item encrypt($value)
2981 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2983 Returns the encrypted string.
2985 You should generally not have to worry about calling this, as the system handles this for you.
2990 my ($self, $value) = @_;
2991 my $encrypted = $value;
2993 if ($conf->exists('encryption')) {
2994 if ($self->is_encrypted($value)) {
2995 # Return the original value if it isn't plaintext.
2996 $encrypted = $value;
2999 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3000 # RSA doesn't like the empty string so let's pack it up
3001 # The database doesn't like the RSA data so uuencode it
3002 my $length = length($value)+1;
3003 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3005 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3012 =item is_encrypted($value)
3014 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3020 my ($self, $value) = @_;
3021 # Possible Bug - Some work may be required here....
3023 if ($value =~ /^M/ && length($value) > 80) {
3030 =item decrypt($value)
3032 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3034 You should generally not have to worry about calling this, as the system handles this for you.
3039 my ($self,$value) = @_;
3040 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3041 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
3043 if (ref($rsa_decrypt) =~ /::RSA/) {
3044 my $encrypted = unpack ("u*", $value);
3045 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3046 if ($@) {warn "Decryption Failed"};
3054 #Initialize the Module
3055 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3057 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
3058 $rsa_module = $conf->config('encryptionmodule');
3062 eval ("require $rsa_module"); # No need to import the namespace
3065 # Initialize Encryption
3066 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
3067 my $public_key = join("\n",$conf->config('encryptionpublickey'));
3068 $rsa_encrypt = $rsa_module->new_public_key($public_key);
3071 # Intitalize Decryption
3072 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
3073 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
3074 $rsa_decrypt = $rsa_module->new_private_key($private_key);
3078 =item h_search ACTION
3080 Given an ACTION, either "insert", or "delete", returns the appropriate history
3081 record corresponding to this record, if any.
3086 my( $self, $action ) = @_;
3088 my $table = $self->table;
3091 my $primary_key = dbdef->table($table)->primary_key;
3094 'table' => "h_$table",
3095 'hashref' => { $primary_key => $self->$primary_key(),
3096 'history_action' => $action,
3104 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3105 appropriate history record corresponding to this record, if any.
3110 my($self, $action) = @_;
3111 my $h = $self->h_search($action);
3112 $h ? $h->history_date : '';
3115 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3117 A class or object method. Executes the sql statement represented by SQL and
3118 returns a scalar representing the result: the first column of the first row.
3120 Dies on bogus SQL. Returns an empty string if no row is returned.
3122 Typically used for statments which return a single value such as "SELECT
3123 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3128 my($self, $sql) = (shift, shift);
3129 my $sth = dbh->prepare($sql) or die dbh->errstr;
3131 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3132 my $row = $sth->fetchrow_arrayref or return '';
3133 my $scalar = $row->[0];
3134 defined($scalar) ? $scalar : '';
3137 =item count [ WHERE ]
3139 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3140 with optional WHERE. Must be called as method on a class with an
3146 my($self, $where) = (shift, shift);
3147 my $table = $self->table or die 'count called on object of class '.ref($self);
3148 my $sql = "SELECT COUNT(*) FROM $table";
3149 $sql .= " WHERE $where" if $where;
3150 $self->scalar_sql($sql);
3159 =item real_fields [ TABLE ]
3161 Returns a list of the real columns in the specified table. Called only by
3162 fields() and other subroutines elsewhere in FS::Record.
3169 my($table_obj) = dbdef->table($table);
3170 confess "Unknown table $table" unless $table_obj;
3171 $table_obj->columns;
3174 =item pvf FIELD_NAME
3176 Returns the FS::part_virtual_field object corresponding to a field in the
3177 record (specified by FIELD_NAME).
3182 my ($self, $name) = (shift, shift);
3184 if(grep /^$name$/, $self->virtual_fields) {
3186 my $concat = [ "'cf_'", "name" ];
3187 return qsearchs({ table => 'part_virtual_field',
3188 hashref => { dbtable => $self->table,
3191 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3197 =item _quote VALUE, TABLE, COLUMN
3199 This is an internal function used to construct SQL statements. It returns
3200 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3201 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3206 my($value, $table, $column) = @_;
3207 my $column_obj = dbdef->table($table)->column($column);
3208 my $column_type = $column_obj->type;
3209 my $nullable = $column_obj->null;
3211 utf8::upgrade($value);
3213 warn " $table.$column: $value ($column_type".
3214 ( $nullable ? ' NULL' : ' NOT NULL' ).
3215 ")\n" if $DEBUG > 2;
3217 if ( $value eq '' && $nullable ) {
3219 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3220 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3223 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3224 ! $column_type =~ /(char|binary|text)$/i ) {
3226 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3227 && driver_name eq 'Pg'
3231 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3232 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3233 # single-quote the whole mess, and put an "E" in front.
3234 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3242 This is deprecated. Don't use it.
3244 It returns a hash-type list with the fields of this record's table set true.
3249 carp "warning: hfields is deprecated";
3252 foreach (fields($table)) {
3261 "$_: ". $self->getfield($_). "|"
3262 } (fields($self->table)) );
3265 sub DESTROY { return; }
3269 # #use Carp qw(cluck);
3270 # #cluck "DESTROYING $self";
3271 # warn "DESTROYING $self";
3275 # return ! eval { join('',@_), kill 0; 1; };
3278 =item str2time_sql [ DRIVER_NAME ]
3280 Returns a function to convert to unix time based on database type, such as
3281 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3282 the str2time_sql_closing method to return a closing string rather than just
3283 using a closing parenthesis as previously suggested.
3285 You can pass an optional driver name such as "Pg", "mysql" or
3286 $dbh->{Driver}->{Name} to return a function for that database instead of
3287 the current database.
3292 my $driver = shift || driver_name;
3294 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3295 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3297 warn "warning: unknown database type $driver; guessing how to convert ".
3298 "dates to UNIX timestamps";
3299 return 'EXTRACT(EPOCH FROM ';
3303 =item str2time_sql_closing [ DRIVER_NAME ]
3305 Returns the closing suffix of a function to convert to unix time based on
3306 database type, such as ")::integer" for Pg or ")" for mysql.
3308 You can pass an optional driver name such as "Pg", "mysql" or
3309 $dbh->{Driver}->{Name} to return a function for that database instead of
3310 the current database.
3314 sub str2time_sql_closing {
3315 my $driver = shift || driver_name;
3317 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3321 =item regexp_sql [ DRIVER_NAME ]
3323 Returns the operator to do a regular expression comparison based on database
3324 type, such as '~' for Pg or 'REGEXP' for mysql.
3326 You can pass an optional driver name such as "Pg", "mysql" or
3327 $dbh->{Driver}->{Name} to return a function for that database instead of
3328 the current database.
3333 my $driver = shift || driver_name;
3335 return '~' if $driver =~ /^Pg/i;
3336 return 'REGEXP' if $driver =~ /^mysql/i;
3338 die "don't know how to use regular expressions in ". driver_name." databases";
3342 =item not_regexp_sql [ DRIVER_NAME ]
3344 Returns the operator to do a regular expression negation based on database
3345 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3347 You can pass an optional driver name such as "Pg", "mysql" or
3348 $dbh->{Driver}->{Name} to return a function for that database instead of
3349 the current database.
3353 sub not_regexp_sql {
3354 my $driver = shift || driver_name;
3356 return '!~' if $driver =~ /^Pg/i;
3357 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3359 die "don't know how to use regular expressions in ". driver_name." databases";
3363 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3365 Returns the items concatenated based on database type, using "CONCAT()" for
3366 mysql and " || " for Pg and other databases.
3368 You can pass an optional driver name such as "Pg", "mysql" or
3369 $dbh->{Driver}->{Name} to return a function for that database instead of
3370 the current database.
3375 my $driver = ref($_[0]) ? driver_name : shift;
3378 if ( $driver =~ /^mysql/i ) {
3379 'CONCAT('. join(',', @$items). ')';
3381 join('||', @$items);
3386 =item midnight_sql DATE
3388 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3389 on that day in the system timezone, using the default driver name.
3394 my $driver = driver_name;
3396 if ( $driver =~ /^mysql/i ) {
3397 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3400 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3408 This module should probably be renamed, since much of the functionality is
3409 of general use. It is not completely unlike Adapter::DBI (see below).
3411 Exported qsearch and qsearchs should be deprecated in favor of method calls
3412 (against an FS::Record object like the old search and searchs that qsearch
3413 and qsearchs were on top of.)
3415 The whole fields / hfields mess should be removed.
3417 The various WHERE clauses should be subroutined.
3419 table string should be deprecated in favor of DBIx::DBSchema::Table.
3421 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3422 true maps to the database (and WHERE clauses) would also help.
3424 The ut_ methods should ask the dbdef for a default length.
3426 ut_sqltype (like ut_varchar) should all be defined
3428 A fallback check method should be provided which uses the dbdef.
3430 The ut_money method assumes money has two decimal digits.
3432 The Pg money kludge in the new method only strips `$'.
3434 The ut_phonen method only checks US-style phone numbers.
3436 The _quote function should probably use ut_float instead of a regex.
3438 All the subroutines probably should be methods, here or elsewhere.
3440 Probably should borrow/use some dbdef methods where appropriate (like sub
3443 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3444 or allow it to be set. Working around it is ugly any way around - DBI should
3445 be fixed. (only affects RDBMS which return uppercase column names)
3447 ut_zip should take an optional country like ut_phone.
3451 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3453 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.