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
42 concat_sql group_concat_sql
49 $nowarn_identical = 0;
50 $nowarn_classload = 0;
53 $no_check_foreign = 0;
61 $conf_encryption = '';
62 FS::UID->install_callback( sub {
66 $conf = FS::Conf->new;
67 $conf_encryption = $conf->exists('encryption');
68 $money_char = $conf->config('money_char') || '$';
69 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
70 $lat_lower = $nw_coords ? 1 : -90;
71 $lon_upper = $nw_coords ? -1 : 180;
73 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
75 if ( driver_name eq 'Pg' ) {
76 eval "use DBD::Pg ':pg_types'";
79 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
86 FS::Record - Database record objects
91 use FS::Record qw(dbh fields qsearch qsearchs);
93 $record = new FS::Record 'table', \%hash;
94 $record = new FS::Record 'table', { 'column' => 'value', ... };
96 $record = qsearchs FS::Record 'table', \%hash;
97 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
98 @records = qsearch FS::Record 'table', \%hash;
99 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
101 $table = $record->table;
102 $dbdef_table = $record->dbdef_table;
104 $value = $record->get('column');
105 $value = $record->getfield('column');
106 $value = $record->column;
108 $record->set( 'column' => 'value' );
109 $record->setfield( 'column' => 'value' );
110 $record->column('value');
112 %hash = $record->hash;
114 $hashref = $record->hashref;
116 $error = $record->insert;
118 $error = $record->delete;
120 $error = $new_record->replace($old_record);
122 # external use deprecated - handled by the database (at least for Pg, mysql)
123 $value = $record->unique('column');
125 $error = $record->ut_float('column');
126 $error = $record->ut_floatn('column');
127 $error = $record->ut_number('column');
128 $error = $record->ut_numbern('column');
129 $error = $record->ut_decimal('column');
130 $error = $record->ut_decimaln('column');
131 $error = $record->ut_snumber('column');
132 $error = $record->ut_snumbern('column');
133 $error = $record->ut_money('column');
134 $error = $record->ut_text('column');
135 $error = $record->ut_textn('column');
136 $error = $record->ut_alpha('column');
137 $error = $record->ut_alphan('column');
138 $error = $record->ut_phonen('column');
139 $error = $record->ut_anything('column');
140 $error = $record->ut_name('column');
142 $quoted_value = _quote($value,'table','field');
145 $fields = hfields('table');
146 if ( $fields->{Field} ) { # etc.
148 @fields = fields 'table'; #as a subroutine
149 @fields = $record->fields; #as a method call
154 (Mostly) object-oriented interface to database records. Records are currently
155 implemented on top of DBI. FS::Record is intended as a base class for
156 table-specific classes to inherit from, i.e. FS::cust_main.
162 =item new [ TABLE, ] HASHREF
164 Creates a new record. It doesn't store it in the database, though. See
165 L<"insert"> for that.
167 Note that the object stores this hash reference, not a distinct copy of the
168 hash it points to. You can ask the object for a copy with the I<hash>
171 TABLE can only be omitted when a dervived class overrides the table method.
177 my $class = ref($proto) || $proto;
179 bless ($self, $class);
181 unless ( defined ( $self->table ) ) {
182 $self->{'Table'} = shift;
183 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
184 unless $nowarn_classload;
187 $self->{'Hash'} = shift;
189 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
190 $self->{'Hash'}{$field}='';
193 $self->_rebless if $self->can('_rebless');
195 $self->{'modified'} = 0;
197 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
204 my $class = ref($proto) || $proto;
206 bless ($self, $class);
208 $self->{'Table'} = shift unless defined ( $self->table );
210 my $hashref = $self->{'Hash'} = shift;
212 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
213 my $obj = $cache->cache->{$hashref->{$cache->key}};
214 $obj->_cache($hashref, $cache) if $obj->can('_cache');
217 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
224 my $class = ref($proto) || $proto;
226 bless ($self, $class);
227 if ( defined $self->table ) {
228 cluck "create constructor is deprecated, use new!";
231 croak "FS::Record::create called (not from a subclass)!";
235 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
237 Searches the database for all records matching (at least) the key/value pairs
238 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
239 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
242 The preferred usage is to pass a hash reference of named parameters:
244 @records = qsearch( {
245 'table' => 'table_name',
246 'hashref' => { 'field' => 'value'
247 'field' => { 'op' => '<',
252 #these are optional...
254 'extra_sql' => 'AND field = ? AND intfield = ?',
255 'extra_param' => [ 'value', [ 5, 'int' ] ],
256 'order_by' => 'ORDER BY something',
257 #'cache_obj' => '', #optional
258 'addl_from' => 'LEFT JOIN othtable USING ( field )',
263 Much code still uses old-style positional parameters, this is also probably
264 fine in the common case where there are only two parameters:
266 my @records = qsearch( 'table', { 'field' => 'value' } );
268 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
269 the individual PARAMS_HASHREF queries
271 ###oops, argh, FS::Record::new only lets us create database fields.
272 #Normal behaviour if SELECT is not specified is `*', as in
273 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
274 #feature where you can specify SELECT - remember, the objects returned,
275 #although blessed into the appropriate `FS::TABLE' package, will only have the
276 #fields you specify. This might have unwanted results if you then go calling
277 #regular FS::TABLE methods
282 my %TYPE = (); #for debugging
285 my($type, $value) = @_;
287 my $bind_type = { TYPE => SQL_VARCHAR };
289 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
291 $bind_type = { TYPE => SQL_INTEGER };
293 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
295 if ( driver_name eq 'Pg' ) {
297 $bind_type = { pg_type => PG_BYTEA };
299 # $bind_type = ? #SQL_VARCHAR could be fine?
302 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
303 #fixed by DBD::Pg 2.11.8
304 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
305 #(make a Tron test first)
306 } elsif ( _is_fs_float( $type, $value ) ) {
308 $bind_type = { TYPE => SQL_DECIMAL };
317 my($type, $value) = @_;
318 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
319 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
327 my( @stable, @record, @cache );
328 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
330 my %union_options = ();
331 if ( ref($_[0]) eq 'ARRAY' ) {
334 foreach my $href ( @$optlist ) {
335 push @stable, ( $href->{'table'} or die "table name is required" );
336 push @record, ( $href->{'hashref'} || {} );
337 push @select, ( $href->{'select'} || '*' );
338 push @extra_sql, ( $href->{'extra_sql'} || '' );
339 push @extra_param, ( $href->{'extra_param'} || [] );
340 push @order_by, ( $href->{'order_by'} || '' );
341 push @cache, ( $href->{'cache_obj'} || '' );
342 push @addl_from, ( $href->{'addl_from'} || '' );
343 push @debug, ( $href->{'debug'} || '' );
345 die "at least one hashref is required" unless scalar(@stable);
346 } elsif ( ref($_[0]) eq 'HASH' ) {
348 $stable[0] = $opt->{'table'} or die "table name is required";
349 $record[0] = $opt->{'hashref'} || {};
350 $select[0] = $opt->{'select'} || '*';
351 $extra_sql[0] = $opt->{'extra_sql'} || '';
352 $extra_param[0] = $opt->{'extra_param'} || [];
353 $order_by[0] = $opt->{'order_by'} || '';
354 $cache[0] = $opt->{'cache_obj'} || '';
355 $addl_from[0] = $opt->{'addl_from'} || '';
356 $debug[0] = $opt->{'debug'} || '';
367 my $cache = $cache[0];
373 foreach my $stable ( @stable ) {
374 #stop altering the caller's hashref
375 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
376 my $select = shift @select;
377 my $extra_sql = shift @extra_sql;
378 my $extra_param = shift @extra_param;
379 my $order_by = shift @order_by;
380 my $cache = shift @cache;
381 my $addl_from = shift @addl_from;
382 my $debug = shift @debug;
384 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
386 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
389 my $table = $cache ? $cache->table : $stable;
390 my $dbdef_table = dbdef->table($table)
391 or die "No schema for table $table found - ".
392 "do you need to run freeside-upgrade?";
393 my $pkey = $dbdef_table->primary_key;
395 my @real_fields = grep exists($record->{$_}), real_fields($table);
397 my $statement .= "SELECT $select FROM $stable";
398 $statement .= " $addl_from" if $addl_from;
399 if ( @real_fields ) {
400 $statement .= ' WHERE '. join(' AND ',
401 get_real_fields($table, $record, \@real_fields));
404 $statement .= " $extra_sql" if defined($extra_sql);
405 $statement .= " $order_by" if defined($order_by);
407 push @statement, $statement;
409 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
413 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
416 my $value = $record->{$field};
417 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
418 $value = $value->{'value'} if ref($value);
419 my $type = dbdef->table($table)->column($field)->type;
421 my $bind_type = _bind_type($type, $value);
425 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
427 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
431 push @bind_type, $bind_type;
435 foreach my $param ( @$extra_param ) {
436 my $bind_type = { TYPE => SQL_VARCHAR };
439 $value = $param->[0];
440 my $type = $param->[1];
441 $bind_type = _bind_type($type, $value);
444 push @bind_type, $bind_type;
448 my $statement = join( ' ) UNION ( ', @statement );
449 $statement = "( $statement )" if scalar(@statement) > 1;
450 $statement .= " $union_options{order_by}" if $union_options{order_by};
452 my $sth = $dbh->prepare($statement)
453 or croak "$dbh->errstr doing $statement";
456 foreach my $value ( @value ) {
457 my $bind_type = shift @bind_type;
458 $sth->bind_param($bind++, $value, $bind_type );
461 # $sth->execute( map $record->{$_},
462 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
463 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
465 my $ok = $sth->execute;
467 my $error = "Error executing \"$statement\"";
468 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
469 $error .= ': '. $sth->errstr;
473 my $table = $stable[0];
475 $table = '' if grep { $_ ne $table } @stable;
476 $pkey = dbdef->table($table)->primary_key if $table;
479 tie %result, "Tie::IxHash";
480 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
481 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
482 %result = map { $_->{$pkey}, $_ } @stuff;
484 @result{@stuff} = @stuff;
490 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
491 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
492 #derivied class didn't override new method, so this optimization is safe
495 new_or_cached( "FS::$table", { %{$_} }, $cache )
499 new( "FS::$table", { %{$_} } )
503 #okay, its been tested
504 # warn "untested code (class FS::$table uses custom new method)";
506 eval 'FS::'. $table. '->new( { %{$_} } )';
510 # Check for encrypted fields and decrypt them.
511 ## only in the local copy, not the cached object
512 if ( $conf_encryption
513 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
514 foreach my $record (@return) {
515 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
516 next if $field eq 'payinfo'
517 && ($record->isa('FS::payinfo_transaction_Mixin')
518 || $record->isa('FS::payinfo_Mixin') )
520 && !grep { $record->payby eq $_ } @encrypt_payby;
521 # Set it directly... This may cause a problem in the future...
522 $record->setfield($field, $record->decrypt($record->getfield($field)));
527 cluck "warning: FS::$table not loaded; returning FS::Record objects"
528 unless $nowarn_classload;
530 FS::Record->new( $table, { %{$_} } );
538 Construct the SQL statement and parameter-binding list for qsearch. Takes
539 the qsearch parameters.
541 Returns a hash containing:
542 'table': The primary table name (if there is one).
543 'statement': The SQL statement itself.
544 'bind_type': An arrayref of bind types.
545 'value': An arrayref of parameter values.
546 'cache': The cache object, if one was passed.
551 my( @stable, @record, @cache );
552 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
555 my %union_options = ();
556 if ( ref($_[0]) eq 'ARRAY' ) {
559 foreach my $href ( @$optlist ) {
560 push @stable, ( $href->{'table'} or die "table name is required" );
561 push @record, ( $href->{'hashref'} || {} );
562 push @select, ( $href->{'select'} || '*' );
563 push @extra_sql, ( $href->{'extra_sql'} || '' );
564 push @extra_param, ( $href->{'extra_param'} || [] );
565 push @order_by, ( $href->{'order_by'} || '' );
566 push @cache, ( $href->{'cache_obj'} || '' );
567 push @addl_from, ( $href->{'addl_from'} || '' );
568 push @debug, ( $href->{'debug'} || '' );
570 die "at least one hashref is required" unless scalar(@stable);
571 } elsif ( ref($_[0]) eq 'HASH' ) {
573 $stable[0] = $opt->{'table'} or die "table name is required";
574 $record[0] = $opt->{'hashref'} || {};
575 $select[0] = $opt->{'select'} || '*';
576 $extra_sql[0] = $opt->{'extra_sql'} || '';
577 $extra_param[0] = $opt->{'extra_param'} || [];
578 $order_by[0] = $opt->{'order_by'} || '';
579 $cache[0] = $opt->{'cache_obj'} || '';
580 $addl_from[0] = $opt->{'addl_from'} || '';
581 $debug[0] = $opt->{'debug'} || '';
592 my $cache = $cache[0];
598 my $result_table = $stable[0];
599 foreach my $stable ( @stable ) {
600 #stop altering the caller's hashref
601 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
602 my $select = shift @select;
603 my $extra_sql = shift @extra_sql;
604 my $extra_param = shift @extra_param;
605 my $order_by = shift @order_by;
606 my $cache = shift @cache;
607 my $addl_from = shift @addl_from;
608 my $debug = shift @debug;
610 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
612 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
615 $result_table = '' if $result_table ne $stable;
617 my $table = $cache ? $cache->table : $stable;
618 my $dbdef_table = dbdef->table($table)
619 or die "No schema for table $table found - ".
620 "do you need to run freeside-upgrade?";
621 my $pkey = $dbdef_table->primary_key;
623 my @real_fields = grep exists($record->{$_}), real_fields($table);
625 my $statement .= "SELECT $select FROM $stable";
626 $statement .= " $addl_from" if $addl_from;
627 if ( @real_fields ) {
628 $statement .= ' WHERE '. join(' AND ',
629 get_real_fields($table, $record, \@real_fields));
632 $statement .= " $extra_sql" if defined($extra_sql);
633 $statement .= " $order_by" if defined($order_by);
635 push @statement, $statement;
637 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
641 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
644 my $value = $record->{$field};
645 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
646 $value = $value->{'value'} if ref($value);
647 my $type = dbdef->table($table)->column($field)->type;
649 my $bind_type = _bind_type($type, $value);
653 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
655 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
659 push @bind_type, $bind_type;
663 foreach my $param ( @$extra_param ) {
664 my $bind_type = { TYPE => SQL_VARCHAR };
667 $value = $param->[0];
668 my $type = $param->[1];
669 $bind_type = _bind_type($type, $value);
672 push @bind_type, $bind_type;
676 my $statement = join( ' ) UNION ( ', @statement );
677 $statement = "( $statement )" if scalar(@statement) > 1;
678 $statement .= " $union_options{order_by}" if $union_options{order_by};
681 statement => $statement,
682 bind_type => \@bind_type,
684 table => $result_table,
689 # qsearch should eventually use this
691 my ($table, $cache, @hashrefs) = @_;
693 # XXX get rid of these string evals at some point
694 # (when we have time to test it)
695 # my $class = "FS::$table" if $table;
696 # if ( $class and $class->isa('FS::Record') )
697 # if ( $class->can('new') eq \&new )
699 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
700 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
701 #derivied class didn't override new method, so this optimization is safe
704 new_or_cached( "FS::$table", { %{$_} }, $cache )
708 new( "FS::$table", { %{$_} } )
712 #okay, its been tested
713 # warn "untested code (class FS::$table uses custom new method)";
715 eval 'FS::'. $table. '->new( { %{$_} } )';
719 # Check for encrypted fields and decrypt them.
720 ## only in the local copy, not the cached object
721 if ( $conf_encryption
722 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
723 foreach my $record (@return) {
724 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
725 next if $field eq 'payinfo'
726 && ($record->isa('FS::payinfo_transaction_Mixin')
727 || $record->isa('FS::payinfo_Mixin') )
729 && !grep { $record->payby eq $_ } @encrypt_payby;
730 # Set it directly... This may cause a problem in the future...
731 $record->setfield($field, $record->decrypt($record->getfield($field)));
736 cluck "warning: FS::$table not loaded; returning FS::Record objects"
737 unless $nowarn_classload;
739 FS::Record->new( $table, { %{$_} } );
745 ## makes this easier to read
747 sub get_real_fields {
750 my $real_fields = shift;
752 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
758 my $type = dbdef->table($table)->column($column)->type;
759 my $value = $record->{$column};
760 $value = $value->{'value'} if ref($value);
761 if ( ref($record->{$_}) ) {
762 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
763 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
764 if ( uc($op) eq 'ILIKE' ) {
766 $record->{$_}{'value'} = lc($record->{$_}{'value'});
767 $column = "LOWER($_)";
769 $record->{$_} = $record->{$_}{'value'}
772 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
774 if ( driver_name eq 'Pg' ) {
775 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
776 qq-( $column IS NULL )-;
778 qq-( $column IS NULL OR $column = '' )-;
781 qq-( $column IS NULL OR $column = "" )-;
783 } elsif ( $op eq '!=' ) {
784 if ( driver_name eq 'Pg' ) {
785 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
786 qq-( $column IS NOT NULL )-;
788 qq-( $column IS NOT NULL AND $column != '' )-;
791 qq-( $column IS NOT NULL AND $column != "" )-;
794 if ( driver_name eq 'Pg' ) {
795 qq-( $column $op '' )-;
797 qq-( $column $op "" )-;
800 } elsif ( $op eq '!=' ) {
801 qq-( $column IS NULL OR $column != ? )-;
802 #if this needs to be re-enabled, it needs to use a custom op like
803 #"APPROX=" or something (better name?, not '=', to avoid affecting other
805 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
806 # ( "$column <= ?", "$column >= ?" );
810 } @{ $real_fields } );
813 =item by_key PRIMARY_KEY_VALUE
815 This is a class method that returns the record with the given primary key
816 value. This method is only useful in FS::Record subclasses. For example:
818 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
822 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
827 my ($class, $pkey_value) = @_;
829 my $table = $class->table
830 or croak "No table for $class found";
832 my $dbdef_table = dbdef->table($table)
833 or die "No schema for table $table found - ".
834 "do you need to create it or run dbdef-create?";
835 my $pkey = $dbdef_table->primary_key
836 or die "No primary key for table $table";
838 return qsearchs($table, { $pkey => $pkey_value });
841 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
843 Experimental JOINed search method. Using this method, you can execute a
844 single SELECT spanning multiple tables, and cache the results for subsequent
845 method calls. Interface will almost definately change in an incompatible
853 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
854 my $cache = FS::SearchCache->new( $ptable, $pkey );
857 grep { !$saw{$_->getfield($pkey)}++ }
858 qsearch($table, $record, $select, $extra_sql, $cache )
862 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
864 Same as qsearch, except that if more than one record matches, it B<carp>s but
865 returns the first. If this happens, you either made a logic error in asking
866 for a single item, or your data is corrupted.
870 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
872 my(@result) = qsearch(@_);
873 cluck "warning: Multiple records in scalar search ($table)"
874 if scalar(@result) > 1;
875 #should warn more vehemently if the search was on a primary key?
876 scalar(@result) ? ($result[0]) : ();
887 Returns the table name.
892 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
899 Returns the DBIx::DBSchema::Table object for the table.
905 my($table)=$self->table;
906 dbdef->table($table);
911 Returns the primary key for the table.
917 my $pkey = $self->dbdef_table->primary_key;
920 =item get, getfield COLUMN
922 Returns the value of the column/field/key COLUMN.
927 my($self,$field) = @_;
928 # to avoid "Use of unitialized value" errors
929 if ( defined ( $self->{Hash}->{$field} ) ) {
930 $self->{Hash}->{$field};
940 =item set, setfield COLUMN, VALUE
942 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
947 my($self,$field,$value) = @_;
948 $self->{'modified'} = 1;
949 $self->{'Hash'}->{$field} = $value;
958 Returns true if the column/field/key COLUMN exists.
963 my($self,$field) = @_;
964 exists($self->{Hash}->{$field});
967 =item AUTLOADED METHODS
969 $record->column is a synonym for $record->get('column');
971 $record->column('value') is a synonym for $record->set('column','value');
978 my($field)=$AUTOLOAD;
980 if ( defined($value) ) {
981 confess "errant AUTOLOAD $field for $self (arg $value)"
982 unless blessed($self) && $self->can('setfield');
983 $self->setfield($field,$value);
985 confess "errant AUTOLOAD $field for $self (no args)"
986 unless blessed($self) && $self->can('getfield');
987 $self->getfield($field);
993 # my $field = $AUTOLOAD;
995 # if ( defined($_[1]) ) {
996 # $_[0]->setfield($field, $_[1]);
998 # $_[0]->getfield($field);
1004 Returns a list of the column/value pairs, usually for assigning to a new hash.
1006 To make a distinct duplicate of an FS::Record object, you can do:
1008 $new = new FS::Record ( $old->table, { $old->hash } );
1014 confess $self. ' -> hash: Hash attribute is undefined'
1015 unless defined($self->{'Hash'});
1016 %{ $self->{'Hash'} };
1021 Returns a reference to the column/value hash. This may be deprecated in the
1022 future; if there's a reason you can't just use the autoloaded or get/set
1034 Returns true if any of this object's values have been modified with set (or via
1035 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1042 $self->{'modified'};
1045 =item select_for_update
1047 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1052 sub select_for_update {
1054 my $primary_key = $self->primary_key;
1057 'table' => $self->table,
1058 'hashref' => { $primary_key => $self->$primary_key() },
1059 'extra_sql' => 'FOR UPDATE',
1065 Locks this table with a database-driver specific lock method. This is used
1066 as a mutex in order to do a duplicate search.
1068 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1070 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1072 Errors are fatal; no useful return value.
1074 Note: To use this method for new tables other than svc_acct and svc_phone,
1075 edit freeside-upgrade and add those tables to the duplicate_lock list.
1081 my $table = $self->table;
1083 warn "$me locking $table table\n" if $DEBUG;
1085 if ( driver_name =~ /^Pg/i ) {
1087 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1090 } elsif ( driver_name =~ /^mysql/i ) {
1092 dbh->do("SELECT * FROM duplicate_lock
1093 WHERE lockname = '$table'
1095 ) or die dbh->errstr;
1099 die "unknown database ". driver_name. "; don't know how to lock table";
1103 warn "$me acquired $table table lock\n" if $DEBUG;
1109 Inserts this record to the database. If there is an error, returns the error,
1110 otherwise returns false.
1118 warn "$self -> insert" if $DEBUG;
1120 my $error = $self->check;
1121 return $error if $error;
1123 #single-field non-null unique keys are given a value if empty
1124 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1125 foreach ( $self->dbdef_table->unique_singles) {
1126 next if $self->getfield($_);
1127 next if $self->dbdef_table->column($_)->null eq 'NULL';
1131 #and also the primary key, if the database isn't going to
1132 my $primary_key = $self->dbdef_table->primary_key;
1134 if ( $primary_key ) {
1135 my $col = $self->dbdef_table->column($primary_key);
1138 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1139 || ( driver_name eq 'Pg'
1140 && defined($col->default)
1141 && $col->quoted_default =~ /^nextval\(/i
1143 || ( driver_name eq 'mysql'
1144 && defined($col->local)
1145 && $col->local =~ /AUTO_INCREMENT/i
1147 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1150 my $table = $self->table;
1152 # Encrypt before the database
1153 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
1154 && scalar( eval '@FS::'. $table . '::encrypted_fields')
1155 && $conf->exists('encryption')
1157 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1158 next if $field eq 'payinfo'
1159 && ($self->isa('FS::payinfo_transaction_Mixin')
1160 || $self->isa('FS::payinfo_Mixin') )
1162 && !grep { $self->payby eq $_ } @encrypt_payby;
1163 $saved->{$field} = $self->getfield($field);
1164 $self->setfield($field, $self->encrypt($self->getfield($field)));
1168 #false laziness w/delete
1170 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1173 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1176 my $statement = "INSERT INTO $table ";
1177 if ( @real_fields ) {
1180 join( ', ', @real_fields ).
1182 join( ', ', @values ).
1186 $statement .= 'DEFAULT VALUES';
1188 warn "[debug]$me $statement\n" if $DEBUG > 1;
1189 my $sth = dbh->prepare($statement) or return dbh->errstr;
1191 local $SIG{HUP} = 'IGNORE';
1192 local $SIG{INT} = 'IGNORE';
1193 local $SIG{QUIT} = 'IGNORE';
1194 local $SIG{TERM} = 'IGNORE';
1195 local $SIG{TSTP} = 'IGNORE';
1196 local $SIG{PIPE} = 'IGNORE';
1198 $sth->execute or return $sth->errstr;
1200 # get inserted id from the database, if applicable & needed
1201 if ( $db_seq && ! $self->getfield($primary_key) ) {
1202 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1206 if ( driver_name eq 'Pg' ) {
1208 #my $oid = $sth->{'pg_oid_status'};
1209 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1211 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1212 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1213 dbh->rollback if $FS::UID::AutoCommit;
1214 return "can't parse $table.$primary_key default value".
1215 " for sequence name: $default";
1219 my $i_sql = "SELECT currval('$sequence')";
1220 my $i_sth = dbh->prepare($i_sql) or do {
1221 dbh->rollback if $FS::UID::AutoCommit;
1224 $i_sth->execute() or do { #$i_sth->execute($oid)
1225 dbh->rollback if $FS::UID::AutoCommit;
1226 return $i_sth->errstr;
1228 $insertid = $i_sth->fetchrow_arrayref->[0];
1230 } elsif ( driver_name eq 'mysql' ) {
1232 $insertid = dbh->{'mysql_insertid'};
1233 # work around mysql_insertid being null some of the time, ala RT :/
1234 unless ( $insertid ) {
1235 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1236 "using SELECT LAST_INSERT_ID();";
1237 my $i_sql = "SELECT LAST_INSERT_ID()";
1238 my $i_sth = dbh->prepare($i_sql) or do {
1239 dbh->rollback if $FS::UID::AutoCommit;
1242 $i_sth->execute or do {
1243 dbh->rollback if $FS::UID::AutoCommit;
1244 return $i_sth->errstr;
1246 $insertid = $i_sth->fetchrow_arrayref->[0];
1251 dbh->rollback if $FS::UID::AutoCommit;
1252 return "don't know how to retreive inserted ids from ". driver_name.
1253 ", try using counterfiles (maybe run dbdef-create?)";
1257 $self->setfield($primary_key, $insertid);
1262 if ( defined( dbdef->table('h_'. $table) ) && ! $no_history ) {
1263 my $h_statement = $self->_h_statement('insert');
1264 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1265 $h_sth = dbh->prepare($h_statement) or do {
1266 dbh->rollback if $FS::UID::AutoCommit;
1272 $h_sth->execute or return $h_sth->errstr if $h_sth;
1274 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1276 # Now that it has been saved, reset the encrypted fields so that $new
1277 # can still be used.
1278 foreach my $field (keys %{$saved}) {
1279 $self->setfield($field, $saved->{$field});
1287 Depriciated (use insert instead).
1292 cluck "warning: FS::Record::add deprecated!";
1293 insert @_; #call method in this scope
1298 Delete this record from the database. If there is an error, returns the error,
1299 otherwise returns false.
1306 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1308 $self->getfield($_) eq ''
1309 #? "( $_ IS NULL OR $_ = \"\" )"
1310 ? ( driver_name eq 'Pg'
1312 : "( $_ IS NULL OR $_ = \"\" )"
1314 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1315 } ( $self->dbdef_table->primary_key )
1316 ? ( $self->dbdef_table->primary_key)
1317 : real_fields($self->table)
1319 warn "[debug]$me $statement\n" if $DEBUG > 1;
1320 my $sth = dbh->prepare($statement) or return dbh->errstr;
1323 if ( defined dbdef->table('h_'. $self->table) ) {
1324 my $h_statement = $self->_h_statement('delete');
1325 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1326 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1331 my $primary_key = $self->dbdef_table->primary_key;
1333 local $SIG{HUP} = 'IGNORE';
1334 local $SIG{INT} = 'IGNORE';
1335 local $SIG{QUIT} = 'IGNORE';
1336 local $SIG{TERM} = 'IGNORE';
1337 local $SIG{TSTP} = 'IGNORE';
1338 local $SIG{PIPE} = 'IGNORE';
1340 my $rc = $sth->execute or return $sth->errstr;
1341 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1342 $h_sth->execute or return $h_sth->errstr if $h_sth;
1344 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1346 #no need to needlessly destoy the data either (causes problems actually)
1347 #undef $self; #no need to keep object!
1354 Depriciated (use delete instead).
1359 cluck "warning: FS::Record::del deprecated!";
1360 &delete(@_); #call method in this scope
1363 =item replace OLD_RECORD
1365 Replace the OLD_RECORD with this one in the database. If there is an error,
1366 returns the error, otherwise returns false.
1371 my ($new, $old) = (shift, shift);
1373 $old = $new->replace_old unless defined($old);
1375 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1377 if ( $new->can('replace_check') ) {
1378 my $error = $new->replace_check($old);
1379 return $error if $error;
1382 return "Records not in same table!" unless $new->table eq $old->table;
1384 my $primary_key = $old->dbdef_table->primary_key;
1385 return "Can't change primary key $primary_key ".
1386 'from '. $old->getfield($primary_key).
1387 ' to ' . $new->getfield($primary_key)
1389 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1391 my $error = $new->check;
1392 return $error if $error;
1394 # Encrypt for replace
1396 if ( $conf->exists('encryption')
1397 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1398 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1400 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1401 next if $field eq 'payinfo'
1402 && ($new->isa('FS::payinfo_transaction_Mixin')
1403 || $new->isa('FS::payinfo_Mixin') )
1405 && !grep { $new->payby eq $_ } @encrypt_payby;
1406 $saved->{$field} = $new->getfield($field);
1407 $new->setfield($field, $new->encrypt($new->getfield($field)));
1411 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1412 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1413 ? ($_, $new->getfield($_)) : () } $old->fields;
1415 unless (keys(%diff) || $no_update_diff ) {
1416 carp "[warning]$me ". ref($new)."->replace ".
1417 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1418 ": records identical"
1419 unless $nowarn_identical;
1423 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1425 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1426 } real_fields($old->table)
1431 if ( $old->getfield($_) eq '' ) {
1433 #false laziness w/qsearch
1434 if ( driver_name eq 'Pg' ) {
1435 my $type = $old->dbdef_table->column($_)->type;
1436 if ( $type =~ /(int|(big)?serial)/i ) {
1439 qq-( $_ IS NULL OR $_ = '' )-;
1442 qq-( $_ IS NULL OR $_ = "" )-;
1446 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1449 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1452 warn "[debug]$me $statement\n" if $DEBUG > 1;
1453 my $sth = dbh->prepare($statement) or return dbh->errstr;
1456 if ( defined dbdef->table('h_'. $old->table) ) {
1457 my $h_old_statement = $old->_h_statement('replace_old');
1458 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1459 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1465 if ( defined dbdef->table('h_'. $new->table) ) {
1466 my $h_new_statement = $new->_h_statement('replace_new');
1467 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1468 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1473 local $SIG{HUP} = 'IGNORE';
1474 local $SIG{INT} = 'IGNORE';
1475 local $SIG{QUIT} = 'IGNORE';
1476 local $SIG{TERM} = 'IGNORE';
1477 local $SIG{TSTP} = 'IGNORE';
1478 local $SIG{PIPE} = 'IGNORE';
1480 my $rc = $sth->execute or return $sth->errstr;
1481 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1482 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1483 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1485 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1487 # Now that it has been saved, reset the encrypted fields so that $new
1488 # can still be used.
1489 foreach my $field (keys %{$saved}) {
1490 $new->setfield($field, $saved->{$field});
1498 my( $self ) = shift;
1499 warn "[$me] replace called with no arguments; autoloading old record\n"
1502 my $primary_key = $self->dbdef_table->primary_key;
1503 if ( $primary_key ) {
1504 $self->by_key( $self->$primary_key() ) #this is what's returned
1505 or croak "can't find ". $self->table. ".$primary_key ".
1506 $self->$primary_key();
1508 croak $self->table. " has no primary key; pass old record as argument";
1515 Depriciated (use replace instead).
1520 cluck "warning: FS::Record::rep deprecated!";
1521 replace @_; #call method in this scope
1526 Checks custom fields. Subclasses should still provide a check method to validate
1527 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1533 foreach my $field ($self->virtual_fields) {
1534 my $error = $self->ut_textn($field);
1535 return $error if $error;
1540 =item virtual_fields [ TABLE ]
1542 Returns a list of virtual fields defined for the table. This should not
1543 be exported, and should only be called as an instance or class method.
1547 sub virtual_fields {
1550 $table = $self->table or confess "virtual_fields called on non-table";
1552 confess "Unknown table $table" unless dbdef->table($table);
1554 return () unless dbdef->table('part_virtual_field');
1556 unless ( $virtual_fields_cache{$table} ) {
1557 my $concat = [ "'cf_'", "name" ];
1558 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1559 "WHERE dbtable = '$table'";
1561 my $result = $dbh->selectcol_arrayref($query);
1562 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1564 $virtual_fields_cache{$table} = $result;
1567 @{$virtual_fields_cache{$table}};
1571 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1573 Processes a batch import as a queued JSRPC job
1575 JOB is an FS::queue entry.
1577 OPTIONS_HASHREF can have the following keys:
1583 Table name (required).
1587 Arrayref of field names for static fields. They will be given values from the
1588 PARAMS hashref and passed as a "params" hashref to batch_import.
1592 Formats hashref. Keys are field names, values are listrefs that define the
1595 Each listref value can be a column name or a code reference. Coderefs are run
1596 with the row object, data and a FS::Conf object as the three parameters.
1597 For example, this coderef does the same thing as using the "columnname" string:
1600 my( $record, $data, $conf ) = @_;
1601 $record->columnname( $data );
1604 Coderefs are run after all "column name" fields are assigned.
1608 Optional format hashref of types. Keys are field names, values are "csv",
1609 "xls" or "fixedlength". Overrides automatic determination of file type
1612 =item format_headers
1614 Optional format hashref of header lines. Keys are field names, values are 0
1615 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1618 =item format_sep_chars
1620 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1621 CSV separation character.
1623 =item format_fixedlenth_formats
1625 Optional format hashref of fixed length format defintiions. Keys are field
1626 names, values Parse::FixedLength listrefs of field definitions.
1630 Set true to default to CSV file type if the filename does not contain a
1631 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1636 PARAMS is a hashref (or base64-encoded Storable hashref) containing the
1637 POSTed data. It must contain the field "uploaded files", generated by
1638 /elements/file-upload.html and containing the list of uploaded files.
1639 Currently only supports a single file named "file".
1643 # uploaded_files is kind of bizarre; fix that some time
1645 use Storable qw(thaw);
1648 sub process_batch_import {
1649 my($job, $opt) = ( shift, shift );
1651 my $table = $opt->{table};
1652 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1653 my %formats = %{ $opt->{formats} };
1656 # because some job-spawning code (JSRPC) pre-freezes the arguments,
1657 # and then the 'frozen' attribute doesn't get set, and thus $job->args
1658 # doesn't know to thaw them, we have to do this everywhere.
1660 $param = thaw(decode_base64($param));
1662 warn Dumper($param) if $DEBUG;
1664 my $files = $param->{'uploaded_files'}
1665 or die "No files provided.\n";
1667 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1669 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1670 my $file = $dir. $files{'file'};
1675 formats => \%formats,
1676 format_types => $opt->{format_types},
1677 format_headers => $opt->{format_headers},
1678 format_sep_chars => $opt->{format_sep_chars},
1679 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1680 format_xml_formats => $opt->{format_xml_formats},
1681 format_asn_formats => $opt->{format_asn_formats},
1682 format_row_callbacks => $opt->{format_row_callbacks},
1687 format => $param->{format},
1688 params => { map { $_ => $param->{$_} } @pass_params },
1690 default_csv => $opt->{default_csv},
1691 postinsert_callback => $opt->{postinsert_callback},
1694 if ( $opt->{'batch_namecol'} ) {
1695 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1696 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1699 my $error = FS::Record::batch_import( \%iopt );
1703 die "$error\n" if $error;
1706 =item batch_import PARAM_HASHREF
1708 Class method for batch imports. Available params:
1714 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1720 =item format_headers
1722 =item format_sep_chars
1724 =item format_fixedlength_formats
1726 =item format_row_callbacks
1728 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1730 =item preinsert_callback
1732 =item postinsert_callback
1738 FS::queue object, will be updated with progress
1744 csv, xls, fixedlength, xml
1755 warn "$me batch_import call with params: \n". Dumper($param)
1758 my $table = $param->{table};
1760 my $job = $param->{job};
1761 my $file = $param->{file};
1762 my $params = $param->{params} || {};
1764 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1765 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1767 my( $type, $header, $sep_char,
1768 $fixedlength_format, $xml_format, $asn_format,
1769 $parser_opt, $row_callback, @fields );
1771 my $postinsert_callback = '';
1772 $postinsert_callback = $param->{'postinsert_callback'}
1773 if $param->{'postinsert_callback'};
1774 my $preinsert_callback = '';
1775 $preinsert_callback = $param->{'preinsert_callback'}
1776 if $param->{'preinsert_callback'};
1778 if ( $param->{'format'} ) {
1780 my $format = $param->{'format'};
1781 my $formats = $param->{formats};
1782 die "unknown format $format" unless exists $formats->{ $format };
1784 $type = $param->{'format_types'}
1785 ? $param->{'format_types'}{ $format }
1786 : $param->{type} || 'csv';
1789 $header = $param->{'format_headers'}
1790 ? $param->{'format_headers'}{ $param->{'format'} }
1793 $sep_char = $param->{'format_sep_chars'}
1794 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1797 $fixedlength_format =
1798 $param->{'format_fixedlength_formats'}
1799 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1803 $param->{'format_parser_opts'}
1804 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1808 $param->{'format_xml_formats'}
1809 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1813 $param->{'format_asn_formats'}
1814 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1818 $param->{'format_row_callbacks'}
1819 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1822 @fields = @{ $formats->{ $format } };
1824 } elsif ( $param->{'fields'} ) {
1826 $type = ''; #infer from filename
1829 $fixedlength_format = '';
1831 @fields = @{ $param->{'fields'} };
1834 die "neither format nor fields specified";
1837 #my $file = $param->{file};
1840 if ( $file =~ /\.(\w+)$/i ) {
1844 warn "can't parse file type from filename $file; defaulting to CSV";
1848 if $param->{'default_csv'} && $type ne 'xls';
1856 my $asn_header_buffer;
1857 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1859 if ( $type eq 'csv' ) {
1861 $parser_opt->{'binary'} = 1;
1862 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
1863 $parser = Text::CSV_XS->new($parser_opt);
1865 } elsif ( $type eq 'fixedlength' ) {
1867 eval "use Parse::FixedLength;";
1869 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
1872 die "Unknown file type $type\n";
1875 @buffer = split(/\r?\n/, slurp($file) );
1876 splice(@buffer, 0, ($header || 0) );
1877 $count = scalar(@buffer);
1879 } elsif ( $type eq 'xls' ) {
1881 eval "use Spreadsheet::ParseExcel;";
1884 eval "use DateTime::Format::Excel;";
1885 #for now, just let the error be thrown if it is used, since only CDR
1886 # formats bill_west and troop use it, not other excel-parsing things
1889 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1891 $parser = $excel->{Worksheet}[0]; #first sheet
1893 $count = $parser->{MaxRow} || $parser->{MinRow};
1896 $row = $header || 0;
1898 } elsif ( $type eq 'xml' ) {
1901 eval "use XML::Simple;";
1903 my $xmlrow = $xml_format->{'xmlrow'};
1904 $parser = $xml_format->{'xmlkeys'};
1905 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1906 my $data = XML::Simple::XMLin(
1908 'SuppressEmpty' => '', #sets empty values to ''
1912 $rows = $rows->{$_} foreach @$xmlrow;
1913 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1914 $count = @buffer = @$rows;
1916 } elsif ( $type eq 'asn.1' ) {
1918 eval "use Convert::ASN1";
1921 my $asn = Convert::ASN1->new;
1922 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1924 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1926 my $data = slurp($file);
1927 my $asn_output = $parser->decode( $data )
1928 or return "No ". $asn_format->{'macro'}. " found\n";
1930 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1932 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1933 $count = @buffer = @$rows;
1936 die "Unknown file type $type\n";
1941 local $SIG{HUP} = 'IGNORE';
1942 local $SIG{INT} = 'IGNORE';
1943 local $SIG{QUIT} = 'IGNORE';
1944 local $SIG{TERM} = 'IGNORE';
1945 local $SIG{TSTP} = 'IGNORE';
1946 local $SIG{PIPE} = 'IGNORE';
1948 my $oldAutoCommit = $FS::UID::AutoCommit;
1949 local $FS::UID::AutoCommit = 0;
1952 #my $params = $param->{params} || {};
1953 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1954 my $batch_col = $param->{'batch_keycol'};
1956 my $batch_class = 'FS::'. $param->{'batch_table'};
1957 my $batch = $batch_class->new({
1958 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1960 my $error = $batch->insert;
1962 $dbh->rollback if $oldAutoCommit;
1963 return "can't insert batch record: $error";
1965 #primary key via dbdef? (so the column names don't have to match)
1966 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1968 $params->{ $batch_col } = $batch_value;
1971 #my $job = $param->{job};
1974 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1978 my %hash = %$params;
1979 if ( $type eq 'csv' ) {
1981 last unless scalar(@buffer);
1982 $line = shift(@buffer);
1984 next if $line =~ /^\s*$/; #skip empty lines
1986 $line = &{$row_callback}($line) if $row_callback;
1988 next if $line =~ /^\s*$/; #skip empty lines
1990 $parser->parse($line) or do {
1991 $dbh->rollback if $oldAutoCommit;
1992 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
1994 @columns = $parser->fields();
1996 } elsif ( $type eq 'fixedlength' ) {
1998 last unless scalar(@buffer);
1999 $line = shift(@buffer);
2001 @columns = $parser->parse($line);
2003 } elsif ( $type eq 'xls' ) {
2005 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
2006 || ! $parser->{Cells}[$row];
2008 my @row = @{ $parser->{Cells}[$row] };
2009 @columns = map $_->{Val}, @row;
2012 #warn $z++. ": $_\n" for @columns;
2014 } elsif ( $type eq 'xml' ) {
2016 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2017 last unless scalar(@buffer);
2018 my $row = shift @buffer;
2019 @columns = @{ $row }{ @$parser };
2021 } elsif ( $type eq 'asn.1' ) {
2023 last unless scalar(@buffer);
2024 my $row = shift @buffer;
2025 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2026 if $asn_format->{row_callback};
2027 foreach my $key ( keys %{ $asn_format->{map} } ) {
2028 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2032 die "Unknown file type $type\n";
2037 foreach my $field ( @fields ) {
2039 my $value = shift @columns;
2041 if ( ref($field) eq 'CODE' ) {
2042 #&{$field}(\%hash, $value);
2043 push @later, $field, $value;
2045 #??? $hash{$field} = $value if length($value);
2046 $hash{$field} = $value if defined($value) && length($value);
2051 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2052 && length($1) == $custnum_length ) {
2053 $hash{custnum} = $2;
2056 #my $table = $param->{table};
2057 my $class = "FS::$table";
2059 my $record = $class->new( \%hash );
2062 while ( scalar(@later) ) {
2063 my $sub = shift @later;
2064 my $data = shift @later;
2066 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2069 $dbh->rollback if $oldAutoCommit;
2070 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2072 last if exists( $param->{skiprow} );
2074 next if exists( $param->{skiprow} );
2076 if ( $preinsert_callback ) {
2077 my $error = &{$preinsert_callback}($record, $param);
2079 $dbh->rollback if $oldAutoCommit;
2080 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2083 next if exists $param->{skiprow} && $param->{skiprow};
2086 my $error = $record->insert;
2089 $dbh->rollback if $oldAutoCommit;
2090 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2096 if ( $postinsert_callback ) {
2097 my $error = &{$postinsert_callback}($record, $param);
2099 $dbh->rollback if $oldAutoCommit;
2100 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2105 if ( $job && time - $min_sec > $last ) { #progress bar
2106 $job->update_statustext( int(100 * $imported / $count) );
2112 unless ( $imported || $param->{empty_ok} ) {
2113 $dbh->rollback if $oldAutoCommit;
2114 return "Empty file!";
2117 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2124 my( $self, $action, $time ) = @_;
2128 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2131 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2132 real_fields($self->table);
2135 # If we're encrypting then don't store the payinfo in the history
2136 if ( $conf && $conf->exists('encryption') && $self->table ne 'banned_pay' ) {
2137 @fields = grep { $_ ne 'payinfo' } @fields;
2140 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2142 "INSERT INTO h_". $self->table. " ( ".
2143 join(', ', qw(history_date history_user history_action), @fields ).
2145 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
2152 B<Warning>: External use is B<deprecated>.
2154 Replaces COLUMN in record with a unique number, using counters in the
2155 filesystem. Used by the B<insert> method on single-field unique columns
2156 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2157 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2159 Returns the new value.
2164 my($self,$field) = @_;
2165 my($table)=$self->table;
2167 croak "Unique called on field $field, but it is ",
2168 $self->getfield($field),
2170 if $self->getfield($field);
2172 #warn "table $table is tainted" if is_tainted($table);
2173 #warn "field $field is tainted" if is_tainted($field);
2175 my($counter) = new File::CounterFile "$table.$field",0;
2177 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2179 # my($counter) = new File::CounterFile "$user/$table.$field",0;
2182 my $index = $counter->inc;
2183 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2185 $index =~ /^(\d*)$/;
2188 $self->setfield($field,$index);
2192 =item ut_float COLUMN
2194 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2195 null. If there is an error, returns the error, otherwise returns false.
2200 my($self,$field)=@_ ;
2201 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2202 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2203 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2204 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2205 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2206 $self->setfield($field,$1);
2209 =item ut_floatn COLUMN
2211 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2212 null. If there is an error, returns the error, otherwise returns false.
2216 #false laziness w/ut_ipn
2218 my( $self, $field ) = @_;
2219 if ( $self->getfield($field) =~ /^()$/ ) {
2220 $self->setfield($field,'');
2223 $self->ut_float($field);
2227 =item ut_sfloat COLUMN
2229 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2230 May not be null. If there is an error, returns the error, otherwise returns
2236 my($self,$field)=@_ ;
2237 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2238 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2239 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2240 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2241 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2242 $self->setfield($field,$1);
2245 =item ut_sfloatn COLUMN
2247 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2248 null. If there is an error, returns the error, otherwise returns false.
2253 my( $self, $field ) = @_;
2254 if ( $self->getfield($field) =~ /^()$/ ) {
2255 $self->setfield($field,'');
2258 $self->ut_sfloat($field);
2262 =item ut_snumber COLUMN
2264 Check/untaint signed numeric data (whole numbers). If there is an error,
2265 returns the error, otherwise returns false.
2270 my($self, $field) = @_;
2271 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2272 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2273 $self->setfield($field, "$1$2");
2277 =item ut_snumbern COLUMN
2279 Check/untaint signed numeric data (whole numbers). If there is an error,
2280 returns the error, otherwise returns false.
2285 my($self, $field) = @_;
2286 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2287 or return "Illegal (numeric) $field: ". $self->getfield($field);
2289 return "Illegal (numeric) $field: ". $self->getfield($field)
2292 $self->setfield($field, "$1$2");
2296 =item ut_number COLUMN
2298 Check/untaint simple numeric data (whole numbers). May not be null. If there
2299 is an error, returns the error, otherwise returns false.
2304 my($self,$field)=@_;
2305 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2306 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2307 $self->setfield($field,$1);
2311 =item ut_numbern COLUMN
2313 Check/untaint simple numeric data (whole numbers). May be null. If there is
2314 an error, returns the error, otherwise returns false.
2319 my($self,$field)=@_;
2320 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2321 or return "Illegal (numeric) $field: ". $self->getfield($field);
2322 $self->setfield($field,$1);
2326 =item ut_decimal COLUMN[, DIGITS]
2328 Check/untaint decimal numbers (up to DIGITS decimal places. If there is an
2329 error, returns the error, otherwise returns false.
2331 =item ut_decimaln COLUMN[, DIGITS]
2333 Check/untaint decimal numbers. May be null. If there is an error, returns
2334 the error, otherwise returns false.
2339 my($self, $field, $digits) = @_;
2341 $self->getfield($field) =~ /^\s*(\d+(\.\d{0,$digits})?)\s*$/
2342 or return "Illegal or empty (decimal) $field: ".$self->getfield($field);
2343 $self->setfield($field, $1);
2348 my($self, $field, $digits) = @_;
2349 $self->getfield($field) =~ /^\s*(\d*(\.\d{0,$digits})?)\s*$/
2350 or return "Illegal (decimal) $field: ".$self->getfield($field);
2351 $self->setfield($field, $1);
2355 =item ut_money COLUMN
2357 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2358 is an error, returns the error, otherwise returns false.
2363 my($self,$field)=@_;
2365 if ( $self->getfield($field) eq '' ) {
2366 $self->setfield($field, 0);
2367 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2368 #handle one decimal place without barfing out
2369 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2370 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2371 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2373 return "Illegal (money) $field: ". $self->getfield($field);
2379 =item ut_moneyn COLUMN
2381 Check/untaint monetary numbers. May be negative. If there
2382 is an error, returns the error, otherwise returns false.
2387 my($self,$field)=@_;
2388 if ($self->getfield($field) eq '') {
2389 $self->setfield($field, '');
2392 $self->ut_money($field);
2395 =item ut_text COLUMN
2397 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2398 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2399 May not be null. If there is an error, returns the error, otherwise returns
2405 my($self,$field)=@_;
2406 #warn "msgcat ". \&msgcat. "\n";
2407 #warn "notexist ". \¬exist. "\n";
2408 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2409 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2410 # see perldoc perluniprops
2411 $self->getfield($field)
2412 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2413 or return gettext('illegal_or_empty_text'). " $field: ".
2414 $self->getfield($field);
2415 $self->setfield($field,$1);
2419 =item ut_textn COLUMN
2421 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2422 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2423 May be null. If there is an error, returns the error, otherwise returns false.
2428 my($self,$field)=@_;
2429 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2430 $self->ut_text($field);
2433 =item ut_alpha COLUMN
2435 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2436 an error, returns the error, otherwise returns false.
2441 my($self,$field)=@_;
2442 $self->getfield($field) =~ /^(\w+)$/
2443 or return "Illegal or empty (alphanumeric) $field: ".
2444 $self->getfield($field);
2445 $self->setfield($field,$1);
2449 =item ut_alphan COLUMN
2451 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2452 error, returns the error, otherwise returns false.
2457 my($self,$field)=@_;
2458 $self->getfield($field) =~ /^(\w*)$/
2459 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2460 $self->setfield($field,$1);
2464 =item ut_alphasn COLUMN
2466 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2467 an error, returns the error, otherwise returns false.
2472 my($self,$field)=@_;
2473 $self->getfield($field) =~ /^([\w ]*)$/
2474 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2475 $self->setfield($field,$1);
2480 =item ut_alpha_lower COLUMN
2482 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2483 there is an error, returns the error, otherwise returns false.
2487 sub ut_alpha_lower {
2488 my($self,$field)=@_;
2489 $self->getfield($field) =~ /[[:upper:]]/
2490 and return "Uppercase characters are not permitted in $field";
2491 $self->ut_alpha($field);
2494 =item ut_phonen COLUMN [ COUNTRY ]
2496 Check/untaint phone numbers. May be null. If there is an error, returns
2497 the error, otherwise returns false.
2499 Takes an optional two-letter ISO 3166-1 alpha-2 country code; without
2500 it or with unsupported countries, ut_phonen simply calls ut_alphan.
2505 my( $self, $field, $country ) = @_;
2506 return $self->ut_alphan($field) unless defined $country;
2507 my $phonen = $self->getfield($field);
2508 if ( $phonen eq '' ) {
2509 $self->setfield($field,'');
2510 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2512 $phonen = $conf->config('cust_main-default_areacode').$phonen
2513 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2514 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2515 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2516 $phonen = "$1-$2-$3";
2517 $phonen .= " x$4" if $4;
2518 $self->setfield($field,$phonen);
2520 warn "warning: don't know how to check phone numbers for country $country";
2521 return $self->ut_textn($field);
2528 Check/untaint hexadecimal values.
2533 my($self, $field) = @_;
2534 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2535 or return "Illegal (hex) $field: ". $self->getfield($field);
2536 $self->setfield($field, uc($1));
2540 =item ut_hexn COLUMN
2542 Check/untaint hexadecimal values. May be null.
2547 my($self, $field) = @_;
2548 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2549 or return "Illegal (hex) $field: ". $self->getfield($field);
2550 $self->setfield($field, uc($1));
2554 =item ut_mac_addr COLUMN
2556 Check/untaint mac addresses. May be null.
2561 my($self, $field) = @_;
2563 my $mac = $self->get($field);
2566 $self->set($field, $mac);
2568 my $e = $self->ut_hex($field);
2571 return "Illegal (mac address) $field: ". $self->getfield($field)
2572 unless length($self->getfield($field)) == 12;
2578 =item ut_mac_addrn COLUMN
2580 Check/untaint mac addresses. May be null.
2585 my($self, $field) = @_;
2586 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2591 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2597 my( $self, $field ) = @_;
2598 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2599 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2600 or return "Illegal (IP address) $field: ". $self->getfield($field);
2601 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2602 $self->setfield($field, "$1.$2.$3.$4");
2608 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2609 to 127.0.0.1. May be null.
2614 my( $self, $field ) = @_;
2615 if ( $self->getfield($field) =~ /^()$/ ) {
2616 $self->setfield($field,'');
2619 $self->ut_ip($field);
2623 =item ut_ip46 COLUMN
2625 Check/untaint IPv4 or IPv6 address.
2630 my( $self, $field ) = @_;
2631 my $ip = NetAddr::IP->new($self->getfield($field))
2632 or return "Illegal (IP address) $field: ".$self->getfield($field);
2633 $self->setfield($field, lc($ip->addr));
2639 Check/untaint IPv6 or IPv6 address. May be null.
2644 my( $self, $field ) = @_;
2645 if ( $self->getfield($field) =~ /^$/ ) {
2646 $self->setfield($field, '');
2649 $self->ut_ip46($field);
2652 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2654 Check/untaint coordinates.
2655 Accepts the following forms:
2665 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2666 The latter form (that is, the MMM are thousands of minutes) is
2667 assumed if the "MMM" is exactly three digits or two digits > 59.
2669 To be safe, just use the DDD.DDDDD form.
2671 If LOWER or UPPER are specified, then the coordinate is checked
2672 for lower and upper bounds, respectively.
2677 my ($self, $field) = (shift, shift);
2680 if ( $field =~ /latitude/ ) {
2681 $lower = $lat_lower;
2683 } elsif ( $field =~ /longitude/ ) {
2685 $upper = $lon_upper;
2688 my $coord = $self->getfield($field);
2689 my $neg = $coord =~ s/^(-)//;
2691 my ($d, $m, $s) = (0, 0, 0);
2694 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2695 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2696 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2698 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2701 return "Invalid (coordinate with minutes > 59) $field: "
2702 . $self->getfield($field);
2705 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2707 if (defined($lower) and ($coord < $lower)) {
2708 return "Invalid (coordinate < $lower) $field: "
2709 . $self->getfield($field);;
2712 if (defined($upper) and ($coord > $upper)) {
2713 return "Invalid (coordinate > $upper) $field: "
2714 . $self->getfield($field);;
2717 $self->setfield($field, $coord);
2721 return "Invalid (coordinate) $field: " . $self->getfield($field);
2725 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2727 Same as ut_coord, except optionally null.
2733 my ($self, $field) = (shift, shift);
2735 if ($self->getfield($field) =~ /^\s*$/) {
2738 return $self->ut_coord($field, @_);
2743 =item ut_domain COLUMN
2745 Check/untaint host and domain names. May not be null.
2750 my( $self, $field ) = @_;
2751 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2752 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2753 or return "Illegal (hostname) $field: ". $self->getfield($field);
2754 $self->setfield($field,$1);
2758 =item ut_domainn COLUMN
2760 Check/untaint host and domain names. May be null.
2765 my( $self, $field ) = @_;
2766 if ( $self->getfield($field) =~ /^()$/ ) {
2767 $self->setfield($field,'');
2770 $self->ut_domain($field);
2774 =item ut_name COLUMN
2776 Check/untaint proper names; allows alphanumerics, spaces and the following
2777 punctuation: , . - '
2784 my( $self, $field ) = @_;
2785 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2786 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
2787 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2792 $self->setfield($field, $name);
2796 =item ut_namen COLUMN
2798 Check/untaint proper names; allows alphanumerics, spaces and the following
2799 punctuation: , . - '
2806 my( $self, $field ) = @_;
2807 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2808 $self->ut_name($field);
2813 Check/untaint zip codes.
2817 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2820 my( $self, $field, $country ) = @_;
2822 if ( $country eq 'US' ) {
2824 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2825 or return gettext('illegal_zip'). " $field for country $country: ".
2826 $self->getfield($field);
2827 $self->setfield($field, $1);
2829 } elsif ( $country eq 'CA' ) {
2831 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2832 or return gettext('illegal_zip'). " $field for country $country: ".
2833 $self->getfield($field);
2834 $self->setfield($field, "$1 $2");
2838 if ( $self->getfield($field) =~ /^\s*$/
2839 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2842 $self->setfield($field,'');
2844 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2845 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2846 $self->setfield($field,$1);
2854 =item ut_country COLUMN
2856 Check/untaint country codes. Country names are changed to codes, if possible -
2857 see L<Locale::Country>.
2862 my( $self, $field ) = @_;
2863 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2864 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2865 && country2code($1) ) {
2866 $self->setfield($field,uc(country2code($1)));
2869 $self->getfield($field) =~ /^(\w\w)$/
2870 or return "Illegal (country) $field: ". $self->getfield($field);
2871 $self->setfield($field,uc($1));
2875 =item ut_anything COLUMN
2877 Untaints arbitrary data. Be careful.
2882 my( $self, $field ) = @_;
2883 $self->getfield($field) =~ /^(.*)$/s
2884 or return "Illegal $field: ". $self->getfield($field);
2885 $self->setfield($field,$1);
2889 =item ut_enum COLUMN CHOICES_ARRAYREF
2891 Check/untaint a column, supplying all possible choices, like the "enum" type.
2896 my( $self, $field, $choices ) = @_;
2897 foreach my $choice ( @$choices ) {
2898 if ( $self->getfield($field) eq $choice ) {
2899 $self->setfield($field, $choice);
2903 return "Illegal (enum) field $field: ". $self->getfield($field);
2906 =item ut_enumn COLUMN CHOICES_ARRAYREF
2908 Like ut_enum, except the null value is also allowed.
2913 my( $self, $field, $choices ) = @_;
2914 $self->getfield($field)
2915 ? $self->ut_enum($field, $choices)
2919 =item ut_flag COLUMN
2921 Check/untaint a column if it contains either an empty string or 'Y'. This
2922 is the standard form for boolean flags in Freeside.
2927 my( $self, $field ) = @_;
2928 my $value = uc($self->getfield($field));
2929 if ( $value eq '' or $value eq 'Y' ) {
2930 $self->setfield($field, $value);
2933 return "Illegal (flag) field $field: $value";
2936 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2938 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2939 on the column first.
2943 sub ut_foreign_key {
2944 my( $self, $field, $table, $foreign ) = @_;
2945 return '' if $no_check_foreign;
2946 qsearchs($table, { $foreign => $self->getfield($field) })
2947 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2948 " in $table.$foreign";
2952 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2954 Like ut_foreign_key, except the null value is also allowed.
2958 sub ut_foreign_keyn {
2959 my( $self, $field, $table, $foreign ) = @_;
2960 $self->getfield($field)
2961 ? $self->ut_foreign_key($field, $table, $foreign)
2965 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2967 Checks this column as an agentnum, taking into account the current users's
2968 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2969 right or rights allowing no agentnum.
2973 sub ut_agentnum_acl {
2974 my( $self, $field ) = (shift, shift);
2975 my $null_acl = scalar(@_) ? shift : [];
2976 $null_acl = [ $null_acl ] unless ref($null_acl);
2978 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2979 return "Illegal agentnum: $error" if $error;
2981 my $curuser = $FS::CurrentUser::CurrentUser;
2983 if ( $self->$field() ) {
2985 return "Access denied"
2986 unless $curuser->agentnum($self->$field());
2990 return "Access denied"
2991 unless grep $curuser->access_right($_), @$null_acl;
2999 =item fields [ TABLE ]
3001 This is a wrapper for real_fields. Code that called
3002 fields before should probably continue to call fields.
3007 my $something = shift;
3009 if($something->isa('FS::Record')) {
3010 $table = $something->table;
3012 $table = $something;
3013 $something = "FS::$table";
3015 return (real_fields($table));
3019 =item encrypt($value)
3021 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
3023 Returns the encrypted string.
3025 You should generally not have to worry about calling this, as the system handles this for you.
3030 my ($self, $value) = @_;
3031 my $encrypted = $value;
3033 if ($conf->exists('encryption')) {
3034 if ($self->is_encrypted($value)) {
3035 # Return the original value if it isn't plaintext.
3036 $encrypted = $value;
3039 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3040 # RSA doesn't like the empty string so let's pack it up
3041 # The database doesn't like the RSA data so uuencode it
3042 my $length = length($value)+1;
3043 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3045 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3052 =item is_encrypted($value)
3054 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3060 my ($self, $value) = @_;
3061 # Possible Bug - Some work may be required here....
3063 if ($value =~ /^M/ && length($value) > 80) {
3070 =item decrypt($value)
3072 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3074 You should generally not have to worry about calling this, as the system handles this for you.
3079 my ($self,$value) = @_;
3080 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3081 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
3083 if (ref($rsa_decrypt) =~ /::RSA/) {
3084 my $encrypted = unpack ("u*", $value);
3085 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3086 if ($@) {warn "Decryption Failed"};
3094 #Initialize the Module
3095 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3097 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
3098 $rsa_module = $conf->config('encryptionmodule');
3102 eval ("require $rsa_module"); # No need to import the namespace
3105 # Initialize Encryption
3106 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
3107 my $public_key = join("\n",$conf->config('encryptionpublickey'));
3108 $rsa_encrypt = $rsa_module->new_public_key($public_key);
3111 # Intitalize Decryption
3112 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
3113 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
3114 $rsa_decrypt = $rsa_module->new_private_key($private_key);
3118 =item h_search ACTION
3120 Given an ACTION, either "insert", or "delete", returns the appropriate history
3121 record corresponding to this record, if any.
3126 my( $self, $action ) = @_;
3128 my $table = $self->table;
3131 my $primary_key = dbdef->table($table)->primary_key;
3134 'table' => "h_$table",
3135 'hashref' => { $primary_key => $self->$primary_key(),
3136 'history_action' => $action,
3144 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3145 appropriate history record corresponding to this record, if any.
3150 my($self, $action) = @_;
3151 my $h = $self->h_search($action);
3152 $h ? $h->history_date : '';
3155 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3157 A class or object method. Executes the sql statement represented by SQL and
3158 returns a scalar representing the result: the first column of the first row.
3160 Dies on bogus SQL. Returns an empty string if no row is returned.
3162 Typically used for statments which return a single value such as "SELECT
3163 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3168 my($self, $sql) = (shift, shift);
3169 my $sth = dbh->prepare($sql) or die dbh->errstr;
3171 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3172 my $row = $sth->fetchrow_arrayref or return '';
3173 my $scalar = $row->[0];
3174 defined($scalar) ? $scalar : '';
3177 =item count [ WHERE [, PLACEHOLDER ...] ]
3179 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3180 with optional WHERE. Must be called as method on a class with an
3186 my($self, $where) = (shift, shift);
3187 my $table = $self->table or die 'count called on object of class '.ref($self);
3188 my $sql = "SELECT COUNT(*) FROM $table";
3189 $sql .= " WHERE $where" if $where;
3190 $self->scalar_sql($sql, @_);
3199 =item real_fields [ TABLE ]
3201 Returns a list of the real columns in the specified table. Called only by
3202 fields() and other subroutines elsewhere in FS::Record.
3209 my($table_obj) = dbdef->table($table);
3210 confess "Unknown table $table" unless $table_obj;
3211 $table_obj->columns;
3214 =item pvf FIELD_NAME
3216 Returns the FS::part_virtual_field object corresponding to a field in the
3217 record (specified by FIELD_NAME).
3222 my ($self, $name) = (shift, shift);
3224 if(grep /^$name$/, $self->virtual_fields) {
3226 my $concat = [ "'cf_'", "name" ];
3227 return qsearchs({ table => 'part_virtual_field',
3228 hashref => { dbtable => $self->table,
3231 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3237 =item _quote VALUE, TABLE, COLUMN
3239 This is an internal function used to construct SQL statements. It returns
3240 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3241 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3246 my($value, $table, $column) = @_;
3247 my $column_obj = dbdef->table($table)->column($column);
3248 my $column_type = $column_obj->type;
3249 my $nullable = $column_obj->null;
3251 utf8::upgrade($value);
3253 warn " $table.$column: $value ($column_type".
3254 ( $nullable ? ' NULL' : ' NOT NULL' ).
3255 ")\n" if $DEBUG > 2;
3257 if ( $value eq '' && $nullable ) {
3259 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3260 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3263 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3264 ! $column_type =~ /(char|binary|text)$/i ) {
3266 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3267 && driver_name eq 'Pg'
3271 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3272 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3273 # single-quote the whole mess, and put an "E" in front.
3274 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3282 This is deprecated. Don't use it.
3284 It returns a hash-type list with the fields of this record's table set true.
3289 carp "warning: hfields is deprecated";
3292 foreach (fields($table)) {
3301 "$_: ". $self->getfield($_). "|"
3302 } (fields($self->table)) );
3305 sub DESTROY { return; }
3309 # #use Carp qw(cluck);
3310 # #cluck "DESTROYING $self";
3311 # warn "DESTROYING $self";
3315 # return ! eval { join('',@_), kill 0; 1; };
3318 =item str2time_sql [ DRIVER_NAME ]
3320 Returns a function to convert to unix time based on database type, such as
3321 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3322 the str2time_sql_closing method to return a closing string rather than just
3323 using a closing parenthesis as previously suggested.
3325 You can pass an optional driver name such as "Pg", "mysql" or
3326 $dbh->{Driver}->{Name} to return a function for that database instead of
3327 the current database.
3332 my $driver = shift || driver_name;
3334 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3335 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3337 warn "warning: unknown database type $driver; guessing how to convert ".
3338 "dates to UNIX timestamps";
3339 return 'EXTRACT(EPOCH FROM ';
3343 =item str2time_sql_closing [ DRIVER_NAME ]
3345 Returns the closing suffix of a function to convert to unix time based on
3346 database type, such as ")::integer" for Pg or ")" for mysql.
3348 You can pass an optional driver name such as "Pg", "mysql" or
3349 $dbh->{Driver}->{Name} to return a function for that database instead of
3350 the current database.
3354 sub str2time_sql_closing {
3355 my $driver = shift || driver_name;
3357 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3361 =item regexp_sql [ DRIVER_NAME ]
3363 Returns the operator to do a regular expression comparison based on database
3364 type, such as '~' for Pg or 'REGEXP' for mysql.
3366 You can pass an optional driver name such as "Pg", "mysql" or
3367 $dbh->{Driver}->{Name} to return a function for that database instead of
3368 the current database.
3373 my $driver = shift || driver_name;
3375 return '~' if $driver =~ /^Pg/i;
3376 return 'REGEXP' if $driver =~ /^mysql/i;
3378 die "don't know how to use regular expressions in ". driver_name." databases";
3382 =item not_regexp_sql [ DRIVER_NAME ]
3384 Returns the operator to do a regular expression negation based on database
3385 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3387 You can pass an optional driver name such as "Pg", "mysql" or
3388 $dbh->{Driver}->{Name} to return a function for that database instead of
3389 the current database.
3393 sub not_regexp_sql {
3394 my $driver = shift || driver_name;
3396 return '!~' if $driver =~ /^Pg/i;
3397 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3399 die "don't know how to use regular expressions in ". driver_name." databases";
3403 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3405 Returns the items concatenated based on database type, using "CONCAT()" for
3406 mysql and " || " for Pg and other databases.
3408 You can pass an optional driver name such as "Pg", "mysql" or
3409 $dbh->{Driver}->{Name} to return a function for that database instead of
3410 the current database.
3415 my $driver = ref($_[0]) ? driver_name : shift;
3418 if ( $driver =~ /^mysql/i ) {
3419 'CONCAT('. join(',', @$items). ')';
3421 join('||', @$items);
3426 =item group_concat_sql COLUMN, DELIMITER
3428 Returns an SQL expression to concatenate an aggregate column, using
3429 GROUP_CONCAT() for mysql and array_to_string() and array_agg() for Pg.
3433 sub group_concat_sql {
3434 my ($col, $delim) = @_;
3435 $delim = dbh->quote($delim);
3436 if ( driver_name() =~ /^mysql/i ) {
3437 # DISTINCT(foo) is valid as $col
3438 return "GROUP_CONCAT($col SEPARATOR $delim)";
3440 return "array_to_string(array_agg($col), $delim)";
3444 =item midnight_sql DATE
3446 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3447 on that day in the system timezone, using the default driver name.
3452 my $driver = driver_name;
3454 if ( $driver =~ /^mysql/i ) {
3455 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3458 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3466 This module should probably be renamed, since much of the functionality is
3467 of general use. It is not completely unlike Adapter::DBI (see below).
3469 Exported qsearch and qsearchs should be deprecated in favor of method calls
3470 (against an FS::Record object like the old search and searchs that qsearch
3471 and qsearchs were on top of.)
3473 The whole fields / hfields mess should be removed.
3475 The various WHERE clauses should be subroutined.
3477 table string should be deprecated in favor of DBIx::DBSchema::Table.
3479 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3480 true maps to the database (and WHERE clauses) would also help.
3482 The ut_ methods should ask the dbdef for a default length.
3484 ut_sqltype (like ut_varchar) should all be defined
3486 A fallback check method should be provided which uses the dbdef.
3488 The ut_money method assumes money has two decimal digits.
3490 The Pg money kludge in the new method only strips `$'.
3492 The ut_phonen method only checks US-style phone numbers.
3494 The _quote function should probably use ut_float instead of a regex.
3496 All the subroutines probably should be methods, here or elsewhere.
3498 Probably should borrow/use some dbdef methods where appropriate (like sub
3501 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3502 or allow it to be set. Working around it is ugly any way around - DBI should
3503 be fixed. (only affects RDBMS which return uppercase column names)
3505 ut_zip should take an optional country like ut_phone.
3509 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3511 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.