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 Listref 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 base64-encoded Storable string containing the POSTed data as
1637 a hash ref. It normally contains at least one field, "uploaded files",
1638 generated by /elements/file-upload.html and containing the list of uploaded
1639 files. Currently only supports a single file named "file".
1643 use Storable qw(thaw);
1646 sub process_batch_import {
1647 my($job, $opt) = ( shift, shift );
1649 my $table = $opt->{table};
1650 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1651 my %formats = %{ $opt->{formats} };
1653 my $param = thaw(decode_base64(shift));
1654 warn Dumper($param) if $DEBUG;
1656 my $files = $param->{'uploaded_files'}
1657 or die "No files provided.\n";
1659 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1661 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1662 my $file = $dir. $files{'file'};
1667 formats => \%formats,
1668 format_types => $opt->{format_types},
1669 format_headers => $opt->{format_headers},
1670 format_sep_chars => $opt->{format_sep_chars},
1671 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1672 format_xml_formats => $opt->{format_xml_formats},
1673 format_asn_formats => $opt->{format_asn_formats},
1674 format_row_callbacks => $opt->{format_row_callbacks},
1679 format => $param->{format},
1680 params => { map { $_ => $param->{$_} } @pass_params },
1682 default_csv => $opt->{default_csv},
1683 postinsert_callback => $opt->{postinsert_callback},
1686 if ( $opt->{'batch_namecol'} ) {
1687 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1688 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1691 my $error = FS::Record::batch_import( \%iopt );
1695 die "$error\n" if $error;
1698 =item batch_import PARAM_HASHREF
1700 Class method for batch imports. Available params:
1706 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1712 =item format_headers
1714 =item format_sep_chars
1716 =item format_fixedlength_formats
1718 =item format_row_callbacks
1720 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1722 =item preinsert_callback
1724 =item postinsert_callback
1730 FS::queue object, will be updated with progress
1736 csv, xls, fixedlength, xml
1747 warn "$me batch_import call with params: \n". Dumper($param)
1750 my $table = $param->{table};
1752 my $job = $param->{job};
1753 my $file = $param->{file};
1754 my $params = $param->{params} || {};
1756 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1757 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1759 my( $type, $header, $sep_char,
1760 $fixedlength_format, $xml_format, $asn_format,
1761 $parser_opt, $row_callback, @fields );
1763 my $postinsert_callback = '';
1764 $postinsert_callback = $param->{'postinsert_callback'}
1765 if $param->{'postinsert_callback'};
1766 my $preinsert_callback = '';
1767 $preinsert_callback = $param->{'preinsert_callback'}
1768 if $param->{'preinsert_callback'};
1770 if ( $param->{'format'} ) {
1772 my $format = $param->{'format'};
1773 my $formats = $param->{formats};
1774 die "unknown format $format" unless exists $formats->{ $format };
1776 $type = $param->{'format_types'}
1777 ? $param->{'format_types'}{ $format }
1778 : $param->{type} || 'csv';
1781 $header = $param->{'format_headers'}
1782 ? $param->{'format_headers'}{ $param->{'format'} }
1785 $sep_char = $param->{'format_sep_chars'}
1786 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1789 $fixedlength_format =
1790 $param->{'format_fixedlength_formats'}
1791 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1795 $param->{'format_parser_opts'}
1796 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1800 $param->{'format_xml_formats'}
1801 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1805 $param->{'format_asn_formats'}
1806 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1810 $param->{'format_row_callbacks'}
1811 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1814 @fields = @{ $formats->{ $format } };
1816 } elsif ( $param->{'fields'} ) {
1818 $type = ''; #infer from filename
1821 $fixedlength_format = '';
1823 @fields = @{ $param->{'fields'} };
1826 die "neither format nor fields specified";
1829 #my $file = $param->{file};
1832 if ( $file =~ /\.(\w+)$/i ) {
1836 warn "can't parse file type from filename $file; defaulting to CSV";
1840 if $param->{'default_csv'} && $type ne 'xls';
1848 my $asn_header_buffer;
1849 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1851 if ( $type eq 'csv' ) {
1853 $parser_opt->{'binary'} = 1;
1854 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
1855 $parser = Text::CSV_XS->new($parser_opt);
1857 } elsif ( $type eq 'fixedlength' ) {
1859 eval "use Parse::FixedLength;";
1861 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
1864 die "Unknown file type $type\n";
1867 @buffer = split(/\r?\n/, slurp($file) );
1868 splice(@buffer, 0, ($header || 0) );
1869 $count = scalar(@buffer);
1871 } elsif ( $type eq 'xls' ) {
1873 eval "use Spreadsheet::ParseExcel;";
1876 eval "use DateTime::Format::Excel;";
1877 #for now, just let the error be thrown if it is used, since only CDR
1878 # formats bill_west and troop use it, not other excel-parsing things
1881 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1883 $parser = $excel->{Worksheet}[0]; #first sheet
1885 $count = $parser->{MaxRow} || $parser->{MinRow};
1888 $row = $header || 0;
1890 } elsif ( $type eq 'xml' ) {
1893 eval "use XML::Simple;";
1895 my $xmlrow = $xml_format->{'xmlrow'};
1896 $parser = $xml_format->{'xmlkeys'};
1897 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1898 my $data = XML::Simple::XMLin(
1900 'SuppressEmpty' => '', #sets empty values to ''
1904 $rows = $rows->{$_} foreach @$xmlrow;
1905 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1906 $count = @buffer = @$rows;
1908 } elsif ( $type eq 'asn.1' ) {
1910 eval "use Convert::ASN1";
1913 my $asn = Convert::ASN1->new;
1914 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1916 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1918 my $data = slurp($file);
1919 my $asn_output = $parser->decode( $data )
1920 or return "No ". $asn_format->{'macro'}. " found\n";
1922 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1924 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1925 $count = @buffer = @$rows;
1928 die "Unknown file type $type\n";
1933 local $SIG{HUP} = 'IGNORE';
1934 local $SIG{INT} = 'IGNORE';
1935 local $SIG{QUIT} = 'IGNORE';
1936 local $SIG{TERM} = 'IGNORE';
1937 local $SIG{TSTP} = 'IGNORE';
1938 local $SIG{PIPE} = 'IGNORE';
1940 my $oldAutoCommit = $FS::UID::AutoCommit;
1941 local $FS::UID::AutoCommit = 0;
1944 #my $params = $param->{params} || {};
1945 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1946 my $batch_col = $param->{'batch_keycol'};
1948 my $batch_class = 'FS::'. $param->{'batch_table'};
1949 my $batch = $batch_class->new({
1950 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1952 my $error = $batch->insert;
1954 $dbh->rollback if $oldAutoCommit;
1955 return "can't insert batch record: $error";
1957 #primary key via dbdef? (so the column names don't have to match)
1958 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1960 $params->{ $batch_col } = $batch_value;
1963 #my $job = $param->{job};
1966 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1970 my %hash = %$params;
1971 if ( $type eq 'csv' ) {
1973 last unless scalar(@buffer);
1974 $line = shift(@buffer);
1976 next if $line =~ /^\s*$/; #skip empty lines
1978 $line = &{$row_callback}($line) if $row_callback;
1980 next if $line =~ /^\s*$/; #skip empty lines
1982 $parser->parse($line) or do {
1983 $dbh->rollback if $oldAutoCommit;
1984 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
1986 @columns = $parser->fields();
1988 } elsif ( $type eq 'fixedlength' ) {
1990 last unless scalar(@buffer);
1991 $line = shift(@buffer);
1993 @columns = $parser->parse($line);
1995 } elsif ( $type eq 'xls' ) {
1997 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1998 || ! $parser->{Cells}[$row];
2000 my @row = @{ $parser->{Cells}[$row] };
2001 @columns = map $_->{Val}, @row;
2004 #warn $z++. ": $_\n" for @columns;
2006 } elsif ( $type eq 'xml' ) {
2008 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2009 last unless scalar(@buffer);
2010 my $row = shift @buffer;
2011 @columns = @{ $row }{ @$parser };
2013 } elsif ( $type eq 'asn.1' ) {
2015 last unless scalar(@buffer);
2016 my $row = shift @buffer;
2017 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2018 if $asn_format->{row_callback};
2019 foreach my $key ( keys %{ $asn_format->{map} } ) {
2020 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2024 die "Unknown file type $type\n";
2029 foreach my $field ( @fields ) {
2031 my $value = shift @columns;
2033 if ( ref($field) eq 'CODE' ) {
2034 #&{$field}(\%hash, $value);
2035 push @later, $field, $value;
2037 #??? $hash{$field} = $value if length($value);
2038 $hash{$field} = $value if defined($value) && length($value);
2043 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2044 && length($1) == $custnum_length ) {
2045 $hash{custnum} = $2;
2048 #my $table = $param->{table};
2049 my $class = "FS::$table";
2051 my $record = $class->new( \%hash );
2054 while ( scalar(@later) ) {
2055 my $sub = shift @later;
2056 my $data = shift @later;
2058 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2061 $dbh->rollback if $oldAutoCommit;
2062 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2064 last if exists( $param->{skiprow} );
2066 next if exists( $param->{skiprow} );
2068 if ( $preinsert_callback ) {
2069 my $error = &{$preinsert_callback}($record, $param);
2071 $dbh->rollback if $oldAutoCommit;
2072 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2075 next if exists $param->{skiprow} && $param->{skiprow};
2078 my $error = $record->insert;
2081 $dbh->rollback if $oldAutoCommit;
2082 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2088 if ( $postinsert_callback ) {
2089 my $error = &{$postinsert_callback}($record, $param);
2091 $dbh->rollback if $oldAutoCommit;
2092 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2097 if ( $job && time - $min_sec > $last ) { #progress bar
2098 $job->update_statustext( int(100 * $imported / $count) );
2104 unless ( $imported || $param->{empty_ok} ) {
2105 $dbh->rollback if $oldAutoCommit;
2106 return "Empty file!";
2109 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2116 my( $self, $action, $time ) = @_;
2120 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2123 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2124 real_fields($self->table);
2127 # If we're encrypting then don't store the payinfo in the history
2128 if ( $conf && $conf->exists('encryption') && $self->table ne 'banned_pay' ) {
2129 @fields = grep { $_ ne 'payinfo' } @fields;
2132 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2134 "INSERT INTO h_". $self->table. " ( ".
2135 join(', ', qw(history_date history_user history_action), @fields ).
2137 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
2144 B<Warning>: External use is B<deprecated>.
2146 Replaces COLUMN in record with a unique number, using counters in the
2147 filesystem. Used by the B<insert> method on single-field unique columns
2148 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2149 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2151 Returns the new value.
2156 my($self,$field) = @_;
2157 my($table)=$self->table;
2159 croak "Unique called on field $field, but it is ",
2160 $self->getfield($field),
2162 if $self->getfield($field);
2164 #warn "table $table is tainted" if is_tainted($table);
2165 #warn "field $field is tainted" if is_tainted($field);
2167 my($counter) = new File::CounterFile "$table.$field",0;
2169 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2171 # my($counter) = new File::CounterFile "$user/$table.$field",0;
2174 my $index = $counter->inc;
2175 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2177 $index =~ /^(\d*)$/;
2180 $self->setfield($field,$index);
2184 =item ut_float COLUMN
2186 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2187 null. If there is an error, returns the error, otherwise returns false.
2192 my($self,$field)=@_ ;
2193 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2194 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2195 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2196 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2197 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2198 $self->setfield($field,$1);
2201 =item ut_floatn COLUMN
2203 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2204 null. If there is an error, returns the error, otherwise returns false.
2208 #false laziness w/ut_ipn
2210 my( $self, $field ) = @_;
2211 if ( $self->getfield($field) =~ /^()$/ ) {
2212 $self->setfield($field,'');
2215 $self->ut_float($field);
2219 =item ut_sfloat COLUMN
2221 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2222 May not be null. If there is an error, returns the error, otherwise returns
2228 my($self,$field)=@_ ;
2229 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2230 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2231 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2232 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2233 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2234 $self->setfield($field,$1);
2237 =item ut_sfloatn COLUMN
2239 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2240 null. If there is an error, returns the error, otherwise returns false.
2245 my( $self, $field ) = @_;
2246 if ( $self->getfield($field) =~ /^()$/ ) {
2247 $self->setfield($field,'');
2250 $self->ut_sfloat($field);
2254 =item ut_snumber COLUMN
2256 Check/untaint signed numeric data (whole numbers). If there is an error,
2257 returns the error, otherwise returns false.
2262 my($self, $field) = @_;
2263 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2264 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2265 $self->setfield($field, "$1$2");
2269 =item ut_snumbern COLUMN
2271 Check/untaint signed numeric data (whole numbers). If there is an error,
2272 returns the error, otherwise returns false.
2277 my($self, $field) = @_;
2278 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2279 or return "Illegal (numeric) $field: ". $self->getfield($field);
2281 return "Illegal (numeric) $field: ". $self->getfield($field)
2284 $self->setfield($field, "$1$2");
2288 =item ut_number COLUMN
2290 Check/untaint simple numeric data (whole numbers). May not be null. If there
2291 is an error, returns the error, otherwise returns false.
2296 my($self,$field)=@_;
2297 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2298 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2299 $self->setfield($field,$1);
2303 =item ut_numbern COLUMN
2305 Check/untaint simple numeric data (whole numbers). May be null. If there is
2306 an error, returns the error, otherwise returns false.
2311 my($self,$field)=@_;
2312 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2313 or return "Illegal (numeric) $field: ". $self->getfield($field);
2314 $self->setfield($field,$1);
2318 =item ut_decimal COLUMN[, DIGITS]
2320 Check/untaint decimal numbers (up to DIGITS decimal places. If there is an
2321 error, returns the error, otherwise returns false.
2323 =item ut_decimaln COLUMN[, DIGITS]
2325 Check/untaint decimal numbers. May be null. If there is an error, returns
2326 the error, otherwise returns false.
2331 my($self, $field, $digits) = @_;
2333 $self->getfield($field) =~ /^\s*(\d+(\.\d{0,$digits})?)\s*$/
2334 or return "Illegal or empty (decimal) $field: ".$self->getfield($field);
2335 $self->setfield($field, $1);
2340 my($self, $field, $digits) = @_;
2341 $self->getfield($field) =~ /^\s*(\d*(\.\d{0,$digits})?)\s*$/
2342 or return "Illegal (decimal) $field: ".$self->getfield($field);
2343 $self->setfield($field, $1);
2347 =item ut_money COLUMN
2349 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2350 is an error, returns the error, otherwise returns false.
2355 my($self,$field)=@_;
2357 if ( $self->getfield($field) eq '' ) {
2358 $self->setfield($field, 0);
2359 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2360 #handle one decimal place without barfing out
2361 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2362 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2363 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2365 return "Illegal (money) $field: ". $self->getfield($field);
2371 =item ut_moneyn COLUMN
2373 Check/untaint monetary numbers. May be negative. If there
2374 is an error, returns the error, otherwise returns false.
2379 my($self,$field)=@_;
2380 if ($self->getfield($field) eq '') {
2381 $self->setfield($field, '');
2384 $self->ut_money($field);
2387 =item ut_text COLUMN
2389 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2390 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2391 May not be null. If there is an error, returns the error, otherwise returns
2397 my($self,$field)=@_;
2398 #warn "msgcat ". \&msgcat. "\n";
2399 #warn "notexist ". \¬exist. "\n";
2400 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2401 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2402 # see perldoc perluniprops
2403 $self->getfield($field)
2404 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2405 or return gettext('illegal_or_empty_text'). " $field: ".
2406 $self->getfield($field);
2407 $self->setfield($field,$1);
2411 =item ut_textn COLUMN
2413 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2414 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2415 May be null. If there is an error, returns the error, otherwise returns false.
2420 my($self,$field)=@_;
2421 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2422 $self->ut_text($field);
2425 =item ut_alpha COLUMN
2427 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2428 an error, returns the error, otherwise returns false.
2433 my($self,$field)=@_;
2434 $self->getfield($field) =~ /^(\w+)$/
2435 or return "Illegal or empty (alphanumeric) $field: ".
2436 $self->getfield($field);
2437 $self->setfield($field,$1);
2441 =item ut_alphan COLUMN
2443 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2444 error, returns the error, otherwise returns false.
2449 my($self,$field)=@_;
2450 $self->getfield($field) =~ /^(\w*)$/
2451 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2452 $self->setfield($field,$1);
2456 =item ut_alphasn COLUMN
2458 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2459 an error, returns the error, otherwise returns false.
2464 my($self,$field)=@_;
2465 $self->getfield($field) =~ /^([\w ]*)$/
2466 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2467 $self->setfield($field,$1);
2472 =item ut_alpha_lower COLUMN
2474 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2475 there is an error, returns the error, otherwise returns false.
2479 sub ut_alpha_lower {
2480 my($self,$field)=@_;
2481 $self->getfield($field) =~ /[[:upper:]]/
2482 and return "Uppercase characters are not permitted in $field";
2483 $self->ut_alpha($field);
2486 =item ut_phonen COLUMN [ COUNTRY ]
2488 Check/untaint phone numbers. May be null. If there is an error, returns
2489 the error, otherwise returns false.
2491 Takes an optional two-letter ISO 3166-1 alpha-2 country code; without
2492 it or with unsupported countries, ut_phonen simply calls ut_alphan.
2497 my( $self, $field, $country ) = @_;
2498 return $self->ut_alphan($field) unless defined $country;
2499 my $phonen = $self->getfield($field);
2500 if ( $phonen eq '' ) {
2501 $self->setfield($field,'');
2502 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2504 $phonen = $conf->config('cust_main-default_areacode').$phonen
2505 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2506 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2507 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2508 $phonen = "$1-$2-$3";
2509 $phonen .= " x$4" if $4;
2510 $self->setfield($field,$phonen);
2512 warn "warning: don't know how to check phone numbers for country $country";
2513 return $self->ut_textn($field);
2520 Check/untaint hexadecimal values.
2525 my($self, $field) = @_;
2526 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2527 or return "Illegal (hex) $field: ". $self->getfield($field);
2528 $self->setfield($field, uc($1));
2532 =item ut_hexn COLUMN
2534 Check/untaint hexadecimal values. May be null.
2539 my($self, $field) = @_;
2540 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2541 or return "Illegal (hex) $field: ". $self->getfield($field);
2542 $self->setfield($field, uc($1));
2546 =item ut_mac_addr COLUMN
2548 Check/untaint mac addresses. May be null.
2553 my($self, $field) = @_;
2555 my $mac = $self->get($field);
2558 $self->set($field, $mac);
2560 my $e = $self->ut_hex($field);
2563 return "Illegal (mac address) $field: ". $self->getfield($field)
2564 unless length($self->getfield($field)) == 12;
2570 =item ut_mac_addrn COLUMN
2572 Check/untaint mac addresses. May be null.
2577 my($self, $field) = @_;
2578 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2583 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2589 my( $self, $field ) = @_;
2590 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2591 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2592 or return "Illegal (IP address) $field: ". $self->getfield($field);
2593 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2594 $self->setfield($field, "$1.$2.$3.$4");
2600 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2601 to 127.0.0.1. May be null.
2606 my( $self, $field ) = @_;
2607 if ( $self->getfield($field) =~ /^()$/ ) {
2608 $self->setfield($field,'');
2611 $self->ut_ip($field);
2615 =item ut_ip46 COLUMN
2617 Check/untaint IPv4 or IPv6 address.
2622 my( $self, $field ) = @_;
2623 my $ip = NetAddr::IP->new($self->getfield($field))
2624 or return "Illegal (IP address) $field: ".$self->getfield($field);
2625 $self->setfield($field, lc($ip->addr));
2631 Check/untaint IPv6 or IPv6 address. May be null.
2636 my( $self, $field ) = @_;
2637 if ( $self->getfield($field) =~ /^$/ ) {
2638 $self->setfield($field, '');
2641 $self->ut_ip46($field);
2644 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2646 Check/untaint coordinates.
2647 Accepts the following forms:
2657 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2658 The latter form (that is, the MMM are thousands of minutes) is
2659 assumed if the "MMM" is exactly three digits or two digits > 59.
2661 To be safe, just use the DDD.DDDDD form.
2663 If LOWER or UPPER are specified, then the coordinate is checked
2664 for lower and upper bounds, respectively.
2669 my ($self, $field) = (shift, shift);
2672 if ( $field =~ /latitude/ ) {
2673 $lower = $lat_lower;
2675 } elsif ( $field =~ /longitude/ ) {
2677 $upper = $lon_upper;
2680 my $coord = $self->getfield($field);
2681 my $neg = $coord =~ s/^(-)//;
2683 my ($d, $m, $s) = (0, 0, 0);
2686 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2687 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2688 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2690 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2693 return "Invalid (coordinate with minutes > 59) $field: "
2694 . $self->getfield($field);
2697 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2699 if (defined($lower) and ($coord < $lower)) {
2700 return "Invalid (coordinate < $lower) $field: "
2701 . $self->getfield($field);;
2704 if (defined($upper) and ($coord > $upper)) {
2705 return "Invalid (coordinate > $upper) $field: "
2706 . $self->getfield($field);;
2709 $self->setfield($field, $coord);
2713 return "Invalid (coordinate) $field: " . $self->getfield($field);
2717 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2719 Same as ut_coord, except optionally null.
2725 my ($self, $field) = (shift, shift);
2727 if ($self->getfield($field) =~ /^\s*$/) {
2730 return $self->ut_coord($field, @_);
2735 =item ut_domain COLUMN
2737 Check/untaint host and domain names. May not be null.
2742 my( $self, $field ) = @_;
2743 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2744 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2745 or return "Illegal (hostname) $field: ". $self->getfield($field);
2746 $self->setfield($field,$1);
2750 =item ut_domainn COLUMN
2752 Check/untaint host and domain names. May be null.
2757 my( $self, $field ) = @_;
2758 if ( $self->getfield($field) =~ /^()$/ ) {
2759 $self->setfield($field,'');
2762 $self->ut_domain($field);
2766 =item ut_name COLUMN
2768 Check/untaint proper names; allows alphanumerics, spaces and the following
2769 punctuation: , . - '
2776 my( $self, $field ) = @_;
2777 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2778 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
2779 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2784 $self->setfield($field, $name);
2788 =item ut_namen COLUMN
2790 Check/untaint proper names; allows alphanumerics, spaces and the following
2791 punctuation: , . - '
2798 my( $self, $field ) = @_;
2799 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2800 $self->ut_name($field);
2805 Check/untaint zip codes.
2809 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2812 my( $self, $field, $country ) = @_;
2814 if ( $country eq 'US' ) {
2816 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2817 or return gettext('illegal_zip'). " $field for country $country: ".
2818 $self->getfield($field);
2819 $self->setfield($field, $1);
2821 } elsif ( $country eq 'CA' ) {
2823 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2824 or return gettext('illegal_zip'). " $field for country $country: ".
2825 $self->getfield($field);
2826 $self->setfield($field, "$1 $2");
2830 if ( $self->getfield($field) =~ /^\s*$/
2831 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2834 $self->setfield($field,'');
2836 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2837 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2838 $self->setfield($field,$1);
2846 =item ut_country COLUMN
2848 Check/untaint country codes. Country names are changed to codes, if possible -
2849 see L<Locale::Country>.
2854 my( $self, $field ) = @_;
2855 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2856 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2857 && country2code($1) ) {
2858 $self->setfield($field,uc(country2code($1)));
2861 $self->getfield($field) =~ /^(\w\w)$/
2862 or return "Illegal (country) $field: ". $self->getfield($field);
2863 $self->setfield($field,uc($1));
2867 =item ut_anything COLUMN
2869 Untaints arbitrary data. Be careful.
2874 my( $self, $field ) = @_;
2875 $self->getfield($field) =~ /^(.*)$/s
2876 or return "Illegal $field: ". $self->getfield($field);
2877 $self->setfield($field,$1);
2881 =item ut_enum COLUMN CHOICES_ARRAYREF
2883 Check/untaint a column, supplying all possible choices, like the "enum" type.
2888 my( $self, $field, $choices ) = @_;
2889 foreach my $choice ( @$choices ) {
2890 if ( $self->getfield($field) eq $choice ) {
2891 $self->setfield($field, $choice);
2895 return "Illegal (enum) field $field: ". $self->getfield($field);
2898 =item ut_enumn COLUMN CHOICES_ARRAYREF
2900 Like ut_enum, except the null value is also allowed.
2905 my( $self, $field, $choices ) = @_;
2906 $self->getfield($field)
2907 ? $self->ut_enum($field, $choices)
2911 =item ut_flag COLUMN
2913 Check/untaint a column if it contains either an empty string or 'Y'. This
2914 is the standard form for boolean flags in Freeside.
2919 my( $self, $field ) = @_;
2920 my $value = uc($self->getfield($field));
2921 if ( $value eq '' or $value eq 'Y' ) {
2922 $self->setfield($field, $value);
2925 return "Illegal (flag) field $field: $value";
2928 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2930 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2931 on the column first.
2935 sub ut_foreign_key {
2936 my( $self, $field, $table, $foreign ) = @_;
2937 return '' if $no_check_foreign;
2938 qsearchs($table, { $foreign => $self->getfield($field) })
2939 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2940 " in $table.$foreign";
2944 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2946 Like ut_foreign_key, except the null value is also allowed.
2950 sub ut_foreign_keyn {
2951 my( $self, $field, $table, $foreign ) = @_;
2952 $self->getfield($field)
2953 ? $self->ut_foreign_key($field, $table, $foreign)
2957 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2959 Checks this column as an agentnum, taking into account the current users's
2960 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2961 right or rights allowing no agentnum.
2965 sub ut_agentnum_acl {
2966 my( $self, $field ) = (shift, shift);
2967 my $null_acl = scalar(@_) ? shift : [];
2968 $null_acl = [ $null_acl ] unless ref($null_acl);
2970 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2971 return "Illegal agentnum: $error" if $error;
2973 my $curuser = $FS::CurrentUser::CurrentUser;
2975 if ( $self->$field() ) {
2977 return "Access denied"
2978 unless $curuser->agentnum($self->$field());
2982 return "Access denied"
2983 unless grep $curuser->access_right($_), @$null_acl;
2991 =item fields [ TABLE ]
2993 This is a wrapper for real_fields. Code that called
2994 fields before should probably continue to call fields.
2999 my $something = shift;
3001 if($something->isa('FS::Record')) {
3002 $table = $something->table;
3004 $table = $something;
3005 $something = "FS::$table";
3007 return (real_fields($table));
3011 =item encrypt($value)
3013 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
3015 Returns the encrypted string.
3017 You should generally not have to worry about calling this, as the system handles this for you.
3022 my ($self, $value) = @_;
3023 my $encrypted = $value;
3025 if ($conf->exists('encryption')) {
3026 if ($self->is_encrypted($value)) {
3027 # Return the original value if it isn't plaintext.
3028 $encrypted = $value;
3031 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3032 # RSA doesn't like the empty string so let's pack it up
3033 # The database doesn't like the RSA data so uuencode it
3034 my $length = length($value)+1;
3035 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3037 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3044 =item is_encrypted($value)
3046 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3052 my ($self, $value) = @_;
3053 # Possible Bug - Some work may be required here....
3055 if ($value =~ /^M/ && length($value) > 80) {
3062 =item decrypt($value)
3064 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3066 You should generally not have to worry about calling this, as the system handles this for you.
3071 my ($self,$value) = @_;
3072 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3073 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
3075 if (ref($rsa_decrypt) =~ /::RSA/) {
3076 my $encrypted = unpack ("u*", $value);
3077 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3078 if ($@) {warn "Decryption Failed"};
3086 #Initialize the Module
3087 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3089 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
3090 $rsa_module = $conf->config('encryptionmodule');
3094 eval ("require $rsa_module"); # No need to import the namespace
3097 # Initialize Encryption
3098 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
3099 my $public_key = join("\n",$conf->config('encryptionpublickey'));
3100 $rsa_encrypt = $rsa_module->new_public_key($public_key);
3103 # Intitalize Decryption
3104 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
3105 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
3106 $rsa_decrypt = $rsa_module->new_private_key($private_key);
3110 =item h_search ACTION
3112 Given an ACTION, either "insert", or "delete", returns the appropriate history
3113 record corresponding to this record, if any.
3118 my( $self, $action ) = @_;
3120 my $table = $self->table;
3123 my $primary_key = dbdef->table($table)->primary_key;
3126 'table' => "h_$table",
3127 'hashref' => { $primary_key => $self->$primary_key(),
3128 'history_action' => $action,
3136 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3137 appropriate history record corresponding to this record, if any.
3142 my($self, $action) = @_;
3143 my $h = $self->h_search($action);
3144 $h ? $h->history_date : '';
3147 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3149 A class or object method. Executes the sql statement represented by SQL and
3150 returns a scalar representing the result: the first column of the first row.
3152 Dies on bogus SQL. Returns an empty string if no row is returned.
3154 Typically used for statments which return a single value such as "SELECT
3155 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3160 my($self, $sql) = (shift, shift);
3161 my $sth = dbh->prepare($sql) or die dbh->errstr;
3163 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3164 my $row = $sth->fetchrow_arrayref or return '';
3165 my $scalar = $row->[0];
3166 defined($scalar) ? $scalar : '';
3169 =item count [ WHERE [, PLACEHOLDER ...] ]
3171 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3172 with optional WHERE. Must be called as method on a class with an
3178 my($self, $where) = (shift, shift);
3179 my $table = $self->table or die 'count called on object of class '.ref($self);
3180 my $sql = "SELECT COUNT(*) FROM $table";
3181 $sql .= " WHERE $where" if $where;
3182 $self->scalar_sql($sql, @_);
3191 =item real_fields [ TABLE ]
3193 Returns a list of the real columns in the specified table. Called only by
3194 fields() and other subroutines elsewhere in FS::Record.
3201 my($table_obj) = dbdef->table($table);
3202 confess "Unknown table $table" unless $table_obj;
3203 $table_obj->columns;
3206 =item pvf FIELD_NAME
3208 Returns the FS::part_virtual_field object corresponding to a field in the
3209 record (specified by FIELD_NAME).
3214 my ($self, $name) = (shift, shift);
3216 if(grep /^$name$/, $self->virtual_fields) {
3218 my $concat = [ "'cf_'", "name" ];
3219 return qsearchs({ table => 'part_virtual_field',
3220 hashref => { dbtable => $self->table,
3223 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3229 =item _quote VALUE, TABLE, COLUMN
3231 This is an internal function used to construct SQL statements. It returns
3232 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3233 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3238 my($value, $table, $column) = @_;
3239 my $column_obj = dbdef->table($table)->column($column);
3240 my $column_type = $column_obj->type;
3241 my $nullable = $column_obj->null;
3243 utf8::upgrade($value);
3245 warn " $table.$column: $value ($column_type".
3246 ( $nullable ? ' NULL' : ' NOT NULL' ).
3247 ")\n" if $DEBUG > 2;
3249 if ( $value eq '' && $nullable ) {
3251 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3252 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3255 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3256 ! $column_type =~ /(char|binary|text)$/i ) {
3258 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3259 && driver_name eq 'Pg'
3263 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3264 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3265 # single-quote the whole mess, and put an "E" in front.
3266 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3274 This is deprecated. Don't use it.
3276 It returns a hash-type list with the fields of this record's table set true.
3281 carp "warning: hfields is deprecated";
3284 foreach (fields($table)) {
3293 "$_: ". $self->getfield($_). "|"
3294 } (fields($self->table)) );
3297 sub DESTROY { return; }
3301 # #use Carp qw(cluck);
3302 # #cluck "DESTROYING $self";
3303 # warn "DESTROYING $self";
3307 # return ! eval { join('',@_), kill 0; 1; };
3310 =item str2time_sql [ DRIVER_NAME ]
3312 Returns a function to convert to unix time based on database type, such as
3313 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3314 the str2time_sql_closing method to return a closing string rather than just
3315 using a closing parenthesis as previously suggested.
3317 You can pass an optional driver name such as "Pg", "mysql" or
3318 $dbh->{Driver}->{Name} to return a function for that database instead of
3319 the current database.
3324 my $driver = shift || driver_name;
3326 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3327 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3329 warn "warning: unknown database type $driver; guessing how to convert ".
3330 "dates to UNIX timestamps";
3331 return 'EXTRACT(EPOCH FROM ';
3335 =item str2time_sql_closing [ DRIVER_NAME ]
3337 Returns the closing suffix of a function to convert to unix time based on
3338 database type, such as ")::integer" for Pg or ")" for mysql.
3340 You can pass an optional driver name such as "Pg", "mysql" or
3341 $dbh->{Driver}->{Name} to return a function for that database instead of
3342 the current database.
3346 sub str2time_sql_closing {
3347 my $driver = shift || driver_name;
3349 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3353 =item regexp_sql [ DRIVER_NAME ]
3355 Returns the operator to do a regular expression comparison based on database
3356 type, such as '~' for Pg or 'REGEXP' for mysql.
3358 You can pass an optional driver name such as "Pg", "mysql" or
3359 $dbh->{Driver}->{Name} to return a function for that database instead of
3360 the current database.
3365 my $driver = shift || driver_name;
3367 return '~' if $driver =~ /^Pg/i;
3368 return 'REGEXP' if $driver =~ /^mysql/i;
3370 die "don't know how to use regular expressions in ". driver_name." databases";
3374 =item not_regexp_sql [ DRIVER_NAME ]
3376 Returns the operator to do a regular expression negation based on database
3377 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3379 You can pass an optional driver name such as "Pg", "mysql" or
3380 $dbh->{Driver}->{Name} to return a function for that database instead of
3381 the current database.
3385 sub not_regexp_sql {
3386 my $driver = shift || driver_name;
3388 return '!~' if $driver =~ /^Pg/i;
3389 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3391 die "don't know how to use regular expressions in ". driver_name." databases";
3395 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3397 Returns the items concatenated based on database type, using "CONCAT()" for
3398 mysql and " || " for Pg and other databases.
3400 You can pass an optional driver name such as "Pg", "mysql" or
3401 $dbh->{Driver}->{Name} to return a function for that database instead of
3402 the current database.
3407 my $driver = ref($_[0]) ? driver_name : shift;
3410 if ( $driver =~ /^mysql/i ) {
3411 'CONCAT('. join(',', @$items). ')';
3413 join('||', @$items);
3418 =item group_concat_sql COLUMN, DELIMITER
3420 Returns an SQL expression to concatenate an aggregate column, using
3421 GROUP_CONCAT() for mysql and array_to_string() and array_agg() for Pg.
3425 sub group_concat_sql {
3426 my ($col, $delim) = @_;
3427 $delim = dbh->quote($delim);
3428 if ( driver_name() =~ /^mysql/i ) {
3429 # DISTINCT(foo) is valid as $col
3430 return "GROUP_CONCAT($col SEPARATOR $delim)";
3432 return "array_to_string(array_agg($col), $delim)";
3436 =item midnight_sql DATE
3438 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3439 on that day in the system timezone, using the default driver name.
3444 my $driver = driver_name;
3446 if ( $driver =~ /^mysql/i ) {
3447 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3450 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3458 This module should probably be renamed, since much of the functionality is
3459 of general use. It is not completely unlike Adapter::DBI (see below).
3461 Exported qsearch and qsearchs should be deprecated in favor of method calls
3462 (against an FS::Record object like the old search and searchs that qsearch
3463 and qsearchs were on top of.)
3465 The whole fields / hfields mess should be removed.
3467 The various WHERE clauses should be subroutined.
3469 table string should be deprecated in favor of DBIx::DBSchema::Table.
3471 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3472 true maps to the database (and WHERE clauses) would also help.
3474 The ut_ methods should ask the dbdef for a default length.
3476 ut_sqltype (like ut_varchar) should all be defined
3478 A fallback check method should be provided which uses the dbdef.
3480 The ut_money method assumes money has two decimal digits.
3482 The Pg money kludge in the new method only strips `$'.
3484 The ut_phonen method only checks US-style phone numbers.
3486 The _quote function should probably use ut_float instead of a regex.
3488 All the subroutines probably should be methods, here or elsewhere.
3490 Probably should borrow/use some dbdef methods where appropriate (like sub
3493 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3494 or allow it to be set. Working around it is ugly any way around - DBI should
3495 be fixed. (only affects RDBMS which return uppercase column names)
3497 ut_zip should take an optional country like ut_phone.
3501 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3503 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.