4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 $money_char $lat_lower $lon_upper
8 $nowarn_identical $nowarn_classload
9 $no_update_diff $no_history $qsearch_qualify_columns
14 use Carp qw(carp cluck croak confess);
15 use Scalar::Util qw( blessed );
16 use File::CounterFile;
19 use File::Slurp qw( slurp );
20 use DBI qw(:sql_types);
21 use DBIx::DBSchema 0.38;
22 use FS::UID qw(dbh getotaker datasrc driver_name);
24 use FS::Schema qw(dbdef);
26 use FS::Msgcat qw(gettext);
27 use NetAddr::IP; # for validation
29 #use FS::Conf; #dependency loop bs, in install_callback below instead
31 use FS::part_virtual_field;
37 @encrypt_payby = qw( CARD DCRD CHEK DCHK );
39 #export dbdef for now... everything else expects to find it here
41 dbh fields hfields qsearch qsearchs dbdef jsearch
42 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql
43 concat_sql group_concat_sql
50 $nowarn_identical = 0;
51 $nowarn_classload = 0;
55 $qsearch_qualify_columns = 0;
57 $no_check_foreign = 0;
65 our $conf_encryption = '';
66 our $conf_encryptionmodule = '';
67 our $conf_encryptionpublickey = '';
68 our $conf_encryptionprivatekey = '';
69 FS::UID->install_callback( sub {
73 $conf = FS::Conf->new;
74 $conf_encryption = $conf->exists('encryption');
75 $conf_encryptionmodule = $conf->config('encryptionmodule');
76 $conf_encryptionpublickey = join("\n",$conf->config('encryptionpublickey'));
77 $conf_encryptionprivatekey = join("\n",$conf->config('encryptionprivatekey'));
78 $money_char = $conf->config('money_char') || '$';
79 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
80 $lat_lower = $nw_coords ? 1 : -90;
81 $lon_upper = $nw_coords ? -1 : 180;
83 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
85 if ( driver_name eq 'Pg' ) {
86 eval "use DBD::Pg ':pg_types'";
89 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
96 FS::Record - Database record objects
101 use FS::Record qw(dbh fields qsearch qsearchs);
103 $record = new FS::Record 'table', \%hash;
104 $record = new FS::Record 'table', { 'column' => 'value', ... };
106 $record = qsearchs FS::Record 'table', \%hash;
107 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
108 @records = qsearch FS::Record 'table', \%hash;
109 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
111 $table = $record->table;
112 $dbdef_table = $record->dbdef_table;
114 $value = $record->get('column');
115 $value = $record->getfield('column');
116 $value = $record->column;
118 $record->set( 'column' => 'value' );
119 $record->setfield( 'column' => 'value' );
120 $record->column('value');
122 %hash = $record->hash;
124 $hashref = $record->hashref;
126 $error = $record->insert;
128 $error = $record->delete;
130 $error = $new_record->replace($old_record);
132 # external use deprecated - handled by the database (at least for Pg, mysql)
133 $value = $record->unique('column');
135 $error = $record->ut_float('column');
136 $error = $record->ut_floatn('column');
137 $error = $record->ut_number('column');
138 $error = $record->ut_numbern('column');
139 $error = $record->ut_decimal('column');
140 $error = $record->ut_decimaln('column');
141 $error = $record->ut_snumber('column');
142 $error = $record->ut_snumbern('column');
143 $error = $record->ut_money('column');
144 $error = $record->ut_text('column');
145 $error = $record->ut_textn('column');
146 $error = $record->ut_alpha('column');
147 $error = $record->ut_alphan('column');
148 $error = $record->ut_phonen('column');
149 $error = $record->ut_anything('column');
150 $error = $record->ut_name('column');
152 $quoted_value = _quote($value,'table','field');
155 $fields = hfields('table');
156 if ( $fields->{Field} ) { # etc.
158 @fields = fields 'table'; #as a subroutine
159 @fields = $record->fields; #as a method call
164 (Mostly) object-oriented interface to database records. Records are currently
165 implemented on top of DBI. FS::Record is intended as a base class for
166 table-specific classes to inherit from, i.e. FS::cust_main.
172 =item new [ TABLE, ] HASHREF
174 Creates a new record. It doesn't store it in the database, though. See
175 L<"insert"> for that.
177 Note that the object stores this hash reference, not a distinct copy of the
178 hash it points to. You can ask the object for a copy with the I<hash>
181 TABLE can only be omitted when a dervived class overrides the table method.
187 my $class = ref($proto) || $proto;
189 bless ($self, $class);
191 unless ( defined ( $self->table ) ) {
192 $self->{'Table'} = shift;
193 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
194 unless $nowarn_classload;
197 $self->{'Hash'} = shift;
199 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
200 $self->{'Hash'}{$field}='';
203 $self->_rebless if $self->can('_rebless');
205 $self->{'modified'} = 0;
207 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
214 my $class = ref($proto) || $proto;
216 bless ($self, $class);
218 $self->{'Table'} = shift unless defined ( $self->table );
220 my $hashref = $self->{'Hash'} = shift;
222 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
223 my $obj = $cache->cache->{$hashref->{$cache->key}};
224 $obj->_cache($hashref, $cache) if $obj->can('_cache');
227 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
234 my $class = ref($proto) || $proto;
236 bless ($self, $class);
237 if ( defined $self->table ) {
238 cluck "create constructor is deprecated, use new!";
241 croak "FS::Record::create called (not from a subclass)!";
245 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
247 Searches the database for all records matching (at least) the key/value pairs
248 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
249 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
252 The preferred usage is to pass a hash reference of named parameters:
254 @records = qsearch( {
255 'table' => 'table_name',
256 'hashref' => { 'field' => 'value'
257 'field' => { 'op' => '<',
262 #these are optional...
264 'extra_sql' => 'AND field = ? AND intfield = ?',
265 'extra_param' => [ 'value', [ 5, 'int' ] ],
266 'order_by' => 'ORDER BY something',
267 #'cache_obj' => '', #optional
268 'addl_from' => 'LEFT JOIN othtable USING ( field )',
273 Much code still uses old-style positional parameters, this is also probably
274 fine in the common case where there are only two parameters:
276 my @records = qsearch( 'table', { 'field' => 'value' } );
278 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
279 the individual PARAMS_HASHREF queries
281 ###oops, argh, FS::Record::new only lets us create database fields.
282 #Normal behaviour if SELECT is not specified is `*', as in
283 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
284 #feature where you can specify SELECT - remember, the objects returned,
285 #although blessed into the appropriate `FS::TABLE' package, will only have the
286 #fields you specify. This might have unwanted results if you then go calling
287 #regular FS::TABLE methods
292 my %TYPE = (); #for debugging
295 my($type, $value) = @_;
297 my $bind_type = { TYPE => SQL_VARCHAR };
299 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
301 $bind_type = { TYPE => SQL_INTEGER };
303 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
305 if ( driver_name eq 'Pg' ) {
307 $bind_type = { pg_type => PG_BYTEA };
309 # $bind_type = ? #SQL_VARCHAR could be fine?
312 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
313 #fixed by DBD::Pg 2.11.8
314 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
315 #(make a Tron test first)
316 } elsif ( _is_fs_float( $type, $value ) ) {
318 $bind_type = { TYPE => SQL_DECIMAL };
327 my($type, $value) = @_;
328 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
329 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
337 my( @stable, @record, @cache );
338 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
340 my %union_options = ();
341 if ( ref($_[0]) eq 'ARRAY' ) {
344 foreach my $href ( @$optlist ) {
345 push @stable, ( $href->{'table'} or die "table name is required" );
346 push @record, ( $href->{'hashref'} || {} );
347 push @select, ( $href->{'select'} || '*' );
348 push @extra_sql, ( $href->{'extra_sql'} || '' );
349 push @extra_param, ( $href->{'extra_param'} || [] );
350 push @order_by, ( $href->{'order_by'} || '' );
351 push @cache, ( $href->{'cache_obj'} || '' );
352 push @addl_from, ( $href->{'addl_from'} || '' );
353 push @debug, ( $href->{'debug'} || '' );
355 die "at least one hashref is required" unless scalar(@stable);
356 } elsif ( ref($_[0]) eq 'HASH' ) {
358 $stable[0] = $opt->{'table'} or die "table name is required";
359 $record[0] = $opt->{'hashref'} || {};
360 $select[0] = $opt->{'select'} || '*';
361 $extra_sql[0] = $opt->{'extra_sql'} || '';
362 $extra_param[0] = $opt->{'extra_param'} || [];
363 $order_by[0] = $opt->{'order_by'} || '';
364 $cache[0] = $opt->{'cache_obj'} || '';
365 $addl_from[0] = $opt->{'addl_from'} || '';
366 $debug[0] = $opt->{'debug'} || '';
377 my $cache = $cache[0];
383 foreach my $stable ( @stable ) {
384 #stop altering the caller's hashref
385 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
386 my $select = shift @select;
387 my $extra_sql = shift @extra_sql;
388 my $extra_param = shift @extra_param;
389 my $order_by = shift @order_by;
390 my $cache = shift @cache;
391 my $addl_from = shift @addl_from;
392 my $debug = shift @debug;
394 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
396 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
399 my $table = $cache ? $cache->table : $stable;
400 my $dbdef_table = dbdef->table($table)
401 or die "No schema for table $table found - ".
402 "do you need to run freeside-upgrade?";
403 my $pkey = $dbdef_table->primary_key;
405 my @real_fields = grep exists($record->{$_}), real_fields($table);
407 my $statement .= "SELECT $select FROM $stable";
408 $statement .= " $addl_from" if $addl_from;
409 if ( @real_fields ) {
410 $statement .= ' WHERE '. join(' AND ',
411 get_real_fields($table, $record, \@real_fields));
414 $statement .= " $extra_sql" if defined($extra_sql);
415 $statement .= " $order_by" if defined($order_by);
417 push @statement, $statement;
419 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
423 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
426 my $value = $record->{$field};
427 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
428 $value = $value->{'value'} if ref($value);
429 my $type = dbdef->table($table)->column($field)->type;
431 my $bind_type = _bind_type($type, $value);
435 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
437 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
441 push @bind_type, $bind_type;
445 foreach my $param ( @$extra_param ) {
446 my $bind_type = { TYPE => SQL_VARCHAR };
449 $value = $param->[0];
450 my $type = $param->[1];
451 $bind_type = _bind_type($type, $value);
454 push @bind_type, $bind_type;
458 my $statement = join( ' ) UNION ( ', @statement );
459 $statement = "( $statement )" if scalar(@statement) > 1;
460 $statement .= " $union_options{order_by}" if $union_options{order_by};
462 my $sth = $dbh->prepare($statement)
463 or croak "$dbh->errstr doing $statement";
466 foreach my $value ( @value ) {
467 my $bind_type = shift @bind_type;
468 $sth->bind_param($bind++, $value, $bind_type );
471 # $sth->execute( map $record->{$_},
472 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
473 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
475 my $ok = $sth->execute;
477 my $error = "Error executing \"$statement\"";
478 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
479 $error .= ': '. $sth->errstr;
483 my $table = $stable[0];
485 $table = '' if grep { $_ ne $table } @stable;
486 $pkey = dbdef->table($table)->primary_key if $table;
489 tie %result, "Tie::IxHash";
490 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
491 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
492 %result = map { $_->{$pkey}, $_ } @stuff;
494 @result{@stuff} = @stuff;
500 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
501 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
502 #derivied class didn't override new method, so this optimization is safe
505 new_or_cached( "FS::$table", { %{$_} }, $cache )
509 new( "FS::$table", { %{$_} } )
513 #okay, its been tested
514 # warn "untested code (class FS::$table uses custom new method)";
516 eval 'FS::'. $table. '->new( { %{$_} } )';
520 # Check for encrypted fields and decrypt them.
521 ## only in the local copy, not the cached object
522 no warnings 'deprecated'; # XXX silence the warning for now
523 if ( $conf_encryption
524 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
525 foreach my $record (@return) {
526 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
527 next if $field eq 'payinfo'
528 && ($record->isa('FS::payinfo_transaction_Mixin')
529 || $record->isa('FS::payinfo_Mixin') )
531 && !grep { $record->payby eq $_ } @encrypt_payby;
532 # Set it directly... This may cause a problem in the future...
533 $record->setfield($field, $record->decrypt($record->getfield($field)));
538 cluck "warning: FS::$table not loaded; returning FS::Record objects"
539 unless $nowarn_classload;
541 FS::Record->new( $table, { %{$_} } );
549 Construct the SQL statement and parameter-binding list for qsearch. Takes
550 the qsearch parameters.
552 Returns a hash containing:
553 'table': The primary table name (if there is one).
554 'statement': The SQL statement itself.
555 'bind_type': An arrayref of bind types.
556 'value': An arrayref of parameter values.
557 'cache': The cache object, if one was passed.
562 my( @stable, @record, @cache );
563 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
566 my %union_options = ();
567 if ( ref($_[0]) eq 'ARRAY' ) {
570 foreach my $href ( @$optlist ) {
571 push @stable, ( $href->{'table'} or die "table name is required" );
572 push @record, ( $href->{'hashref'} || {} );
573 push @select, ( $href->{'select'} || '*' );
574 push @extra_sql, ( $href->{'extra_sql'} || '' );
575 push @extra_param, ( $href->{'extra_param'} || [] );
576 push @order_by, ( $href->{'order_by'} || '' );
577 push @cache, ( $href->{'cache_obj'} || '' );
578 push @addl_from, ( $href->{'addl_from'} || '' );
579 push @debug, ( $href->{'debug'} || '' );
581 die "at least one hashref is required" unless scalar(@stable);
582 } elsif ( ref($_[0]) eq 'HASH' ) {
584 $stable[0] = $opt->{'table'} or die "table name is required";
585 $record[0] = $opt->{'hashref'} || {};
586 $select[0] = $opt->{'select'} || '*';
587 $extra_sql[0] = $opt->{'extra_sql'} || '';
588 $extra_param[0] = $opt->{'extra_param'} || [];
589 $order_by[0] = $opt->{'order_by'} || '';
590 $cache[0] = $opt->{'cache_obj'} || '';
591 $addl_from[0] = $opt->{'addl_from'} || '';
592 $debug[0] = $opt->{'debug'} || '';
603 my $cache = $cache[0];
609 my $result_table = $stable[0];
610 foreach my $stable ( @stable ) {
611 #stop altering the caller's hashref
612 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
613 my $select = shift @select;
614 my $extra_sql = shift @extra_sql;
615 my $extra_param = shift @extra_param;
616 my $order_by = shift @order_by;
617 my $cache = shift @cache;
618 my $addl_from = shift @addl_from;
619 my $debug = shift @debug;
621 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
623 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
626 $result_table = '' if $result_table ne $stable;
628 my $table = $cache ? $cache->table : $stable;
629 my $dbdef_table = dbdef->table($table)
630 or die "No schema for table $table found - ".
631 "do you need to run freeside-upgrade?";
632 my $pkey = $dbdef_table->primary_key;
634 my @real_fields = grep exists($record->{$_}), real_fields($table);
636 my $statement .= "SELECT $select FROM $stable";
637 $statement .= " $addl_from" if $addl_from;
638 if ( @real_fields ) {
639 $statement .= ' WHERE '. join(' AND ',
640 get_real_fields($table, $record, \@real_fields));
643 $statement .= " $extra_sql" if defined($extra_sql);
644 $statement .= " $order_by" if defined($order_by);
646 push @statement, $statement;
648 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
652 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
655 my $value = $record->{$field};
656 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
657 $value = $value->{'value'} if ref($value);
658 my $type = dbdef->table($table)->column($field)->type;
660 my $bind_type = _bind_type($type, $value);
664 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
666 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
670 push @bind_type, $bind_type;
674 foreach my $param ( @$extra_param ) {
675 my $bind_type = { TYPE => SQL_VARCHAR };
678 $value = $param->[0];
679 my $type = $param->[1];
680 $bind_type = _bind_type($type, $value);
683 push @bind_type, $bind_type;
687 my $statement = join( ' ) UNION ( ', @statement );
688 $statement = "( $statement )" if scalar(@statement) > 1;
689 $statement .= " $union_options{order_by}" if $union_options{order_by};
692 statement => $statement,
693 bind_type => \@bind_type,
695 table => $result_table,
700 # qsearch should eventually use this
702 my ($table, $cache, @hashrefs) = @_;
704 # XXX get rid of these string evals at some point
705 # (when we have time to test it)
706 # my $class = "FS::$table" if $table;
707 # if ( $class and $class->isa('FS::Record') )
708 # if ( $class->can('new') eq \&new )
710 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
711 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
712 #derivied class didn't override new method, so this optimization is safe
715 new_or_cached( "FS::$table", { %{$_} }, $cache )
719 new( "FS::$table", { %{$_} } )
723 #okay, its been tested
724 # warn "untested code (class FS::$table uses custom new method)";
726 eval 'FS::'. $table. '->new( { %{$_} } )';
730 # Check for encrypted fields and decrypt them.
731 ## only in the local copy, not the cached object
732 if ( $conf_encryption
733 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
734 foreach my $record (@return) {
735 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
736 next if $field eq 'payinfo'
737 && ($record->isa('FS::payinfo_transaction_Mixin')
738 || $record->isa('FS::payinfo_Mixin') )
740 && !grep { $record->payby eq $_ } @encrypt_payby;
741 # Set it directly... This may cause a problem in the future...
742 $record->setfield($field, $record->decrypt($record->getfield($field)));
747 cluck "warning: FS::$table not loaded; returning FS::Record objects"
748 unless $nowarn_classload;
750 FS::Record->new( $table, { %{$_} } );
756 sub get_real_fields {
759 my $real_fields = shift;
761 ## could be optimized more for readability
767 my $table_column = $qsearch_qualify_columns ? "$table.$column" : $column;
768 my $type = dbdef->table($table)->column($column)->type;
769 my $value = $record->{$column};
770 $value = $value->{'value'} if ref($value);
772 if ( ref($record->{$column}) ) {
773 $op = $record->{$column}{'op'} if $record->{$column}{'op'};
774 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
775 if ( uc($op) eq 'ILIKE' ) {
777 $record->{$column}{'value'} = lc($record->{$column}{'value'});
778 $table_column = "LOWER($table_column)";
780 $record->{$column} = $record->{$column}{'value'}
783 if ( ! defined( $record->{$column} ) || $record->{$column} eq '' ) {
785 if ( driver_name eq 'Pg' ) {
786 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
787 qq-( $table_column IS NULL )-;
789 qq-( $table_column IS NULL OR $table_column = '' )-;
792 qq-( $table_column IS NULL OR $table_column = "" )-;
794 } elsif ( $op eq '!=' ) {
795 if ( driver_name eq 'Pg' ) {
796 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
797 qq-( $table_column IS NOT NULL )-;
799 qq-( $table_column IS NOT NULL AND $table_column != '' )-;
802 qq-( $table_column IS NOT NULL AND $table_column != "" )-;
805 if ( driver_name eq 'Pg' ) {
806 qq-( $table_column $op '' )-;
808 qq-( $table_column $op "" )-;
811 } elsif ( $op eq '!=' ) {
812 qq-( $table_column IS NULL OR $table_column != ? )-;
813 #if this needs to be re-enabled, it needs to use a custom op like
814 #"APPROX=" or something (better name?, not '=', to avoid affecting other
816 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
817 # ( "$table_column <= ?", "$table_column >= ?" );
819 "$table_column $op ?";
826 =item by_key PRIMARY_KEY_VALUE
828 This is a class method that returns the record with the given primary key
829 value. This method is only useful in FS::Record subclasses. For example:
831 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
835 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
840 my ($class, $pkey_value) = @_;
842 my $table = $class->table
843 or croak "No table for $class found";
845 my $dbdef_table = dbdef->table($table)
846 or die "No schema for table $table found - ".
847 "do you need to create it or run dbdef-create?";
848 my $pkey = $dbdef_table->primary_key
849 or die "No primary key for table $table";
851 return qsearchs($table, { $pkey => $pkey_value });
854 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
856 Experimental JOINed search method. Using this method, you can execute a
857 single SELECT spanning multiple tables, and cache the results for subsequent
858 method calls. Interface will almost definately change in an incompatible
866 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
867 my $cache = FS::SearchCache->new( $ptable, $pkey );
870 grep { !$saw{$_->getfield($pkey)}++ }
871 qsearch($table, $record, $select, $extra_sql, $cache )
875 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
877 Same as qsearch, except that if more than one record matches, it B<carp>s but
878 returns the first. If this happens, you either made a logic error in asking
879 for a single item, or your data is corrupted.
883 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
885 my(@result) = qsearch(@_);
886 cluck "warning: Multiple records in scalar search ($table)"
887 if scalar(@result) > 1;
888 #should warn more vehemently if the search was on a primary key?
889 scalar(@result) ? ($result[0]) : ();
900 Returns the table name.
905 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
912 Returns the DBIx::DBSchema::Table object for the table.
918 my($table)=$self->table;
919 dbdef->table($table);
924 Returns the primary key for the table.
930 my $pkey = $self->dbdef_table->primary_key;
933 =item get, getfield COLUMN
935 Returns the value of the column/field/key COLUMN.
940 my($self,$field) = @_;
941 # to avoid "Use of unitialized value" errors
942 if ( defined ( $self->{Hash}->{$field} ) ) {
943 $self->{Hash}->{$field};
953 =item set, setfield COLUMN, VALUE
955 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
960 my($self,$field,$value) = @_;
961 $self->{'modified'} = 1;
962 $self->{'Hash'}->{$field} = $value;
971 Returns true if the column/field/key COLUMN exists.
976 my($self,$field) = @_;
977 exists($self->{Hash}->{$field});
980 =item AUTLOADED METHODS
982 $record->column is a synonym for $record->get('column');
984 $record->column('value') is a synonym for $record->set('column','value');
991 my($field)=$AUTOLOAD;
993 if ( defined($value) ) {
994 confess "errant AUTOLOAD $field for $self (arg $value)"
995 unless blessed($self) && $self->can('setfield');
996 $self->setfield($field,$value);
998 confess "errant AUTOLOAD $field for $self (no args)"
999 unless blessed($self) && $self->can('getfield');
1000 $self->getfield($field);
1006 # my $field = $AUTOLOAD;
1007 # $field =~ s/.*://;
1008 # if ( defined($_[1]) ) {
1009 # $_[0]->setfield($field, $_[1]);
1011 # $_[0]->getfield($field);
1017 Returns a list of the column/value pairs, usually for assigning to a new hash.
1019 To make a distinct duplicate of an FS::Record object, you can do:
1021 $new = new FS::Record ( $old->table, { $old->hash } );
1027 confess $self. ' -> hash: Hash attribute is undefined'
1028 unless defined($self->{'Hash'});
1029 %{ $self->{'Hash'} };
1034 Returns a reference to the column/value hash. This may be deprecated in the
1035 future; if there's a reason you can't just use the autoloaded or get/set
1047 Returns true if any of this object's values have been modified with set (or via
1048 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1055 $self->{'modified'};
1058 =item select_for_update
1060 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1065 sub select_for_update {
1067 my $primary_key = $self->primary_key;
1070 'table' => $self->table,
1071 'hashref' => { $primary_key => $self->$primary_key() },
1072 'extra_sql' => 'FOR UPDATE',
1078 Locks this table with a database-driver specific lock method. This is used
1079 as a mutex in order to do a duplicate search.
1081 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1083 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1085 Errors are fatal; no useful return value.
1087 Note: To use this method for new tables other than svc_acct and svc_phone,
1088 edit freeside-upgrade and add those tables to the duplicate_lock list.
1094 my $table = $self->table;
1096 warn "$me locking $table table\n" if $DEBUG;
1098 if ( driver_name =~ /^Pg/i ) {
1100 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1103 } elsif ( driver_name =~ /^mysql/i ) {
1105 dbh->do("SELECT * FROM duplicate_lock
1106 WHERE lockname = '$table'
1108 ) or die dbh->errstr;
1112 die "unknown database ". driver_name. "; don't know how to lock table";
1116 warn "$me acquired $table table lock\n" if $DEBUG;
1122 Inserts this record to the database. If there is an error, returns the error,
1123 otherwise returns false.
1131 warn "$self -> insert" if $DEBUG;
1133 my $error = $self->check;
1134 return $error if $error;
1136 #single-field non-null unique keys are given a value if empty
1137 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1138 foreach ( $self->dbdef_table->unique_singles) {
1139 next if $self->getfield($_);
1140 next if $self->dbdef_table->column($_)->null eq 'NULL';
1144 #and also the primary key, if the database isn't going to
1145 my $primary_key = $self->dbdef_table->primary_key;
1147 if ( $primary_key ) {
1148 my $col = $self->dbdef_table->column($primary_key);
1151 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1152 || ( driver_name eq 'Pg'
1153 && defined($col->default)
1154 && $col->quoted_default =~ /^nextval\(/i
1156 || ( driver_name eq 'mysql'
1157 && defined($col->local)
1158 && $col->local =~ /AUTO_INCREMENT/i
1160 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1163 my $table = $self->table;
1165 # Encrypt before the database
1166 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
1167 && scalar( eval '@FS::'. $table . '::encrypted_fields')
1170 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1171 next if $field eq 'payinfo'
1172 && ($self->isa('FS::payinfo_transaction_Mixin')
1173 || $self->isa('FS::payinfo_Mixin') )
1175 && !grep { $self->payby eq $_ } @encrypt_payby;
1176 $saved->{$field} = $self->getfield($field);
1177 $self->setfield($field, $self->encrypt($self->getfield($field)));
1181 #false laziness w/delete
1183 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1186 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1189 my $statement = "INSERT INTO $table ";
1190 if ( @real_fields ) {
1193 join( ', ', @real_fields ).
1195 join( ', ', @values ).
1199 $statement .= 'DEFAULT VALUES';
1201 warn "[debug]$me $statement\n" if $DEBUG > 1;
1202 my $sth = dbh->prepare($statement) or return dbh->errstr;
1204 local $SIG{HUP} = 'IGNORE';
1205 local $SIG{INT} = 'IGNORE';
1206 local $SIG{QUIT} = 'IGNORE';
1207 local $SIG{TERM} = 'IGNORE';
1208 local $SIG{TSTP} = 'IGNORE';
1209 local $SIG{PIPE} = 'IGNORE';
1211 $sth->execute or return $sth->errstr;
1213 # get inserted id from the database, if applicable & needed
1214 if ( $db_seq && ! $self->getfield($primary_key) ) {
1215 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1219 if ( driver_name eq 'Pg' ) {
1221 #my $oid = $sth->{'pg_oid_status'};
1222 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1224 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1225 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1226 dbh->rollback if $FS::UID::AutoCommit;
1227 return "can't parse $table.$primary_key default value".
1228 " for sequence name: $default";
1232 my $i_sql = "SELECT currval('$sequence')";
1233 my $i_sth = dbh->prepare($i_sql) or do {
1234 dbh->rollback if $FS::UID::AutoCommit;
1237 $i_sth->execute() or do { #$i_sth->execute($oid)
1238 dbh->rollback if $FS::UID::AutoCommit;
1239 return $i_sth->errstr;
1241 $insertid = $i_sth->fetchrow_arrayref->[0];
1243 } elsif ( driver_name eq 'mysql' ) {
1245 $insertid = dbh->{'mysql_insertid'};
1246 # work around mysql_insertid being null some of the time, ala RT :/
1247 unless ( $insertid ) {
1248 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1249 "using SELECT LAST_INSERT_ID();";
1250 my $i_sql = "SELECT LAST_INSERT_ID()";
1251 my $i_sth = dbh->prepare($i_sql) or do {
1252 dbh->rollback if $FS::UID::AutoCommit;
1255 $i_sth->execute or do {
1256 dbh->rollback if $FS::UID::AutoCommit;
1257 return $i_sth->errstr;
1259 $insertid = $i_sth->fetchrow_arrayref->[0];
1264 dbh->rollback if $FS::UID::AutoCommit;
1265 return "don't know how to retreive inserted ids from ". driver_name.
1266 ", try using counterfiles (maybe run dbdef-create?)";
1270 $self->setfield($primary_key, $insertid);
1275 if ( defined( dbdef->table('h_'. $table) ) && ! $no_history ) {
1276 my $h_statement = $self->_h_statement('insert');
1277 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1278 $h_sth = dbh->prepare($h_statement) or do {
1279 dbh->rollback if $FS::UID::AutoCommit;
1285 $h_sth->execute or return $h_sth->errstr if $h_sth;
1287 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1289 # Now that it has been saved, reset the encrypted fields so that $new
1290 # can still be used.
1291 foreach my $field (keys %{$saved}) {
1292 $self->setfield($field, $saved->{$field});
1300 Depriciated (use insert instead).
1305 cluck "warning: FS::Record::add deprecated!";
1306 insert @_; #call method in this scope
1311 Delete this record from the database. If there is an error, returns the error,
1312 otherwise returns false.
1319 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1321 $self->getfield($_) eq ''
1322 #? "( $_ IS NULL OR $_ = \"\" )"
1323 ? ( driver_name eq 'Pg'
1325 : "( $_ IS NULL OR $_ = \"\" )"
1327 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1328 } ( $self->dbdef_table->primary_key )
1329 ? ( $self->dbdef_table->primary_key)
1330 : real_fields($self->table)
1332 warn "[debug]$me $statement\n" if $DEBUG > 1;
1333 my $sth = dbh->prepare($statement) or return dbh->errstr;
1336 if ( defined dbdef->table('h_'. $self->table) ) {
1337 my $h_statement = $self->_h_statement('delete');
1338 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1339 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1344 my $primary_key = $self->dbdef_table->primary_key;
1346 local $SIG{HUP} = 'IGNORE';
1347 local $SIG{INT} = 'IGNORE';
1348 local $SIG{QUIT} = 'IGNORE';
1349 local $SIG{TERM} = 'IGNORE';
1350 local $SIG{TSTP} = 'IGNORE';
1351 local $SIG{PIPE} = 'IGNORE';
1353 my $rc = $sth->execute or return $sth->errstr;
1354 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1355 $h_sth->execute or return $h_sth->errstr if $h_sth;
1357 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1359 #no need to needlessly destoy the data either (causes problems actually)
1360 #undef $self; #no need to keep object!
1367 Depriciated (use delete instead).
1372 cluck "warning: FS::Record::del deprecated!";
1373 &delete(@_); #call method in this scope
1376 =item replace OLD_RECORD
1378 Replace the OLD_RECORD with this one in the database. If there is an error,
1379 returns the error, otherwise returns false.
1384 my ($new, $old) = (shift, shift);
1386 $old = $new->replace_old unless defined($old);
1388 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1390 if ( $new->can('replace_check') ) {
1391 my $error = $new->replace_check($old);
1392 return $error if $error;
1395 return "Records not in same table!" unless $new->table eq $old->table;
1397 my $primary_key = $old->dbdef_table->primary_key;
1398 return "Can't change primary key $primary_key ".
1399 'from '. $old->getfield($primary_key).
1400 ' to ' . $new->getfield($primary_key)
1402 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1404 my $error = $new->check;
1405 return $error if $error;
1407 # Encrypt for replace
1409 if ( $conf_encryption
1410 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1411 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1413 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1414 next if $field eq 'payinfo'
1415 && ($new->isa('FS::payinfo_transaction_Mixin')
1416 || $new->isa('FS::payinfo_Mixin') )
1418 && !grep { $new->payby eq $_ } @encrypt_payby;
1419 $saved->{$field} = $new->getfield($field);
1420 $new->setfield($field, $new->encrypt($new->getfield($field)));
1424 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1425 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1426 ? ($_, $new->getfield($_)) : () } $old->fields;
1428 unless (keys(%diff) || $no_update_diff ) {
1429 carp "[warning]$me ". ref($new)."->replace ".
1430 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1431 ": records identical"
1432 unless $nowarn_identical;
1436 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1438 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1439 } real_fields($old->table)
1444 if ( $old->getfield($_) eq '' ) {
1446 #false laziness w/qsearch
1447 if ( driver_name eq 'Pg' ) {
1448 my $type = $old->dbdef_table->column($_)->type;
1449 if ( $type =~ /(int|(big)?serial)/i ) {
1452 qq-( $_ IS NULL OR $_ = '' )-;
1455 qq-( $_ IS NULL OR $_ = "" )-;
1459 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1462 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1465 warn "[debug]$me $statement\n" if $DEBUG > 1;
1466 my $sth = dbh->prepare($statement) or return dbh->errstr;
1469 if ( defined dbdef->table('h_'. $old->table) ) {
1470 my $h_old_statement = $old->_h_statement('replace_old');
1471 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1472 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1478 if ( defined dbdef->table('h_'. $new->table) ) {
1479 my $h_new_statement = $new->_h_statement('replace_new');
1480 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1481 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1486 local $SIG{HUP} = 'IGNORE';
1487 local $SIG{INT} = 'IGNORE';
1488 local $SIG{QUIT} = 'IGNORE';
1489 local $SIG{TERM} = 'IGNORE';
1490 local $SIG{TSTP} = 'IGNORE';
1491 local $SIG{PIPE} = 'IGNORE';
1493 my $rc = $sth->execute or return $sth->errstr;
1494 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1495 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1496 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1498 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1500 # Now that it has been saved, reset the encrypted fields so that $new
1501 # can still be used.
1502 foreach my $field (keys %{$saved}) {
1503 $new->setfield($field, $saved->{$field});
1511 my( $self ) = shift;
1512 warn "[$me] replace called with no arguments; autoloading old record\n"
1515 my $primary_key = $self->dbdef_table->primary_key;
1516 if ( $primary_key ) {
1517 $self->by_key( $self->$primary_key() ) #this is what's returned
1518 or croak "can't find ". $self->table. ".$primary_key ".
1519 $self->$primary_key();
1521 croak $self->table. " has no primary key; pass old record as argument";
1528 Depriciated (use replace instead).
1533 cluck "warning: FS::Record::rep deprecated!";
1534 replace @_; #call method in this scope
1539 Checks custom fields. Subclasses should still provide a check method to validate
1540 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1546 foreach my $field ($self->virtual_fields) {
1547 my $error = $self->ut_textn($field);
1548 return $error if $error;
1553 =item virtual_fields [ TABLE ]
1555 Returns a list of virtual fields defined for the table. This should not
1556 be exported, and should only be called as an instance or class method.
1560 sub virtual_fields {
1563 $table = $self->table or confess "virtual_fields called on non-table";
1565 confess "Unknown table $table" unless dbdef->table($table);
1567 return () unless dbdef->table('part_virtual_field');
1569 unless ( $virtual_fields_cache{$table} ) {
1570 my $concat = [ "'cf_'", "name" ];
1571 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1572 "WHERE dbtable = '$table'";
1574 my $result = $dbh->selectcol_arrayref($query);
1575 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1577 $virtual_fields_cache{$table} = $result;
1580 @{$virtual_fields_cache{$table}};
1584 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1586 Processes a batch import as a queued JSRPC job
1588 JOB is an FS::queue entry.
1590 OPTIONS_HASHREF can have the following keys:
1596 Table name (required).
1600 Arrayref of field names for static fields. They will be given values from the
1601 PARAMS hashref and passed as a "params" hashref to batch_import.
1605 Formats hashref. Keys are field names, values are listrefs that define the
1608 Each listref value can be a column name or a code reference. Coderefs are run
1609 with the row object, data and a FS::Conf object as the three parameters.
1610 For example, this coderef does the same thing as using the "columnname" string:
1613 my( $record, $data, $conf ) = @_;
1614 $record->columnname( $data );
1617 Coderefs are run after all "column name" fields are assigned.
1621 Optional format hashref of types. Keys are field names, values are "csv",
1622 "xls" or "fixedlength". Overrides automatic determination of file type
1625 =item format_headers
1627 Optional format hashref of header lines. Keys are field names, values are 0
1628 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1631 =item format_sep_chars
1633 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1634 CSV separation character.
1636 =item format_fixedlenth_formats
1638 Optional format hashref of fixed length format defintiions. Keys are field
1639 names, values Parse::FixedLength listrefs of field definitions.
1643 Set true to default to CSV file type if the filename does not contain a
1644 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1649 PARAMS is a hashref (or base64-encoded Storable hashref) containing the
1650 POSTed data. It must contain the field "uploaded files", generated by
1651 /elements/file-upload.html and containing the list of uploaded files.
1652 Currently only supports a single file named "file".
1656 # uploaded_files is kind of bizarre; fix that some time
1658 use Storable qw(thaw);
1661 sub process_batch_import {
1662 my($job, $opt) = ( shift, shift );
1664 my $table = $opt->{table};
1665 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1666 my %formats = %{ $opt->{formats} };
1669 # because some job-spawning code (JSRPC) pre-freezes the arguments,
1670 # and then the 'frozen' attribute doesn't get set, and thus $job->args
1671 # doesn't know to thaw them, we have to do this everywhere.
1673 $param = thaw(decode_base64($param));
1675 warn Dumper($param) if $DEBUG;
1677 my $files = $param->{'uploaded_files'}
1678 or die "No files provided.\n";
1680 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1682 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1683 my $file = $dir. $files{'file'};
1688 formats => \%formats,
1689 format_types => $opt->{format_types},
1690 format_headers => $opt->{format_headers},
1691 format_sep_chars => $opt->{format_sep_chars},
1692 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1693 format_xml_formats => $opt->{format_xml_formats},
1694 format_asn_formats => $opt->{format_asn_formats},
1695 format_row_callbacks => $opt->{format_row_callbacks},
1696 format_hash_callbacks => $opt->{format_hash_callbacks},
1701 format => $param->{format},
1702 params => { map { $_ => $param->{$_} } @pass_params },
1704 default_csv => $opt->{default_csv},
1705 preinsert_callback => $opt->{preinsert_callback},
1706 postinsert_callback => $opt->{postinsert_callback},
1707 insert_args_callback => $opt->{insert_args_callback},
1710 if ( $opt->{'batch_namecol'} ) {
1711 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1712 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1715 my $error = FS::Record::batch_import( \%iopt );
1719 die "$error\n" if $error;
1722 =item batch_import PARAM_HASHREF
1724 Class method for batch imports. Available params:
1730 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1736 =item format_headers
1738 =item format_sep_chars
1740 =item format_fixedlength_formats
1742 =item format_row_callbacks
1744 =item format_hash_callbacks - After parsing, before object creation
1746 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1748 =item preinsert_callback
1750 =item postinsert_callback
1756 FS::queue object, will be updated with progress
1762 csv, xls, fixedlength, xml
1773 warn "$me batch_import call with params: \n". Dumper($param)
1776 my $table = $param->{table};
1778 my $job = $param->{job};
1779 my $file = $param->{file};
1780 my $params = $param->{params} || {};
1782 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1783 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1785 my( $type, $header, $sep_char,
1786 $fixedlength_format, $xml_format, $asn_format,
1787 $parser_opt, $row_callback, $hash_callback, @fields );
1789 my $postinsert_callback = '';
1790 $postinsert_callback = $param->{'postinsert_callback'}
1791 if $param->{'postinsert_callback'};
1792 my $preinsert_callback = '';
1793 $preinsert_callback = $param->{'preinsert_callback'}
1794 if $param->{'preinsert_callback'};
1795 my $insert_args_callback = '';
1796 $insert_args_callback = $param->{'insert_args_callback'}
1797 if $param->{'insert_args_callback'};
1799 if ( $param->{'format'} ) {
1801 my $format = $param->{'format'};
1802 my $formats = $param->{formats};
1803 die "unknown format $format" unless exists $formats->{ $format };
1805 $type = $param->{'format_types'}
1806 ? $param->{'format_types'}{ $format }
1807 : $param->{type} || 'csv';
1810 $header = $param->{'format_headers'}
1811 ? $param->{'format_headers'}{ $param->{'format'} }
1814 $sep_char = $param->{'format_sep_chars'}
1815 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1818 $fixedlength_format =
1819 $param->{'format_fixedlength_formats'}
1820 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1824 $param->{'format_parser_opts'}
1825 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1829 $param->{'format_xml_formats'}
1830 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1834 $param->{'format_asn_formats'}
1835 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1839 $param->{'format_row_callbacks'}
1840 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1844 $param->{'format_hash_callbacks'}
1845 ? $param->{'format_hash_callbacks'}{ $param->{'format'} }
1848 @fields = @{ $formats->{ $format } };
1850 } elsif ( $param->{'fields'} ) {
1852 $type = ''; #infer from filename
1855 $fixedlength_format = '';
1857 $hash_callback = '';
1858 @fields = @{ $param->{'fields'} };
1861 die "neither format nor fields specified";
1864 #my $file = $param->{file};
1867 if ( $file =~ /\.(\w+)$/i ) {
1871 warn "can't parse file type from filename $file; defaulting to CSV";
1875 if $param->{'default_csv'} && $type ne 'xls';
1883 my $asn_header_buffer;
1884 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1886 if ( $type eq 'csv' ) {
1888 $parser_opt->{'binary'} = 1;
1889 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
1890 $parser = Text::CSV_XS->new($parser_opt);
1892 } elsif ( $type eq 'fixedlength' ) {
1894 eval "use Parse::FixedLength;";
1896 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
1899 die "Unknown file type $type\n";
1902 @buffer = split(/\r?\n/, slurp($file) );
1903 splice(@buffer, 0, ($header || 0) );
1904 $count = scalar(@buffer);
1906 } elsif ( $type eq 'xls' ) {
1908 eval "use Spreadsheet::ParseExcel;";
1911 eval "use DateTime::Format::Excel;";
1912 #for now, just let the error be thrown if it is used, since only CDR
1913 # formats bill_west and troop use it, not other excel-parsing things
1916 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1918 $parser = $excel->{Worksheet}[0]; #first sheet
1920 $count = $parser->{MaxRow} || $parser->{MinRow};
1923 $row = $header || 0;
1925 } elsif ( $type eq 'xml' ) {
1928 eval "use XML::Simple;";
1930 my $xmlrow = $xml_format->{'xmlrow'};
1931 $parser = $xml_format->{'xmlkeys'};
1932 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1933 my $data = XML::Simple::XMLin(
1935 'SuppressEmpty' => '', #sets empty values to ''
1939 $rows = $rows->{$_} foreach @$xmlrow;
1940 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1941 $count = @buffer = @$rows;
1943 } elsif ( $type eq 'asn.1' ) {
1945 eval "use Convert::ASN1";
1948 my $asn = Convert::ASN1->new;
1949 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1951 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1953 my $data = slurp($file);
1954 my $asn_output = $parser->decode( $data )
1955 or return "No ". $asn_format->{'macro'}. " found\n";
1957 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1959 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1960 $count = @buffer = @$rows;
1963 die "Unknown file type $type\n";
1968 local $SIG{HUP} = 'IGNORE';
1969 local $SIG{INT} = 'IGNORE';
1970 local $SIG{QUIT} = 'IGNORE';
1971 local $SIG{TERM} = 'IGNORE';
1972 local $SIG{TSTP} = 'IGNORE';
1973 local $SIG{PIPE} = 'IGNORE';
1975 my $oldAutoCommit = $FS::UID::AutoCommit;
1976 local $FS::UID::AutoCommit = 0;
1979 #my $params = $param->{params} || {};
1980 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1981 my $batch_col = $param->{'batch_keycol'};
1983 my $batch_class = 'FS::'. $param->{'batch_table'};
1984 my $batch = $batch_class->new({
1985 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1987 my $error = $batch->insert;
1989 $dbh->rollback if $oldAutoCommit;
1990 return "can't insert batch record: $error";
1992 #primary key via dbdef? (so the column names don't have to match)
1993 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1995 $params->{ $batch_col } = $batch_value;
1998 #my $job = $param->{job};
2001 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
2005 my %hash = %$params;
2006 if ( $type eq 'csv' ) {
2008 last unless scalar(@buffer);
2009 $line = shift(@buffer);
2011 next if $line =~ /^\s*$/; #skip empty lines
2013 $line = &{$row_callback}($line) if $row_callback;
2015 next if $line =~ /^\s*$/; #skip empty lines
2017 $parser->parse($line) or do {
2018 $dbh->rollback if $oldAutoCommit;
2019 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
2021 @columns = $parser->fields();
2023 } elsif ( $type eq 'fixedlength' ) {
2025 last unless scalar(@buffer);
2026 $line = shift(@buffer);
2028 @columns = $parser->parse($line);
2030 } elsif ( $type eq 'xls' ) {
2032 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
2033 || ! $parser->{Cells}[$row];
2035 my @row = @{ $parser->{Cells}[$row] };
2036 @columns = map $_->{Val}, @row;
2039 #warn $z++. ": $_\n" for @columns;
2041 } elsif ( $type eq 'xml' ) {
2043 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2044 last unless scalar(@buffer);
2045 my $row = shift @buffer;
2046 @columns = @{ $row }{ @$parser };
2048 } elsif ( $type eq 'asn.1' ) {
2050 last unless scalar(@buffer);
2051 my $row = shift @buffer;
2052 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2053 if $asn_format->{row_callback};
2054 foreach my $key ( keys %{ $asn_format->{map} } ) {
2055 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2059 die "Unknown file type $type\n";
2064 foreach my $field ( @fields ) {
2066 my $value = shift @columns;
2068 if ( ref($field) eq 'CODE' ) {
2069 #&{$field}(\%hash, $value);
2070 push @later, $field, $value;
2072 #??? $hash{$field} = $value if length($value);
2073 $hash{$field} = $value if defined($value) && length($value);
2078 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2079 && length($1) == $custnum_length ) {
2080 $hash{custnum} = $2;
2083 %hash = &{$hash_callback}(%hash) if $hash_callback;
2085 #my $table = $param->{table};
2086 my $class = "FS::$table";
2088 my $record = $class->new( \%hash );
2091 while ( scalar(@later) ) {
2092 my $sub = shift @later;
2093 my $data = shift @later;
2095 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2098 $dbh->rollback if $oldAutoCommit;
2099 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2101 last if exists( $param->{skiprow} );
2103 next if exists( $param->{skiprow} );
2105 if ( $preinsert_callback ) {
2106 my $error = &{$preinsert_callback}($record, $param);
2108 $dbh->rollback if $oldAutoCommit;
2109 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2112 next if exists $param->{skiprow} && $param->{skiprow};
2115 my @insert_args = ();
2116 if ( $insert_args_callback ) {
2117 @insert_args = &{$insert_args_callback}($record, $param);
2120 my $error = $record->insert(@insert_args);
2123 $dbh->rollback if $oldAutoCommit;
2124 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2130 if ( $postinsert_callback ) {
2131 my $error = &{$postinsert_callback}($record, $param);
2133 $dbh->rollback if $oldAutoCommit;
2134 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2139 if ( $job && time - $min_sec > $last ) { #progress bar
2140 $job->update_statustext( int(100 * $imported / $count) );
2146 unless ( $imported || $param->{empty_ok} ) {
2147 $dbh->rollback if $oldAutoCommit;
2148 return "Empty file!";
2151 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2158 my( $self, $action, $time ) = @_;
2162 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2165 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2166 real_fields($self->table);
2169 # If we're encrypting then don't store the payinfo in the history
2170 if ( $conf_encryption && $self->table ne 'banned_pay' ) {
2171 @fields = grep { $_ ne 'payinfo' } @fields;
2174 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2176 "INSERT INTO h_". $self->table. " ( ".
2177 join(', ', qw(history_date history_user history_action), @fields ).
2179 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
2186 B<Warning>: External use is B<deprecated>.
2188 Replaces COLUMN in record with a unique number, using counters in the
2189 filesystem. Used by the B<insert> method on single-field unique columns
2190 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2191 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2193 Returns the new value.
2198 my($self,$field) = @_;
2199 my($table)=$self->table;
2201 croak "Unique called on field $field, but it is ",
2202 $self->getfield($field),
2204 if $self->getfield($field);
2206 #warn "table $table is tainted" if is_tainted($table);
2207 #warn "field $field is tainted" if is_tainted($field);
2209 my($counter) = new File::CounterFile "$table.$field",0;
2211 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2213 # my($counter) = new File::CounterFile "$user/$table.$field",0;
2216 my $index = $counter->inc;
2217 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2219 $index =~ /^(\d*)$/;
2222 $self->setfield($field,$index);
2226 =item ut_float COLUMN
2228 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2229 null. If there is an error, returns the error, otherwise returns false.
2234 my($self,$field)=@_ ;
2235 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2236 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2237 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2238 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2239 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2240 $self->setfield($field,$1);
2243 =item ut_floatn COLUMN
2245 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2246 null. If there is an error, returns the error, otherwise returns false.
2250 #false laziness w/ut_ipn
2252 my( $self, $field ) = @_;
2253 if ( $self->getfield($field) =~ /^()$/ ) {
2254 $self->setfield($field,'');
2257 $self->ut_float($field);
2261 =item ut_sfloat COLUMN
2263 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2264 May not be null. If there is an error, returns the error, otherwise returns
2270 my($self,$field)=@_ ;
2271 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2272 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2273 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2274 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2275 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2276 $self->setfield($field,$1);
2279 =item ut_sfloatn COLUMN
2281 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2282 null. If there is an error, returns the error, otherwise returns false.
2287 my( $self, $field ) = @_;
2288 if ( $self->getfield($field) =~ /^()$/ ) {
2289 $self->setfield($field,'');
2292 $self->ut_sfloat($field);
2296 =item ut_snumber COLUMN
2298 Check/untaint signed numeric data (whole numbers). If there is an error,
2299 returns the error, otherwise returns false.
2304 my($self, $field) = @_;
2305 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2306 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2307 $self->setfield($field, "$1$2");
2311 =item ut_snumbern COLUMN
2313 Check/untaint signed numeric data (whole numbers). If there is an error,
2314 returns the error, otherwise returns false.
2319 my($self, $field) = @_;
2320 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2321 or return "Illegal (numeric) $field: ". $self->getfield($field);
2323 return "Illegal (numeric) $field: ". $self->getfield($field)
2326 $self->setfield($field, "$1$2");
2330 =item ut_number COLUMN
2332 Check/untaint simple numeric data (whole numbers). May not be null. If there
2333 is an error, returns the error, otherwise returns false.
2338 my($self,$field)=@_;
2339 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2340 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2341 $self->setfield($field,$1);
2345 =item ut_numbern COLUMN
2347 Check/untaint simple numeric data (whole numbers). May be null. If there is
2348 an error, returns the error, otherwise returns false.
2353 my($self,$field)=@_;
2354 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2355 or return "Illegal (numeric) $field: ". $self->getfield($field);
2356 $self->setfield($field,$1);
2360 =item ut_decimal COLUMN[, DIGITS]
2362 Check/untaint decimal numbers (up to DIGITS decimal places. If there is an
2363 error, returns the error, otherwise returns false.
2365 =item ut_decimaln COLUMN[, DIGITS]
2367 Check/untaint decimal numbers. May be null. If there is an error, returns
2368 the error, otherwise returns false.
2373 my($self, $field, $digits) = @_;
2375 $self->getfield($field) =~ /^\s*(\d+(\.\d{0,$digits})?)\s*$/
2376 or return "Illegal or empty (decimal) $field: ".$self->getfield($field);
2377 $self->setfield($field, $1);
2382 my($self, $field, $digits) = @_;
2383 $self->getfield($field) =~ /^\s*(\d*(\.\d{0,$digits})?)\s*$/
2384 or return "Illegal (decimal) $field: ".$self->getfield($field);
2385 $self->setfield($field, $1);
2389 =item ut_money COLUMN
2391 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2392 is an error, returns the error, otherwise returns false.
2397 my($self,$field)=@_;
2399 if ( $self->getfield($field) eq '' ) {
2400 $self->setfield($field, 0);
2401 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2402 #handle one decimal place without barfing out
2403 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2404 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2405 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2407 return "Illegal (money) $field: ". $self->getfield($field);
2413 =item ut_moneyn COLUMN
2415 Check/untaint monetary numbers. May be negative. If there
2416 is an error, returns the error, otherwise returns false.
2421 my($self,$field)=@_;
2422 if ($self->getfield($field) eq '') {
2423 $self->setfield($field, '');
2426 $self->ut_money($field);
2429 =item ut_text COLUMN
2431 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2432 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2433 May not be null. If there is an error, returns the error, otherwise returns
2439 my($self,$field)=@_;
2440 #warn "msgcat ". \&msgcat. "\n";
2441 #warn "notexist ". \¬exist. "\n";
2442 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2443 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2444 # see perldoc perluniprops
2445 $self->getfield($field)
2446 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2447 or return gettext('illegal_or_empty_text'). " $field: ".
2448 $self->getfield($field);
2449 $self->setfield($field,$1);
2453 =item ut_textn COLUMN
2455 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2456 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2457 May be null. If there is an error, returns the error, otherwise returns false.
2462 my($self,$field)=@_;
2463 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2464 $self->ut_text($field);
2467 =item ut_alpha COLUMN
2469 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2470 an error, returns the error, otherwise returns false.
2475 my($self,$field)=@_;
2476 $self->getfield($field) =~ /^(\w+)$/
2477 or return "Illegal or empty (alphanumeric) $field: ".
2478 $self->getfield($field);
2479 $self->setfield($field,$1);
2483 =item ut_alphan COLUMN
2485 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2486 error, returns the error, otherwise returns false.
2491 my($self,$field)=@_;
2492 $self->getfield($field) =~ /^(\w*)$/
2493 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2494 $self->setfield($field,$1);
2498 =item ut_alphasn COLUMN
2500 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2501 an error, returns the error, otherwise returns false.
2506 my($self,$field)=@_;
2507 $self->getfield($field) =~ /^([\w ]*)$/
2508 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2509 $self->setfield($field,$1);
2514 =item ut_alpha_lower COLUMN
2516 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2517 there is an error, returns the error, otherwise returns false.
2521 sub ut_alpha_lower {
2522 my($self,$field)=@_;
2523 $self->getfield($field) =~ /[[:upper:]]/
2524 and return "Uppercase characters are not permitted in $field";
2525 $self->ut_alpha($field);
2528 =item ut_phonen COLUMN [ COUNTRY ]
2530 Check/untaint phone numbers. May be null. If there is an error, returns
2531 the error, otherwise returns false.
2533 Takes an optional two-letter ISO 3166-1 alpha-2 country code; without
2534 it or with unsupported countries, ut_phonen simply calls ut_alphan.
2539 my( $self, $field, $country ) = @_;
2540 return $self->ut_alphan($field) unless defined $country;
2541 my $phonen = $self->getfield($field);
2542 if ( $phonen eq '' ) {
2543 $self->setfield($field,'');
2544 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2546 $phonen = $conf->config('cust_main-default_areacode').$phonen
2547 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2548 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2549 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2550 $phonen = "$1-$2-$3";
2551 $phonen .= " x$4" if $4;
2552 $self->setfield($field,$phonen);
2554 warn "warning: don't know how to check phone numbers for country $country";
2555 return $self->ut_textn($field);
2562 Check/untaint hexadecimal values.
2567 my($self, $field) = @_;
2568 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2569 or return "Illegal (hex) $field: ". $self->getfield($field);
2570 $self->setfield($field, uc($1));
2574 =item ut_hexn COLUMN
2576 Check/untaint hexadecimal values. May be null.
2581 my($self, $field) = @_;
2582 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2583 or return "Illegal (hex) $field: ". $self->getfield($field);
2584 $self->setfield($field, uc($1));
2588 =item ut_mac_addr COLUMN
2590 Check/untaint mac addresses. May be null.
2595 my($self, $field) = @_;
2597 my $mac = $self->get($field);
2600 $self->set($field, $mac);
2602 my $e = $self->ut_hex($field);
2605 return "Illegal (mac address) $field: ". $self->getfield($field)
2606 unless length($self->getfield($field)) == 12;
2612 =item ut_mac_addrn COLUMN
2614 Check/untaint mac addresses. May be null.
2619 my($self, $field) = @_;
2620 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2625 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2631 my( $self, $field ) = @_;
2632 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2633 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2634 or return "Illegal (IP address) $field: ". $self->getfield($field);
2635 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2636 $self->setfield($field, "$1.$2.$3.$4");
2642 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2643 to 127.0.0.1. May be null.
2648 my( $self, $field ) = @_;
2649 if ( $self->getfield($field) =~ /^()$/ ) {
2650 $self->setfield($field,'');
2653 $self->ut_ip($field);
2657 =item ut_ip46 COLUMN
2659 Check/untaint IPv4 or IPv6 address.
2664 my( $self, $field ) = @_;
2665 my $ip = NetAddr::IP->new($self->getfield($field))
2666 or return "Illegal (IP address) $field: ".$self->getfield($field);
2667 $self->setfield($field, lc($ip->addr));
2673 Check/untaint IPv6 or IPv6 address. May be null.
2678 my( $self, $field ) = @_;
2679 if ( $self->getfield($field) =~ /^$/ ) {
2680 $self->setfield($field, '');
2683 $self->ut_ip46($field);
2686 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2688 Check/untaint coordinates.
2689 Accepts the following forms:
2699 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2700 The latter form (that is, the MMM are thousands of minutes) is
2701 assumed if the "MMM" is exactly three digits or two digits > 59.
2703 To be safe, just use the DDD.DDDDD form.
2705 If LOWER or UPPER are specified, then the coordinate is checked
2706 for lower and upper bounds, respectively.
2711 my ($self, $field) = (shift, shift);
2714 if ( $field =~ /latitude/ ) {
2715 $lower = $lat_lower;
2717 } elsif ( $field =~ /longitude/ ) {
2719 $upper = $lon_upper;
2722 my $coord = $self->getfield($field);
2723 my $neg = $coord =~ s/^(-)//;
2725 my ($d, $m, $s) = (0, 0, 0);
2728 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2729 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2730 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2732 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2735 return "Invalid (coordinate with minutes > 59) $field: "
2736 . $self->getfield($field);
2739 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2741 if (defined($lower) and ($coord < $lower)) {
2742 return "Invalid (coordinate < $lower) $field: "
2743 . $self->getfield($field);;
2746 if (defined($upper) and ($coord > $upper)) {
2747 return "Invalid (coordinate > $upper) $field: "
2748 . $self->getfield($field);;
2751 $self->setfield($field, $coord);
2755 return "Invalid (coordinate) $field: " . $self->getfield($field);
2759 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2761 Same as ut_coord, except optionally null.
2767 my ($self, $field) = (shift, shift);
2769 if ($self->getfield($field) =~ /^\s*$/) {
2772 return $self->ut_coord($field, @_);
2777 =item ut_domain COLUMN
2779 Check/untaint host and domain names. May not be null.
2784 my( $self, $field ) = @_;
2785 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2786 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2787 or return "Illegal (hostname) $field: ". $self->getfield($field);
2788 $self->setfield($field,$1);
2792 =item ut_domainn COLUMN
2794 Check/untaint host and domain names. May be null.
2799 my( $self, $field ) = @_;
2800 if ( $self->getfield($field) =~ /^()$/ ) {
2801 $self->setfield($field,'');
2804 $self->ut_domain($field);
2808 =item ut_name COLUMN
2810 Check/untaint proper names; allows alphanumerics, spaces and the following
2811 punctuation: , . - '
2818 my( $self, $field ) = @_;
2819 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2820 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
2821 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2826 $self->setfield($field, $name);
2830 =item ut_namen COLUMN
2832 Check/untaint proper names; allows alphanumerics, spaces and the following
2833 punctuation: , . - '
2840 my( $self, $field ) = @_;
2841 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2842 $self->ut_name($field);
2847 Check/untaint zip codes.
2851 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2854 my( $self, $field, $country ) = @_;
2856 if ( $country eq 'US' ) {
2858 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2859 or return gettext('illegal_zip'). " $field for country $country: ".
2860 $self->getfield($field);
2861 $self->setfield($field, $1);
2863 } elsif ( $country eq 'CA' ) {
2865 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2866 or return gettext('illegal_zip'). " $field for country $country: ".
2867 $self->getfield($field);
2868 $self->setfield($field, "$1 $2");
2872 if ( $self->getfield($field) =~ /^\s*$/
2873 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2876 $self->setfield($field,'');
2878 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2879 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2880 $self->setfield($field,$1);
2888 =item ut_country COLUMN
2890 Check/untaint country codes. Country names are changed to codes, if possible -
2891 see L<Locale::Country>.
2896 my( $self, $field ) = @_;
2897 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2898 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2899 && country2code($1) ) {
2900 $self->setfield($field,uc(country2code($1)));
2903 $self->getfield($field) =~ /^(\w\w)$/
2904 or return "Illegal (country) $field: ". $self->getfield($field);
2905 $self->setfield($field,uc($1));
2909 =item ut_anything COLUMN
2911 Untaints arbitrary data. Be careful.
2916 my( $self, $field ) = @_;
2917 $self->getfield($field) =~ /^(.*)$/s
2918 or return "Illegal $field: ". $self->getfield($field);
2919 $self->setfield($field,$1);
2923 =item ut_enum COLUMN CHOICES_ARRAYREF
2925 Check/untaint a column, supplying all possible choices, like the "enum" type.
2930 my( $self, $field, $choices ) = @_;
2931 foreach my $choice ( @$choices ) {
2932 if ( $self->getfield($field) eq $choice ) {
2933 $self->setfield($field, $choice);
2937 return "Illegal (enum) field $field: ". $self->getfield($field);
2940 =item ut_enumn COLUMN CHOICES_ARRAYREF
2942 Like ut_enum, except the null value is also allowed.
2947 my( $self, $field, $choices ) = @_;
2948 $self->getfield($field)
2949 ? $self->ut_enum($field, $choices)
2953 =item ut_flag COLUMN
2955 Check/untaint a column if it contains either an empty string or 'Y'. This
2956 is the standard form for boolean flags in Freeside.
2961 my( $self, $field ) = @_;
2962 my $value = uc($self->getfield($field));
2963 if ( $value eq '' or $value eq 'Y' ) {
2964 $self->setfield($field, $value);
2967 return "Illegal (flag) field $field: $value";
2970 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2972 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2973 on the column first.
2977 sub ut_foreign_key {
2978 my( $self, $field, $table, $foreign ) = @_;
2979 return '' if $no_check_foreign;
2980 qsearchs($table, { $foreign => $self->getfield($field) })
2981 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2982 " in $table.$foreign";
2986 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2988 Like ut_foreign_key, except the null value is also allowed.
2992 sub ut_foreign_keyn {
2993 my( $self, $field, $table, $foreign ) = @_;
2994 $self->getfield($field)
2995 ? $self->ut_foreign_key($field, $table, $foreign)
2999 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
3001 Checks this column as an agentnum, taking into account the current users's
3002 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
3003 right or rights allowing no agentnum.
3007 sub ut_agentnum_acl {
3008 my( $self, $field ) = (shift, shift);
3009 my $null_acl = scalar(@_) ? shift : [];
3010 $null_acl = [ $null_acl ] unless ref($null_acl);
3012 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
3013 return "Illegal agentnum: $error" if $error;
3015 my $curuser = $FS::CurrentUser::CurrentUser;
3017 if ( $self->$field() ) {
3019 return "Access denied"
3020 unless $curuser->agentnum($self->$field());
3024 return "Access denied"
3025 unless grep $curuser->access_right($_), @$null_acl;
3033 =item fields [ TABLE ]
3035 This is a wrapper for real_fields. Code that called
3036 fields before should probably continue to call fields.
3041 my $something = shift;
3043 if($something->isa('FS::Record')) {
3044 $table = $something->table;
3046 $table = $something;
3047 $something = "FS::$table";
3049 return (real_fields($table));
3053 =item encrypt($value)
3055 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
3057 Returns the encrypted string.
3059 You should generally not have to worry about calling this, as the system handles this for you.
3064 my ($self, $value) = @_;
3065 my $encrypted = $value;
3067 if ($conf_encryption) {
3068 if ($self->is_encrypted($value)) {
3069 # Return the original value if it isn't plaintext.
3070 $encrypted = $value;
3073 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3074 # RSA doesn't like the empty string so let's pack it up
3075 # The database doesn't like the RSA data so uuencode it
3076 my $length = length($value)+1;
3077 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3079 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3086 =item is_encrypted($value)
3088 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3094 my ($self, $value) = @_;
3095 # Possible Bug - Some work may be required here....
3097 if ($value =~ /^M/ && length($value) > 80) {
3104 =item decrypt($value)
3106 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3108 You should generally not have to worry about calling this, as the system handles this for you.
3113 my ($self,$value) = @_;
3114 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3115 if ($conf_encryption && $self->is_encrypted($value)) {
3117 if (ref($rsa_decrypt) =~ /::RSA/) {
3118 my $encrypted = unpack ("u*", $value);
3119 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3120 if ($@) {warn "Decryption Failed"};
3128 #Initialize the Module
3129 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3131 if ($conf_encryptionmodule && $conf_encryptionmodule ne '') {
3132 $rsa_module = $conf_encryptionmodule;
3136 eval ("require $rsa_module"); # No need to import the namespace
3139 # Initialize Encryption
3140 if ($conf_encryptionpublickey && $conf_encryptionpublickey ne '') {
3141 $rsa_encrypt = $rsa_module->new_public_key($conf_encryptionpublickey);
3144 # Intitalize Decryption
3145 if ($conf_encryptionprivatekey && $conf_encryptionprivatekey ne '') {
3146 $rsa_decrypt = $rsa_module->new_private_key($conf_encryptionprivatekey);
3150 =item h_search ACTION
3152 Given an ACTION, either "insert", or "delete", returns the appropriate history
3153 record corresponding to this record, if any.
3158 my( $self, $action ) = @_;
3160 my $table = $self->table;
3163 my $primary_key = dbdef->table($table)->primary_key;
3166 'table' => "h_$table",
3167 'hashref' => { $primary_key => $self->$primary_key(),
3168 'history_action' => $action,
3176 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3177 appropriate history record corresponding to this record, if any.
3182 my($self, $action) = @_;
3183 my $h = $self->h_search($action);
3184 $h ? $h->history_date : '';
3187 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3189 A class or object method. Executes the sql statement represented by SQL and
3190 returns a scalar representing the result: the first column of the first row.
3192 Dies on bogus SQL. Returns an empty string if no row is returned.
3194 Typically used for statments which return a single value such as "SELECT
3195 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3200 my($self, $sql) = (shift, shift);
3201 my $sth = dbh->prepare($sql) or die dbh->errstr;
3203 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3204 my $row = $sth->fetchrow_arrayref or return '';
3205 my $scalar = $row->[0];
3206 defined($scalar) ? $scalar : '';
3209 =item count [ WHERE [, PLACEHOLDER ...] ]
3211 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3212 with optional WHERE. Must be called as method on a class with an
3218 my($self, $where) = (shift, shift);
3219 my $table = $self->table or die 'count called on object of class '.ref($self);
3220 my $sql = "SELECT COUNT(*) FROM $table";
3221 $sql .= " WHERE $where" if $where;
3222 $self->scalar_sql($sql, @_);
3225 =item row_exists [ WHERE [, PLACEHOLDER ...] ]
3227 Convenience method for the common case of "SELECT 1 FROM table ... LIMIT 1"
3228 with optional (but almost always needed) WHERE.
3233 my($self, $where) = (shift, shift);
3234 my $table = $self->table or die 'row_exists called on object of class '.ref($self);
3235 my $sql = "SELECT 1 FROM $table";
3236 $sql .= " WHERE $where" if $where;
3238 $self->scalar_sql($sql, @_);
3247 =item real_fields [ TABLE ]
3249 Returns a list of the real columns in the specified table. Called only by
3250 fields() and other subroutines elsewhere in FS::Record.
3257 my($table_obj) = dbdef->table($table);
3258 confess "Unknown table $table" unless $table_obj;
3259 $table_obj->columns;
3262 =item pvf FIELD_NAME
3264 Returns the FS::part_virtual_field object corresponding to a field in the
3265 record (specified by FIELD_NAME).
3270 my ($self, $name) = (shift, shift);
3272 if(grep /^$name$/, $self->virtual_fields) {
3274 my $concat = [ "'cf_'", "name" ];
3275 return qsearchs({ table => 'part_virtual_field',
3276 hashref => { dbtable => $self->table,
3279 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3285 =item _quote VALUE, TABLE, COLUMN
3287 This is an internal function used to construct SQL statements. It returns
3288 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3289 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3294 my($value, $table, $column) = @_;
3295 my $column_obj = dbdef->table($table)->column($column);
3296 my $column_type = $column_obj->type;
3297 my $nullable = $column_obj->null;
3299 utf8::upgrade($value);
3301 warn " $table.$column: $value ($column_type".
3302 ( $nullable ? ' NULL' : ' NOT NULL' ).
3303 ")\n" if $DEBUG > 2;
3305 if ( $value eq '' && $nullable ) {
3307 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3308 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3311 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3312 ! $column_type =~ /(char|binary|text)$/i ) {
3314 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3315 && driver_name eq 'Pg'
3319 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3320 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3321 # single-quote the whole mess, and put an "E" in front.
3322 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3330 This is deprecated. Don't use it.
3332 It returns a hash-type list with the fields of this record's table set true.
3337 carp "warning: hfields is deprecated";
3340 foreach (fields($table)) {
3349 "$_: ". $self->getfield($_). "|"
3350 } (fields($self->table)) );
3353 sub DESTROY { return; }
3357 # #use Carp qw(cluck);
3358 # #cluck "DESTROYING $self";
3359 # warn "DESTROYING $self";
3363 # return ! eval { join('',@_), kill 0; 1; };
3366 =item str2time_sql [ DRIVER_NAME ]
3368 Returns a function to convert to unix time based on database type, such as
3369 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3370 the str2time_sql_closing method to return a closing string rather than just
3371 using a closing parenthesis as previously suggested.
3373 You can pass an optional driver name such as "Pg", "mysql" or
3374 $dbh->{Driver}->{Name} to return a function for that database instead of
3375 the current database.
3380 my $driver = shift || driver_name;
3382 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3383 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3385 warn "warning: unknown database type $driver; guessing how to convert ".
3386 "dates to UNIX timestamps";
3387 return 'EXTRACT(EPOCH FROM ';
3391 =item str2time_sql_closing [ DRIVER_NAME ]
3393 Returns the closing suffix of a function to convert to unix time based on
3394 database type, such as ")::integer" for Pg or ")" for mysql.
3396 You can pass an optional driver name such as "Pg", "mysql" or
3397 $dbh->{Driver}->{Name} to return a function for that database instead of
3398 the current database.
3402 sub str2time_sql_closing {
3403 my $driver = shift || driver_name;
3405 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3409 =item regexp_sql [ DRIVER_NAME ]
3411 Returns the operator to do a regular expression comparison based on database
3412 type, such as '~' for Pg or 'REGEXP' for mysql.
3414 You can pass an optional driver name such as "Pg", "mysql" or
3415 $dbh->{Driver}->{Name} to return a function for that database instead of
3416 the current database.
3421 my $driver = shift || driver_name;
3423 return '~' if $driver =~ /^Pg/i;
3424 return 'REGEXP' if $driver =~ /^mysql/i;
3426 die "don't know how to use regular expressions in ". driver_name." databases";
3430 =item not_regexp_sql [ DRIVER_NAME ]
3432 Returns the operator to do a regular expression negation based on database
3433 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3435 You can pass an optional driver name such as "Pg", "mysql" or
3436 $dbh->{Driver}->{Name} to return a function for that database instead of
3437 the current database.
3441 sub not_regexp_sql {
3442 my $driver = shift || driver_name;
3444 return '!~' if $driver =~ /^Pg/i;
3445 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3447 die "don't know how to use regular expressions in ". driver_name." databases";
3451 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3453 Returns the items concatenated based on database type, using "CONCAT()" for
3454 mysql and " || " for Pg and other databases.
3456 You can pass an optional driver name such as "Pg", "mysql" or
3457 $dbh->{Driver}->{Name} to return a function for that database instead of
3458 the current database.
3463 my $driver = ref($_[0]) ? driver_name : shift;
3466 if ( $driver =~ /^mysql/i ) {
3467 'CONCAT('. join(',', @$items). ')';
3469 join('||', @$items);
3474 =item group_concat_sql COLUMN, DELIMITER
3476 Returns an SQL expression to concatenate an aggregate column, using
3477 GROUP_CONCAT() for mysql and array_to_string() and array_agg() for Pg.
3481 sub group_concat_sql {
3482 my ($col, $delim) = @_;
3483 $delim = dbh->quote($delim);
3484 if ( driver_name() =~ /^mysql/i ) {
3485 # DISTINCT(foo) is valid as $col
3486 return "GROUP_CONCAT($col SEPARATOR $delim)";
3488 return "array_to_string(array_agg($col), $delim)";
3492 =item midnight_sql DATE
3494 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3495 on that day in the system timezone, using the default driver name.
3500 my $driver = driver_name;
3502 if ( $driver =~ /^mysql/i ) {
3503 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3506 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3514 This module should probably be renamed, since much of the functionality is
3515 of general use. It is not completely unlike Adapter::DBI (see below).
3517 Exported qsearch and qsearchs should be deprecated in favor of method calls
3518 (against an FS::Record object like the old search and searchs that qsearch
3519 and qsearchs were on top of.)
3521 The whole fields / hfields mess should be removed.
3523 The various WHERE clauses should be subroutined.
3525 table string should be deprecated in favor of DBIx::DBSchema::Table.
3527 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3528 true maps to the database (and WHERE clauses) would also help.
3530 The ut_ methods should ask the dbdef for a default length.
3532 ut_sqltype (like ut_varchar) should all be defined
3534 A fallback check method should be provided which uses the dbdef.
3536 The ut_money method assumes money has two decimal digits.
3538 The Pg money kludge in the new method only strips `$'.
3540 The ut_phonen method only checks US-style phone numbers.
3542 The _quote function should probably use ut_float instead of a regex.
3544 All the subroutines probably should be methods, here or elsewhere.
3546 Probably should borrow/use some dbdef methods where appropriate (like sub
3549 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3550 or allow it to be set. Working around it is ugly any way around - DBI should
3551 be fixed. (only affects RDBMS which return uppercase column names)
3553 ut_zip should take an optional country like ut_phone.
3557 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3559 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.