4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 $money_char $lat_lower $lon_upper
8 $nowarn_identical $nowarn_classload
9 $no_update_diff $no_history $qsearch_qualify_columns
14 use Carp qw(carp cluck croak confess);
15 use Scalar::Util qw( blessed );
16 use File::CounterFile;
19 use File::Slurp qw( slurp );
20 use DBI qw(:sql_types);
21 use DBIx::DBSchema 0.38;
22 use FS::UID qw(dbh getotaker datasrc driver_name);
24 use FS::Schema qw(dbdef);
26 use FS::Msgcat qw(gettext);
27 use NetAddr::IP; # for validation
29 #use FS::Conf; #dependency loop bs, in install_callback below instead
31 use FS::part_virtual_field;
37 @encrypt_payby = qw( CARD DCRD CHEK DCHK );
39 #export dbdef for now... everything else expects to find it here
41 dbh fields hfields qsearch qsearchs dbdef jsearch
42 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql
43 concat_sql group_concat_sql
50 $nowarn_identical = 0;
51 $nowarn_classload = 0;
55 $qsearch_qualify_columns = 0;
57 $no_check_foreign = 0;
65 our $conf_encryption = '';
66 our $conf_encryptionmodule = '';
67 our $conf_encryptionpublickey = '';
68 our $conf_encryptionprivatekey = '';
69 FS::UID->install_callback( sub {
73 $conf = FS::Conf->new;
74 $conf_encryption = $conf->exists('encryption');
75 $conf_encryptionmodule = $conf->config('encryptionmodule');
76 $conf_encryptionpublickey = join("\n",$conf->config('encryptionpublickey'));
77 $conf_encryptionprivatekey = join("\n",$conf->config('encryptionprivatekey'));
78 $money_char = $conf->config('money_char') || '$';
79 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
80 $lat_lower = $nw_coords ? 1 : -90;
81 $lon_upper = $nw_coords ? -1 : 180;
83 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
85 if ( driver_name eq 'Pg' ) {
86 eval "use DBD::Pg ':pg_types'";
89 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
96 FS::Record - Database record objects
101 use FS::Record qw(dbh fields qsearch qsearchs);
103 $record = new FS::Record 'table', \%hash;
104 $record = new FS::Record 'table', { 'column' => 'value', ... };
106 $record = qsearchs FS::Record 'table', \%hash;
107 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
108 @records = qsearch FS::Record 'table', \%hash;
109 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
111 $table = $record->table;
112 $dbdef_table = $record->dbdef_table;
114 $value = $record->get('column');
115 $value = $record->getfield('column');
116 $value = $record->column;
118 $record->set( 'column' => 'value' );
119 $record->setfield( 'column' => 'value' );
120 $record->column('value');
122 %hash = $record->hash;
124 $hashref = $record->hashref;
126 $error = $record->insert;
128 $error = $record->delete;
130 $error = $new_record->replace($old_record);
132 # external use deprecated - handled by the database (at least for Pg, mysql)
133 $value = $record->unique('column');
135 $error = $record->ut_float('column');
136 $error = $record->ut_floatn('column');
137 $error = $record->ut_number('column');
138 $error = $record->ut_numbern('column');
139 $error = $record->ut_decimal('column');
140 $error = $record->ut_decimaln('column');
141 $error = $record->ut_snumber('column');
142 $error = $record->ut_snumbern('column');
143 $error = $record->ut_money('column');
144 $error = $record->ut_text('column');
145 $error = $record->ut_textn('column');
146 $error = $record->ut_alpha('column');
147 $error = $record->ut_alphan('column');
148 $error = $record->ut_phonen('column');
149 $error = $record->ut_anything('column');
150 $error = $record->ut_name('column');
152 $quoted_value = _quote($value,'table','field');
155 $fields = hfields('table');
156 if ( $fields->{Field} ) { # etc.
158 @fields = fields 'table'; #as a subroutine
159 @fields = $record->fields; #as a method call
164 (Mostly) object-oriented interface to database records. Records are currently
165 implemented on top of DBI. FS::Record is intended as a base class for
166 table-specific classes to inherit from, i.e. FS::cust_main.
172 =item new [ TABLE, ] HASHREF
174 Creates a new record. It doesn't store it in the database, though. See
175 L<"insert"> for that.
177 Note that the object stores this hash reference, not a distinct copy of the
178 hash it points to. You can ask the object for a copy with the I<hash>
181 TABLE can only be omitted when a dervived class overrides the table method.
187 my $class = ref($proto) || $proto;
189 bless ($self, $class);
191 unless ( defined ( $self->table ) ) {
192 $self->{'Table'} = shift;
193 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
194 unless $nowarn_classload;
197 $self->{'Hash'} = shift;
199 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
200 $self->{'Hash'}{$field}='';
203 $self->_rebless if $self->can('_rebless');
205 $self->{'modified'} = 0;
207 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
214 my $class = ref($proto) || $proto;
216 bless ($self, $class);
218 $self->{'Table'} = shift unless defined ( $self->table );
220 my $hashref = $self->{'Hash'} = shift;
222 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
223 my $obj = $cache->cache->{$hashref->{$cache->key}};
224 $obj->_cache($hashref, $cache) if $obj->can('_cache');
227 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
234 my $class = ref($proto) || $proto;
236 bless ($self, $class);
237 if ( defined $self->table ) {
238 cluck "create constructor is deprecated, use new!";
241 croak "FS::Record::create called (not from a subclass)!";
245 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
247 Searches the database for all records matching (at least) the key/value pairs
248 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
249 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
252 The preferred usage is to pass a hash reference of named parameters:
254 @records = qsearch( {
255 'table' => 'table_name',
256 'hashref' => { 'field' => 'value'
257 'field' => { 'op' => '<',
262 #these are optional...
264 'extra_sql' => 'AND field = ? AND intfield = ?',
265 'extra_param' => [ 'value', [ 5, 'int' ] ],
266 'order_by' => 'ORDER BY something',
267 #'cache_obj' => '', #optional
268 'addl_from' => 'LEFT JOIN othtable USING ( field )',
273 Much code still uses old-style positional parameters, this is also probably
274 fine in the common case where there are only two parameters:
276 my @records = qsearch( 'table', { 'field' => 'value' } );
278 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
279 the individual PARAMS_HASHREF queries
281 ###oops, argh, FS::Record::new only lets us create database fields.
282 #Normal behaviour if SELECT is not specified is `*', as in
283 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
284 #feature where you can specify SELECT - remember, the objects returned,
285 #although blessed into the appropriate `FS::TABLE' package, will only have the
286 #fields you specify. This might have unwanted results if you then go calling
287 #regular FS::TABLE methods
292 my %TYPE = (); #for debugging
295 my($type, $value) = @_;
297 my $bind_type = { TYPE => SQL_VARCHAR };
299 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
301 $bind_type = { TYPE => SQL_INTEGER };
303 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
305 if ( driver_name eq 'Pg' ) {
307 $bind_type = { pg_type => PG_BYTEA };
309 # $bind_type = ? #SQL_VARCHAR could be fine?
312 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
313 #fixed by DBD::Pg 2.11.8
314 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
315 #(make a Tron test first)
316 } elsif ( _is_fs_float( $type, $value ) ) {
318 $bind_type = { TYPE => SQL_DECIMAL };
327 my($type, $value) = @_;
328 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
329 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
337 my( @stable, @record, @cache );
338 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
340 my %union_options = ();
341 if ( ref($_[0]) eq 'ARRAY' ) {
344 foreach my $href ( @$optlist ) {
345 push @stable, ( $href->{'table'} or die "table name is required" );
346 push @record, ( $href->{'hashref'} || {} );
347 push @select, ( $href->{'select'} || '*' );
348 push @extra_sql, ( $href->{'extra_sql'} || '' );
349 push @extra_param, ( $href->{'extra_param'} || [] );
350 push @order_by, ( $href->{'order_by'} || '' );
351 push @cache, ( $href->{'cache_obj'} || '' );
352 push @addl_from, ( $href->{'addl_from'} || '' );
353 push @debug, ( $href->{'debug'} || '' );
355 die "at least one hashref is required" unless scalar(@stable);
356 } elsif ( ref($_[0]) eq 'HASH' ) {
358 $stable[0] = $opt->{'table'} or die "table name is required";
359 $record[0] = $opt->{'hashref'} || {};
360 $select[0] = $opt->{'select'} || '*';
361 $extra_sql[0] = $opt->{'extra_sql'} || '';
362 $extra_param[0] = $opt->{'extra_param'} || [];
363 $order_by[0] = $opt->{'order_by'} || '';
364 $cache[0] = $opt->{'cache_obj'} || '';
365 $addl_from[0] = $opt->{'addl_from'} || '';
366 $debug[0] = $opt->{'debug'} || '';
377 my $cache = $cache[0];
383 foreach my $stable ( @stable ) {
384 #stop altering the caller's hashref
385 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
386 my $select = shift @select;
387 my $extra_sql = shift @extra_sql;
388 my $extra_param = shift @extra_param;
389 my $order_by = shift @order_by;
390 my $cache = shift @cache;
391 my $addl_from = shift @addl_from;
392 my $debug = shift @debug;
394 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
396 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
399 my $table = $cache ? $cache->table : $stable;
400 my $dbdef_table = dbdef->table($table)
401 or die "No schema for table $table found - ".
402 "do you need to run freeside-upgrade?";
403 my $pkey = $dbdef_table->primary_key;
405 my @real_fields = grep exists($record->{$_}), real_fields($table);
407 my $statement .= "SELECT $select FROM $stable";
408 $statement .= " $addl_from" if $addl_from;
409 if ( @real_fields ) {
410 $statement .= ' WHERE '. join(' AND ',
411 get_real_fields($table, $record, \@real_fields));
414 $statement .= " $extra_sql" if defined($extra_sql);
415 $statement .= " $order_by" if defined($order_by);
417 push @statement, $statement;
419 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
423 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
426 my $value = $record->{$field};
427 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
428 $value = $value->{'value'} if ref($value);
429 my $type = dbdef->table($table)->column($field)->type;
431 my $bind_type = _bind_type($type, $value);
435 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
437 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
441 push @bind_type, $bind_type;
445 foreach my $param ( @$extra_param ) {
446 my $bind_type = { TYPE => SQL_VARCHAR };
449 $value = $param->[0];
450 my $type = $param->[1];
451 $bind_type = _bind_type($type, $value);
454 push @bind_type, $bind_type;
458 my $statement = join( ' ) UNION ( ', @statement );
459 $statement = "( $statement )" if scalar(@statement) > 1;
460 $statement .= " $union_options{order_by}" if $union_options{order_by};
462 my $sth = $dbh->prepare($statement)
463 or croak "$dbh->errstr doing $statement";
466 foreach my $value ( @value ) {
467 my $bind_type = shift @bind_type;
468 $sth->bind_param($bind++, $value, $bind_type );
471 # $sth->execute( map $record->{$_},
472 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
473 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
475 my $ok = $sth->execute;
477 my $error = "Error executing \"$statement\"";
478 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
479 $error .= ': '. $sth->errstr;
483 my $table = $stable[0];
485 $table = '' if grep { $_ ne $table } @stable;
486 $pkey = dbdef->table($table)->primary_key if $table;
489 tie %result, "Tie::IxHash";
490 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
491 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
492 %result = map { $_->{$pkey}, $_ } @stuff;
494 @result{@stuff} = @stuff;
500 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
501 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
502 #derivied class didn't override new method, so this optimization is safe
505 new_or_cached( "FS::$table", { %{$_} }, $cache )
509 new( "FS::$table", { %{$_} } )
513 #okay, its been tested
514 # warn "untested code (class FS::$table uses custom new method)";
516 eval 'FS::'. $table. '->new( { %{$_} } )';
520 # Check for encrypted fields and decrypt them.
521 ## only in the local copy, not the cached object
522 if ( $conf_encryption
523 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
524 foreach my $record (@return) {
525 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
526 next if $field eq 'payinfo'
527 && ($record->isa('FS::payinfo_transaction_Mixin')
528 || $record->isa('FS::payinfo_Mixin') )
530 && !grep { $record->payby eq $_ } @encrypt_payby;
531 # Set it directly... This may cause a problem in the future...
532 $record->setfield($field, $record->decrypt($record->getfield($field)));
537 cluck "warning: FS::$table not loaded; returning FS::Record objects"
538 unless $nowarn_classload;
540 FS::Record->new( $table, { %{$_} } );
548 Construct the SQL statement and parameter-binding list for qsearch. Takes
549 the qsearch parameters.
551 Returns a hash containing:
552 'table': The primary table name (if there is one).
553 'statement': The SQL statement itself.
554 'bind_type': An arrayref of bind types.
555 'value': An arrayref of parameter values.
556 'cache': The cache object, if one was passed.
561 my( @stable, @record, @cache );
562 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
565 my %union_options = ();
566 if ( ref($_[0]) eq 'ARRAY' ) {
569 foreach my $href ( @$optlist ) {
570 push @stable, ( $href->{'table'} or die "table name is required" );
571 push @record, ( $href->{'hashref'} || {} );
572 push @select, ( $href->{'select'} || '*' );
573 push @extra_sql, ( $href->{'extra_sql'} || '' );
574 push @extra_param, ( $href->{'extra_param'} || [] );
575 push @order_by, ( $href->{'order_by'} || '' );
576 push @cache, ( $href->{'cache_obj'} || '' );
577 push @addl_from, ( $href->{'addl_from'} || '' );
578 push @debug, ( $href->{'debug'} || '' );
580 die "at least one hashref is required" unless scalar(@stable);
581 } elsif ( ref($_[0]) eq 'HASH' ) {
583 $stable[0] = $opt->{'table'} or die "table name is required";
584 $record[0] = $opt->{'hashref'} || {};
585 $select[0] = $opt->{'select'} || '*';
586 $extra_sql[0] = $opt->{'extra_sql'} || '';
587 $extra_param[0] = $opt->{'extra_param'} || [];
588 $order_by[0] = $opt->{'order_by'} || '';
589 $cache[0] = $opt->{'cache_obj'} || '';
590 $addl_from[0] = $opt->{'addl_from'} || '';
591 $debug[0] = $opt->{'debug'} || '';
602 my $cache = $cache[0];
608 my $result_table = $stable[0];
609 foreach my $stable ( @stable ) {
610 #stop altering the caller's hashref
611 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
612 my $select = shift @select;
613 my $extra_sql = shift @extra_sql;
614 my $extra_param = shift @extra_param;
615 my $order_by = shift @order_by;
616 my $cache = shift @cache;
617 my $addl_from = shift @addl_from;
618 my $debug = shift @debug;
620 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
622 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
625 $result_table = '' if $result_table ne $stable;
627 my $table = $cache ? $cache->table : $stable;
628 my $dbdef_table = dbdef->table($table)
629 or die "No schema for table $table found - ".
630 "do you need to run freeside-upgrade?";
631 my $pkey = $dbdef_table->primary_key;
633 my @real_fields = grep exists($record->{$_}), real_fields($table);
635 my $statement .= "SELECT $select FROM $stable";
636 $statement .= " $addl_from" if $addl_from;
637 if ( @real_fields ) {
638 $statement .= ' WHERE '. join(' AND ',
639 get_real_fields($table, $record, \@real_fields));
642 $statement .= " $extra_sql" if defined($extra_sql);
643 $statement .= " $order_by" if defined($order_by);
645 push @statement, $statement;
647 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
651 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
654 my $value = $record->{$field};
655 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
656 $value = $value->{'value'} if ref($value);
657 my $type = dbdef->table($table)->column($field)->type;
659 my $bind_type = _bind_type($type, $value);
663 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
665 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
669 push @bind_type, $bind_type;
673 foreach my $param ( @$extra_param ) {
674 my $bind_type = { TYPE => SQL_VARCHAR };
677 $value = $param->[0];
678 my $type = $param->[1];
679 $bind_type = _bind_type($type, $value);
682 push @bind_type, $bind_type;
686 my $statement = join( ' ) UNION ( ', @statement );
687 $statement = "( $statement )" if scalar(@statement) > 1;
688 $statement .= " $union_options{order_by}" if $union_options{order_by};
691 statement => $statement,
692 bind_type => \@bind_type,
694 table => $result_table,
699 # qsearch should eventually use this
701 my ($table, $cache, @hashrefs) = @_;
703 # XXX get rid of these string evals at some point
704 # (when we have time to test it)
705 # my $class = "FS::$table" if $table;
706 # if ( $class and $class->isa('FS::Record') )
707 # if ( $class->can('new') eq \&new )
709 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
710 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
711 #derivied class didn't override new method, so this optimization is safe
714 new_or_cached( "FS::$table", { %{$_} }, $cache )
718 new( "FS::$table", { %{$_} } )
722 #okay, its been tested
723 # warn "untested code (class FS::$table uses custom new method)";
725 eval 'FS::'. $table. '->new( { %{$_} } )';
729 # Check for encrypted fields and decrypt them.
730 ## only in the local copy, not the cached object
731 if ( $conf_encryption
732 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
733 foreach my $record (@return) {
734 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
735 next if $field eq 'payinfo'
736 && ($record->isa('FS::payinfo_transaction_Mixin')
737 || $record->isa('FS::payinfo_Mixin') )
739 && !grep { $record->payby eq $_ } @encrypt_payby;
740 # Set it directly... This may cause a problem in the future...
741 $record->setfield($field, $record->decrypt($record->getfield($field)));
746 cluck "warning: FS::$table not loaded; returning FS::Record objects"
747 unless $nowarn_classload;
749 FS::Record->new( $table, { %{$_} } );
755 sub get_real_fields {
758 my $real_fields = shift;
760 ## could be optimized more for readability
766 my $table_column = $qsearch_qualify_columns ? "$table.$column" : $column;
767 my $type = dbdef->table($table)->column($column)->type;
768 my $value = $record->{$column};
769 $value = $value->{'value'} if ref($value);
771 if ( ref($record->{$column}) ) {
772 $op = $record->{$column}{'op'} if $record->{$column}{'op'};
773 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
774 if ( uc($op) eq 'ILIKE' ) {
776 $record->{$column}{'value'} = lc($record->{$column}{'value'});
777 $table_column = "LOWER($table_column)";
779 $record->{$column} = $record->{$column}{'value'}
782 if ( ! defined( $record->{$column} ) || $record->{$column} eq '' ) {
784 if ( driver_name eq 'Pg' ) {
785 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
786 qq-( $table_column IS NULL )-;
788 qq-( $table_column IS NULL OR $table_column = '' )-;
791 qq-( $table_column IS NULL OR $table_column = "" )-;
793 } elsif ( $op eq '!=' ) {
794 if ( driver_name eq 'Pg' ) {
795 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
796 qq-( $table_column IS NOT NULL )-;
798 qq-( $table_column IS NOT NULL AND $table_column != '' )-;
801 qq-( $table_column IS NOT NULL AND $table_column != "" )-;
804 if ( driver_name eq 'Pg' ) {
805 qq-( $table_column $op '' )-;
807 qq-( $table_column $op "" )-;
810 } elsif ( $op eq '!=' ) {
811 qq-( $table_column IS NULL OR $table_column != ? )-;
812 #if this needs to be re-enabled, it needs to use a custom op like
813 #"APPROX=" or something (better name?, not '=', to avoid affecting other
815 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
816 # ( "$table_column <= ?", "$table_column >= ?" );
818 "$table_column $op ?";
825 =item by_key PRIMARY_KEY_VALUE
827 This is a class method that returns the record with the given primary key
828 value. This method is only useful in FS::Record subclasses. For example:
830 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
834 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
839 my ($class, $pkey_value) = @_;
841 my $table = $class->table
842 or croak "No table for $class found";
844 my $dbdef_table = dbdef->table($table)
845 or die "No schema for table $table found - ".
846 "do you need to create it or run dbdef-create?";
847 my $pkey = $dbdef_table->primary_key
848 or die "No primary key for table $table";
850 return qsearchs($table, { $pkey => $pkey_value });
853 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
855 Experimental JOINed search method. Using this method, you can execute a
856 single SELECT spanning multiple tables, and cache the results for subsequent
857 method calls. Interface will almost definately change in an incompatible
865 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
866 my $cache = FS::SearchCache->new( $ptable, $pkey );
869 grep { !$saw{$_->getfield($pkey)}++ }
870 qsearch($table, $record, $select, $extra_sql, $cache )
874 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
876 Same as qsearch, except that if more than one record matches, it B<carp>s but
877 returns the first. If this happens, you either made a logic error in asking
878 for a single item, or your data is corrupted.
882 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
884 my(@result) = qsearch(@_);
885 cluck "warning: Multiple records in scalar search ($table)"
886 if scalar(@result) > 1;
887 #should warn more vehemently if the search was on a primary key?
888 scalar(@result) ? ($result[0]) : ();
899 Returns the table name.
904 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
911 Returns the DBIx::DBSchema::Table object for the table.
917 my($table)=$self->table;
918 dbdef->table($table);
923 Returns the primary key for the table.
929 my $pkey = $self->dbdef_table->primary_key;
932 =item get, getfield COLUMN
934 Returns the value of the column/field/key COLUMN.
939 my($self,$field) = @_;
940 # to avoid "Use of unitialized value" errors
941 if ( defined ( $self->{Hash}->{$field} ) ) {
942 $self->{Hash}->{$field};
952 =item set, setfield COLUMN, VALUE
954 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
959 my($self,$field,$value) = @_;
960 $self->{'modified'} = 1;
961 $self->{'Hash'}->{$field} = $value;
970 Returns true if the column/field/key COLUMN exists.
975 my($self,$field) = @_;
976 exists($self->{Hash}->{$field});
979 =item AUTLOADED METHODS
981 $record->column is a synonym for $record->get('column');
983 $record->column('value') is a synonym for $record->set('column','value');
990 my($field)=$AUTOLOAD;
992 if ( defined($value) ) {
993 confess "errant AUTOLOAD $field for $self (arg $value)"
994 unless blessed($self) && $self->can('setfield');
995 $self->setfield($field,$value);
997 confess "errant AUTOLOAD $field for $self (no args)"
998 unless blessed($self) && $self->can('getfield');
999 $self->getfield($field);
1005 # my $field = $AUTOLOAD;
1006 # $field =~ s/.*://;
1007 # if ( defined($_[1]) ) {
1008 # $_[0]->setfield($field, $_[1]);
1010 # $_[0]->getfield($field);
1016 Returns a list of the column/value pairs, usually for assigning to a new hash.
1018 To make a distinct duplicate of an FS::Record object, you can do:
1020 $new = new FS::Record ( $old->table, { $old->hash } );
1026 confess $self. ' -> hash: Hash attribute is undefined'
1027 unless defined($self->{'Hash'});
1028 %{ $self->{'Hash'} };
1033 Returns a reference to the column/value hash. This may be deprecated in the
1034 future; if there's a reason you can't just use the autoloaded or get/set
1046 Returns true if any of this object's values have been modified with set (or via
1047 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1054 $self->{'modified'};
1057 =item select_for_update
1059 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1064 sub select_for_update {
1066 my $primary_key = $self->primary_key;
1069 'table' => $self->table,
1070 'hashref' => { $primary_key => $self->$primary_key() },
1071 'extra_sql' => 'FOR UPDATE',
1077 Locks this table with a database-driver specific lock method. This is used
1078 as a mutex in order to do a duplicate search.
1080 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1082 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1084 Errors are fatal; no useful return value.
1086 Note: To use this method for new tables other than svc_acct and svc_phone,
1087 edit freeside-upgrade and add those tables to the duplicate_lock list.
1093 my $table = $self->table;
1095 warn "$me locking $table table\n" if $DEBUG;
1097 if ( driver_name =~ /^Pg/i ) {
1099 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1102 } elsif ( driver_name =~ /^mysql/i ) {
1104 dbh->do("SELECT * FROM duplicate_lock
1105 WHERE lockname = '$table'
1107 ) or die dbh->errstr;
1111 die "unknown database ". driver_name. "; don't know how to lock table";
1115 warn "$me acquired $table table lock\n" if $DEBUG;
1121 Inserts this record to the database. If there is an error, returns the error,
1122 otherwise returns false.
1130 warn "$self -> insert" if $DEBUG;
1132 my $error = $self->check;
1133 return $error if $error;
1135 #single-field non-null unique keys are given a value if empty
1136 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1137 foreach ( $self->dbdef_table->unique_singles) {
1138 next if $self->getfield($_);
1139 next if $self->dbdef_table->column($_)->null eq 'NULL';
1143 #and also the primary key, if the database isn't going to
1144 my $primary_key = $self->dbdef_table->primary_key;
1146 if ( $primary_key ) {
1147 my $col = $self->dbdef_table->column($primary_key);
1150 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1151 || ( driver_name eq 'Pg'
1152 && defined($col->default)
1153 && $col->quoted_default =~ /^nextval\(/i
1155 || ( driver_name eq 'mysql'
1156 && defined($col->local)
1157 && $col->local =~ /AUTO_INCREMENT/i
1159 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1162 my $table = $self->table;
1164 # Encrypt before the database
1165 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
1166 && scalar( eval '@FS::'. $table . '::encrypted_fields')
1169 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1170 next if $field eq 'payinfo'
1171 && ($self->isa('FS::payinfo_transaction_Mixin')
1172 || $self->isa('FS::payinfo_Mixin') )
1174 && !grep { $self->payby eq $_ } @encrypt_payby;
1175 $saved->{$field} = $self->getfield($field);
1176 $self->setfield($field, $self->encrypt($self->getfield($field)));
1180 #false laziness w/delete
1182 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1185 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1188 my $statement = "INSERT INTO $table ";
1189 if ( @real_fields ) {
1192 join( ', ', @real_fields ).
1194 join( ', ', @values ).
1198 $statement .= 'DEFAULT VALUES';
1200 warn "[debug]$me $statement\n" if $DEBUG > 1;
1201 my $sth = dbh->prepare($statement) or return dbh->errstr;
1203 local $SIG{HUP} = 'IGNORE';
1204 local $SIG{INT} = 'IGNORE';
1205 local $SIG{QUIT} = 'IGNORE';
1206 local $SIG{TERM} = 'IGNORE';
1207 local $SIG{TSTP} = 'IGNORE';
1208 local $SIG{PIPE} = 'IGNORE';
1210 $sth->execute or return $sth->errstr;
1212 # get inserted id from the database, if applicable & needed
1213 if ( $db_seq && ! $self->getfield($primary_key) ) {
1214 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1218 if ( driver_name eq 'Pg' ) {
1220 #my $oid = $sth->{'pg_oid_status'};
1221 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1223 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1224 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1225 dbh->rollback if $FS::UID::AutoCommit;
1226 return "can't parse $table.$primary_key default value".
1227 " for sequence name: $default";
1231 my $i_sql = "SELECT currval('$sequence')";
1232 my $i_sth = dbh->prepare($i_sql) or do {
1233 dbh->rollback if $FS::UID::AutoCommit;
1236 $i_sth->execute() or do { #$i_sth->execute($oid)
1237 dbh->rollback if $FS::UID::AutoCommit;
1238 return $i_sth->errstr;
1240 $insertid = $i_sth->fetchrow_arrayref->[0];
1242 } elsif ( driver_name eq 'mysql' ) {
1244 $insertid = dbh->{'mysql_insertid'};
1245 # work around mysql_insertid being null some of the time, ala RT :/
1246 unless ( $insertid ) {
1247 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1248 "using SELECT LAST_INSERT_ID();";
1249 my $i_sql = "SELECT LAST_INSERT_ID()";
1250 my $i_sth = dbh->prepare($i_sql) or do {
1251 dbh->rollback if $FS::UID::AutoCommit;
1254 $i_sth->execute or do {
1255 dbh->rollback if $FS::UID::AutoCommit;
1256 return $i_sth->errstr;
1258 $insertid = $i_sth->fetchrow_arrayref->[0];
1263 dbh->rollback if $FS::UID::AutoCommit;
1264 return "don't know how to retreive inserted ids from ". driver_name.
1265 ", try using counterfiles (maybe run dbdef-create?)";
1269 $self->setfield($primary_key, $insertid);
1274 if ( defined( dbdef->table('h_'. $table) ) && ! $no_history ) {
1275 my $h_statement = $self->_h_statement('insert');
1276 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1277 $h_sth = dbh->prepare($h_statement) or do {
1278 dbh->rollback if $FS::UID::AutoCommit;
1284 $h_sth->execute or return $h_sth->errstr if $h_sth;
1286 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1288 # Now that it has been saved, reset the encrypted fields so that $new
1289 # can still be used.
1290 foreach my $field (keys %{$saved}) {
1291 $self->setfield($field, $saved->{$field});
1299 Depriciated (use insert instead).
1304 cluck "warning: FS::Record::add deprecated!";
1305 insert @_; #call method in this scope
1310 Delete this record from the database. If there is an error, returns the error,
1311 otherwise returns false.
1318 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1320 $self->getfield($_) eq ''
1321 #? "( $_ IS NULL OR $_ = \"\" )"
1322 ? ( driver_name eq 'Pg'
1324 : "( $_ IS NULL OR $_ = \"\" )"
1326 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1327 } ( $self->dbdef_table->primary_key )
1328 ? ( $self->dbdef_table->primary_key)
1329 : real_fields($self->table)
1331 warn "[debug]$me $statement\n" if $DEBUG > 1;
1332 my $sth = dbh->prepare($statement) or return dbh->errstr;
1335 if ( defined dbdef->table('h_'. $self->table) ) {
1336 my $h_statement = $self->_h_statement('delete');
1337 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1338 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1343 my $primary_key = $self->dbdef_table->primary_key;
1345 local $SIG{HUP} = 'IGNORE';
1346 local $SIG{INT} = 'IGNORE';
1347 local $SIG{QUIT} = 'IGNORE';
1348 local $SIG{TERM} = 'IGNORE';
1349 local $SIG{TSTP} = 'IGNORE';
1350 local $SIG{PIPE} = 'IGNORE';
1352 my $rc = $sth->execute or return $sth->errstr;
1353 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1354 $h_sth->execute or return $h_sth->errstr if $h_sth;
1356 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1358 #no need to needlessly destoy the data either (causes problems actually)
1359 #undef $self; #no need to keep object!
1366 Depriciated (use delete instead).
1371 cluck "warning: FS::Record::del deprecated!";
1372 &delete(@_); #call method in this scope
1375 =item replace OLD_RECORD
1377 Replace the OLD_RECORD with this one in the database. If there is an error,
1378 returns the error, otherwise returns false.
1383 my ($new, $old) = (shift, shift);
1385 $old = $new->replace_old unless defined($old);
1387 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1389 if ( $new->can('replace_check') ) {
1390 my $error = $new->replace_check($old);
1391 return $error if $error;
1394 return "Records not in same table!" unless $new->table eq $old->table;
1396 my $primary_key = $old->dbdef_table->primary_key;
1397 return "Can't change primary key $primary_key ".
1398 'from '. $old->getfield($primary_key).
1399 ' to ' . $new->getfield($primary_key)
1401 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1403 my $error = $new->check;
1404 return $error if $error;
1406 # Encrypt for replace
1408 if ( $conf_encryption
1409 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1410 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1412 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1413 next if $field eq 'payinfo'
1414 && ($new->isa('FS::payinfo_transaction_Mixin')
1415 || $new->isa('FS::payinfo_Mixin') )
1417 && !grep { $new->payby eq $_ } @encrypt_payby;
1418 $saved->{$field} = $new->getfield($field);
1419 $new->setfield($field, $new->encrypt($new->getfield($field)));
1423 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1424 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1425 ? ($_, $new->getfield($_)) : () } $old->fields;
1427 unless (keys(%diff) || $no_update_diff ) {
1428 carp "[warning]$me ". ref($new)."->replace ".
1429 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1430 ": records identical"
1431 unless $nowarn_identical;
1435 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1437 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1438 } real_fields($old->table)
1443 if ( $old->getfield($_) eq '' ) {
1445 #false laziness w/qsearch
1446 if ( driver_name eq 'Pg' ) {
1447 my $type = $old->dbdef_table->column($_)->type;
1448 if ( $type =~ /(int|(big)?serial)/i ) {
1451 qq-( $_ IS NULL OR $_ = '' )-;
1454 qq-( $_ IS NULL OR $_ = "" )-;
1458 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1461 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1464 warn "[debug]$me $statement\n" if $DEBUG > 1;
1465 my $sth = dbh->prepare($statement) or return dbh->errstr;
1468 if ( defined dbdef->table('h_'. $old->table) ) {
1469 my $h_old_statement = $old->_h_statement('replace_old');
1470 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1471 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1477 if ( defined dbdef->table('h_'. $new->table) ) {
1478 my $h_new_statement = $new->_h_statement('replace_new');
1479 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1480 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1485 local $SIG{HUP} = 'IGNORE';
1486 local $SIG{INT} = 'IGNORE';
1487 local $SIG{QUIT} = 'IGNORE';
1488 local $SIG{TERM} = 'IGNORE';
1489 local $SIG{TSTP} = 'IGNORE';
1490 local $SIG{PIPE} = 'IGNORE';
1492 my $rc = $sth->execute or return $sth->errstr;
1493 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1494 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1495 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1497 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1499 # Now that it has been saved, reset the encrypted fields so that $new
1500 # can still be used.
1501 foreach my $field (keys %{$saved}) {
1502 $new->setfield($field, $saved->{$field});
1510 my( $self ) = shift;
1511 warn "[$me] replace called with no arguments; autoloading old record\n"
1514 my $primary_key = $self->dbdef_table->primary_key;
1515 if ( $primary_key ) {
1516 $self->by_key( $self->$primary_key() ) #this is what's returned
1517 or croak "can't find ". $self->table. ".$primary_key ".
1518 $self->$primary_key();
1520 croak $self->table. " has no primary key; pass old record as argument";
1527 Depriciated (use replace instead).
1532 cluck "warning: FS::Record::rep deprecated!";
1533 replace @_; #call method in this scope
1538 Checks custom fields. Subclasses should still provide a check method to validate
1539 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1545 foreach my $field ($self->virtual_fields) {
1546 my $error = $self->ut_textn($field);
1547 return $error if $error;
1552 =item virtual_fields [ TABLE ]
1554 Returns a list of virtual fields defined for the table. This should not
1555 be exported, and should only be called as an instance or class method.
1559 sub virtual_fields {
1562 $table = $self->table or confess "virtual_fields called on non-table";
1564 confess "Unknown table $table" unless dbdef->table($table);
1566 return () unless dbdef->table('part_virtual_field');
1568 unless ( $virtual_fields_cache{$table} ) {
1569 my $concat = [ "'cf_'", "name" ];
1570 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1571 "WHERE dbtable = '$table'";
1573 my $result = $dbh->selectcol_arrayref($query);
1574 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1576 $virtual_fields_cache{$table} = $result;
1579 @{$virtual_fields_cache{$table}};
1583 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1585 Processes a batch import as a queued JSRPC job
1587 JOB is an FS::queue entry.
1589 OPTIONS_HASHREF can have the following keys:
1595 Table name (required).
1599 Arrayref of field names for static fields. They will be given values from the
1600 PARAMS hashref and passed as a "params" hashref to batch_import.
1604 Formats hashref. Keys are field names, values are listrefs that define the
1607 Each listref value can be a column name or a code reference. Coderefs are run
1608 with the row object, data and a FS::Conf object as the three parameters.
1609 For example, this coderef does the same thing as using the "columnname" string:
1612 my( $record, $data, $conf ) = @_;
1613 $record->columnname( $data );
1616 Coderefs are run after all "column name" fields are assigned.
1620 Optional format hashref of types. Keys are field names, values are "csv",
1621 "xls" or "fixedlength". Overrides automatic determination of file type
1624 =item format_headers
1626 Optional format hashref of header lines. Keys are field names, values are 0
1627 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1630 =item format_sep_chars
1632 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1633 CSV separation character.
1635 =item format_fixedlenth_formats
1637 Optional format hashref of fixed length format defintiions. Keys are field
1638 names, values Parse::FixedLength listrefs of field definitions.
1642 Set true to default to CSV file type if the filename does not contain a
1643 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1648 PARAMS is a hashref (or base64-encoded Storable hashref) containing the
1649 POSTed data. It must contain the field "uploaded files", generated by
1650 /elements/file-upload.html and containing the list of uploaded files.
1651 Currently only supports a single file named "file".
1655 # uploaded_files is kind of bizarre; fix that some time
1657 use Storable qw(thaw);
1660 sub process_batch_import {
1661 my($job, $opt) = ( shift, shift );
1663 my $table = $opt->{table};
1664 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1665 my %formats = %{ $opt->{formats} };
1668 # because some job-spawning code (JSRPC) pre-freezes the arguments,
1669 # and then the 'frozen' attribute doesn't get set, and thus $job->args
1670 # doesn't know to thaw them, we have to do this everywhere.
1672 $param = thaw(decode_base64($param));
1674 warn Dumper($param) if $DEBUG;
1676 my $files = $param->{'uploaded_files'}
1677 or die "No files provided.\n";
1679 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1681 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1682 my $file = $dir. $files{'file'};
1687 formats => \%formats,
1688 format_types => $opt->{format_types},
1689 format_headers => $opt->{format_headers},
1690 format_sep_chars => $opt->{format_sep_chars},
1691 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1692 format_xml_formats => $opt->{format_xml_formats},
1693 format_asn_formats => $opt->{format_asn_formats},
1694 format_row_callbacks => $opt->{format_row_callbacks},
1695 format_hash_callbacks => $opt->{format_hash_callbacks},
1700 format => $param->{format},
1701 params => { map { $_ => $param->{$_} } @pass_params },
1703 default_csv => $opt->{default_csv},
1704 preinsert_callback => $opt->{preinsert_callback},
1705 postinsert_callback => $opt->{postinsert_callback},
1706 insert_args_callback => $opt->{insert_args_callback},
1709 if ( $opt->{'batch_namecol'} ) {
1710 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1711 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1714 my $error = FS::Record::batch_import( \%iopt );
1718 die "$error\n" if $error;
1721 =item batch_import PARAM_HASHREF
1723 Class method for batch imports. Available params:
1729 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1735 =item format_headers
1737 =item format_sep_chars
1739 =item format_fixedlength_formats
1741 =item format_row_callbacks
1743 =item format_hash_callbacks - After parsing, before object creation
1745 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1747 =item preinsert_callback
1749 =item postinsert_callback
1755 FS::queue object, will be updated with progress
1761 csv, xls, fixedlength, xml
1772 warn "$me batch_import call with params: \n". Dumper($param)
1775 my $table = $param->{table};
1777 my $job = $param->{job};
1778 my $file = $param->{file};
1779 my $params = $param->{params} || {};
1781 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1782 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1784 my( $type, $header, $sep_char,
1785 $fixedlength_format, $xml_format, $asn_format,
1786 $parser_opt, $row_callback, $hash_callback, @fields );
1788 my $postinsert_callback = '';
1789 $postinsert_callback = $param->{'postinsert_callback'}
1790 if $param->{'postinsert_callback'};
1791 my $preinsert_callback = '';
1792 $preinsert_callback = $param->{'preinsert_callback'}
1793 if $param->{'preinsert_callback'};
1794 my $insert_args_callback = '';
1795 $insert_args_callback = $param->{'insert_args_callback'}
1796 if $param->{'insert_args_callback'};
1798 if ( $param->{'format'} ) {
1800 my $format = $param->{'format'};
1801 my $formats = $param->{formats};
1802 die "unknown format $format" unless exists $formats->{ $format };
1804 $type = $param->{'format_types'}
1805 ? $param->{'format_types'}{ $format }
1806 : $param->{type} || 'csv';
1809 $header = $param->{'format_headers'}
1810 ? $param->{'format_headers'}{ $param->{'format'} }
1813 $sep_char = $param->{'format_sep_chars'}
1814 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1817 $fixedlength_format =
1818 $param->{'format_fixedlength_formats'}
1819 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1823 $param->{'format_parser_opts'}
1824 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1828 $param->{'format_xml_formats'}
1829 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1833 $param->{'format_asn_formats'}
1834 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1838 $param->{'format_row_callbacks'}
1839 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1843 $param->{'format_hash_callbacks'}
1844 ? $param->{'format_hash_callbacks'}{ $param->{'format'} }
1847 @fields = @{ $formats->{ $format } };
1849 } elsif ( $param->{'fields'} ) {
1851 $type = ''; #infer from filename
1854 $fixedlength_format = '';
1856 $hash_callback = '';
1857 @fields = @{ $param->{'fields'} };
1860 die "neither format nor fields specified";
1863 #my $file = $param->{file};
1866 if ( $file =~ /\.(\w+)$/i ) {
1870 warn "can't parse file type from filename $file; defaulting to CSV";
1874 if $param->{'default_csv'} && $type ne 'xls';
1882 my $asn_header_buffer;
1883 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1885 if ( $type eq 'csv' ) {
1887 $parser_opt->{'binary'} = 1;
1888 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
1889 $parser = Text::CSV_XS->new($parser_opt);
1891 } elsif ( $type eq 'fixedlength' ) {
1893 eval "use Parse::FixedLength;";
1895 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
1898 die "Unknown file type $type\n";
1901 @buffer = split(/\r?\n/, slurp($file) );
1902 splice(@buffer, 0, ($header || 0) );
1903 $count = scalar(@buffer);
1905 } elsif ( $type eq 'xls' ) {
1907 eval "use Spreadsheet::ParseExcel;";
1910 eval "use DateTime::Format::Excel;";
1911 #for now, just let the error be thrown if it is used, since only CDR
1912 # formats bill_west and troop use it, not other excel-parsing things
1915 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1917 $parser = $excel->{Worksheet}[0]; #first sheet
1919 $count = $parser->{MaxRow} || $parser->{MinRow};
1922 $row = $header || 0;
1924 } elsif ( $type eq 'xml' ) {
1927 eval "use XML::Simple;";
1929 my $xmlrow = $xml_format->{'xmlrow'};
1930 $parser = $xml_format->{'xmlkeys'};
1931 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1932 my $data = XML::Simple::XMLin(
1934 'SuppressEmpty' => '', #sets empty values to ''
1938 $rows = $rows->{$_} foreach @$xmlrow;
1939 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1940 $count = @buffer = @$rows;
1942 } elsif ( $type eq 'asn.1' ) {
1944 eval "use Convert::ASN1";
1947 my $asn = Convert::ASN1->new;
1948 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
1950 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
1952 my $data = slurp($file);
1953 my $asn_output = $parser->decode( $data )
1954 or return "No ". $asn_format->{'macro'}. " found\n";
1956 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
1958 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
1959 $count = @buffer = @$rows;
1962 die "Unknown file type $type\n";
1967 local $SIG{HUP} = 'IGNORE';
1968 local $SIG{INT} = 'IGNORE';
1969 local $SIG{QUIT} = 'IGNORE';
1970 local $SIG{TERM} = 'IGNORE';
1971 local $SIG{TSTP} = 'IGNORE';
1972 local $SIG{PIPE} = 'IGNORE';
1974 my $oldAutoCommit = $FS::UID::AutoCommit;
1975 local $FS::UID::AutoCommit = 0;
1978 #my $params = $param->{params} || {};
1979 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1980 my $batch_col = $param->{'batch_keycol'};
1982 my $batch_class = 'FS::'. $param->{'batch_table'};
1983 my $batch = $batch_class->new({
1984 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1986 my $error = $batch->insert;
1988 $dbh->rollback if $oldAutoCommit;
1989 return "can't insert batch record: $error";
1991 #primary key via dbdef? (so the column names don't have to match)
1992 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1994 $params->{ $batch_col } = $batch_value;
1997 #my $job = $param->{job};
2000 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
2004 my %hash = %$params;
2005 if ( $type eq 'csv' ) {
2007 last unless scalar(@buffer);
2008 $line = shift(@buffer);
2010 next if $line =~ /^\s*$/; #skip empty lines
2012 $line = &{$row_callback}($line) if $row_callback;
2014 next if $line =~ /^\s*$/; #skip empty lines
2016 $parser->parse($line) or do {
2017 $dbh->rollback if $oldAutoCommit;
2018 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
2020 @columns = $parser->fields();
2022 } elsif ( $type eq 'fixedlength' ) {
2024 last unless scalar(@buffer);
2025 $line = shift(@buffer);
2027 @columns = $parser->parse($line);
2029 } elsif ( $type eq 'xls' ) {
2031 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
2032 || ! $parser->{Cells}[$row];
2034 my @row = @{ $parser->{Cells}[$row] };
2035 @columns = map $_->{Val}, @row;
2038 #warn $z++. ": $_\n" for @columns;
2040 } elsif ( $type eq 'xml' ) {
2042 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2043 last unless scalar(@buffer);
2044 my $row = shift @buffer;
2045 @columns = @{ $row }{ @$parser };
2047 } elsif ( $type eq 'asn.1' ) {
2049 last unless scalar(@buffer);
2050 my $row = shift @buffer;
2051 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2052 if $asn_format->{row_callback};
2053 foreach my $key ( keys %{ $asn_format->{map} } ) {
2054 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2058 die "Unknown file type $type\n";
2063 foreach my $field ( @fields ) {
2065 my $value = shift @columns;
2067 if ( ref($field) eq 'CODE' ) {
2068 #&{$field}(\%hash, $value);
2069 push @later, $field, $value;
2071 #??? $hash{$field} = $value if length($value);
2072 $hash{$field} = $value if defined($value) && length($value);
2077 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2078 && length($1) == $custnum_length ) {
2079 $hash{custnum} = $2;
2082 %hash = &{$hash_callback}(%hash) if $hash_callback;
2084 #my $table = $param->{table};
2085 my $class = "FS::$table";
2087 my $record = $class->new( \%hash );
2090 while ( scalar(@later) ) {
2091 my $sub = shift @later;
2092 my $data = shift @later;
2094 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2097 $dbh->rollback if $oldAutoCommit;
2098 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2100 last if exists( $param->{skiprow} );
2102 next if exists( $param->{skiprow} );
2104 if ( $preinsert_callback ) {
2105 my $error = &{$preinsert_callback}($record, $param);
2107 $dbh->rollback if $oldAutoCommit;
2108 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2111 next if exists $param->{skiprow} && $param->{skiprow};
2114 my @insert_args = ();
2115 if ( $insert_args_callback ) {
2116 @insert_args = &{$insert_args_callback}($record, $param);
2119 my $error = $record->insert(@insert_args);
2122 $dbh->rollback if $oldAutoCommit;
2123 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2129 if ( $postinsert_callback ) {
2130 my $error = &{$postinsert_callback}($record, $param);
2132 $dbh->rollback if $oldAutoCommit;
2133 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2138 if ( $job && time - $min_sec > $last ) { #progress bar
2139 $job->update_statustext( int(100 * $imported / $count) );
2145 unless ( $imported || $param->{empty_ok} ) {
2146 $dbh->rollback if $oldAutoCommit;
2147 return "Empty file!";
2150 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2157 my( $self, $action, $time ) = @_;
2161 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2164 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2165 real_fields($self->table);
2168 # If we're encrypting then don't store the payinfo in the history
2169 if ( $conf_encryption && $self->table ne 'banned_pay' ) {
2170 @fields = grep { $_ ne 'payinfo' } @fields;
2173 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2175 "INSERT INTO h_". $self->table. " ( ".
2176 join(', ', qw(history_date history_user history_action), @fields ).
2178 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
2185 B<Warning>: External use is B<deprecated>.
2187 Replaces COLUMN in record with a unique number, using counters in the
2188 filesystem. Used by the B<insert> method on single-field unique columns
2189 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2190 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2192 Returns the new value.
2197 my($self,$field) = @_;
2198 my($table)=$self->table;
2200 croak "Unique called on field $field, but it is ",
2201 $self->getfield($field),
2203 if $self->getfield($field);
2205 #warn "table $table is tainted" if is_tainted($table);
2206 #warn "field $field is tainted" if is_tainted($field);
2208 my($counter) = new File::CounterFile "$table.$field",0;
2210 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
2212 # my($counter) = new File::CounterFile "$user/$table.$field",0;
2215 my $index = $counter->inc;
2216 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2218 $index =~ /^(\d*)$/;
2221 $self->setfield($field,$index);
2225 =item ut_float COLUMN
2227 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2228 null. If there is an error, returns the error, otherwise returns false.
2233 my($self,$field)=@_ ;
2234 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2235 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2236 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2237 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2238 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2239 $self->setfield($field,$1);
2242 =item ut_floatn COLUMN
2244 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2245 null. If there is an error, returns the error, otherwise returns false.
2249 #false laziness w/ut_ipn
2251 my( $self, $field ) = @_;
2252 if ( $self->getfield($field) =~ /^()$/ ) {
2253 $self->setfield($field,'');
2256 $self->ut_float($field);
2260 =item ut_sfloat COLUMN
2262 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2263 May not be null. If there is an error, returns the error, otherwise returns
2269 my($self,$field)=@_ ;
2270 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2271 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2272 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2273 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2274 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2275 $self->setfield($field,$1);
2278 =item ut_sfloatn COLUMN
2280 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2281 null. If there is an error, returns the error, otherwise returns false.
2286 my( $self, $field ) = @_;
2287 if ( $self->getfield($field) =~ /^()$/ ) {
2288 $self->setfield($field,'');
2291 $self->ut_sfloat($field);
2295 =item ut_snumber COLUMN
2297 Check/untaint signed numeric data (whole numbers). If there is an error,
2298 returns the error, otherwise returns false.
2303 my($self, $field) = @_;
2304 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2305 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2306 $self->setfield($field, "$1$2");
2310 =item ut_snumbern COLUMN
2312 Check/untaint signed numeric data (whole numbers). If there is an error,
2313 returns the error, otherwise returns false.
2318 my($self, $field) = @_;
2319 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2320 or return "Illegal (numeric) $field: ". $self->getfield($field);
2322 return "Illegal (numeric) $field: ". $self->getfield($field)
2325 $self->setfield($field, "$1$2");
2329 =item ut_number COLUMN
2331 Check/untaint simple numeric data (whole numbers). May not be null. If there
2332 is an error, returns the error, otherwise returns false.
2337 my($self,$field)=@_;
2338 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2339 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2340 $self->setfield($field,$1);
2344 =item ut_numbern COLUMN
2346 Check/untaint simple numeric data (whole numbers). May be null. If there is
2347 an error, returns the error, otherwise returns false.
2352 my($self,$field)=@_;
2353 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2354 or return "Illegal (numeric) $field: ". $self->getfield($field);
2355 $self->setfield($field,$1);
2359 =item ut_decimal COLUMN[, DIGITS]
2361 Check/untaint decimal numbers (up to DIGITS decimal places. If there is an
2362 error, returns the error, otherwise returns false.
2364 =item ut_decimaln COLUMN[, DIGITS]
2366 Check/untaint decimal numbers. May be null. If there is an error, returns
2367 the error, otherwise returns false.
2372 my($self, $field, $digits) = @_;
2374 $self->getfield($field) =~ /^\s*(\d+(\.\d{0,$digits})?)\s*$/
2375 or return "Illegal or empty (decimal) $field: ".$self->getfield($field);
2376 $self->setfield($field, $1);
2381 my($self, $field, $digits) = @_;
2382 $self->getfield($field) =~ /^\s*(\d*(\.\d{0,$digits})?)\s*$/
2383 or return "Illegal (decimal) $field: ".$self->getfield($field);
2384 $self->setfield($field, $1);
2388 =item ut_money COLUMN
2390 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2391 is an error, returns the error, otherwise returns false.
2396 my($self,$field)=@_;
2398 if ( $self->getfield($field) eq '' ) {
2399 $self->setfield($field, 0);
2400 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2401 #handle one decimal place without barfing out
2402 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2403 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2404 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2406 return "Illegal (money) $field: ". $self->getfield($field);
2412 =item ut_moneyn COLUMN
2414 Check/untaint monetary numbers. May be negative. If there
2415 is an error, returns the error, otherwise returns false.
2420 my($self,$field)=@_;
2421 if ($self->getfield($field) eq '') {
2422 $self->setfield($field, '');
2425 $self->ut_money($field);
2428 =item ut_text COLUMN
2430 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2431 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2432 May not be null. If there is an error, returns the error, otherwise returns
2438 my($self,$field)=@_;
2439 #warn "msgcat ". \&msgcat. "\n";
2440 #warn "notexist ". \¬exist. "\n";
2441 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2442 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2443 # see perldoc perluniprops
2444 $self->getfield($field)
2445 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2446 or return gettext('illegal_or_empty_text'). " $field: ".
2447 $self->getfield($field);
2448 $self->setfield($field,$1);
2452 =item ut_textn COLUMN
2454 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2455 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2456 May be null. If there is an error, returns the error, otherwise returns false.
2461 my($self,$field)=@_;
2462 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2463 $self->ut_text($field);
2466 =item ut_alpha COLUMN
2468 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2469 an error, returns the error, otherwise returns false.
2474 my($self,$field)=@_;
2475 $self->getfield($field) =~ /^(\w+)$/
2476 or return "Illegal or empty (alphanumeric) $field: ".
2477 $self->getfield($field);
2478 $self->setfield($field,$1);
2482 =item ut_alphan COLUMN
2484 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2485 error, returns the error, otherwise returns false.
2490 my($self,$field)=@_;
2491 $self->getfield($field) =~ /^(\w*)$/
2492 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2493 $self->setfield($field,$1);
2497 =item ut_alphasn COLUMN
2499 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2500 an error, returns the error, otherwise returns false.
2505 my($self,$field)=@_;
2506 $self->getfield($field) =~ /^([\w ]*)$/
2507 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2508 $self->setfield($field,$1);
2513 =item ut_alpha_lower COLUMN
2515 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2516 there is an error, returns the error, otherwise returns false.
2520 sub ut_alpha_lower {
2521 my($self,$field)=@_;
2522 $self->getfield($field) =~ /[[:upper:]]/
2523 and return "Uppercase characters are not permitted in $field";
2524 $self->ut_alpha($field);
2527 =item ut_phonen COLUMN [ COUNTRY ]
2529 Check/untaint phone numbers. May be null. If there is an error, returns
2530 the error, otherwise returns false.
2532 Takes an optional two-letter ISO 3166-1 alpha-2 country code; without
2533 it or with unsupported countries, ut_phonen simply calls ut_alphan.
2538 my( $self, $field, $country ) = @_;
2539 return $self->ut_alphan($field) unless defined $country;
2540 my $phonen = $self->getfield($field);
2541 if ( $phonen eq '' ) {
2542 $self->setfield($field,'');
2543 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2545 $phonen = $conf->config('cust_main-default_areacode').$phonen
2546 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2547 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2548 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2549 $phonen = "$1-$2-$3";
2550 $phonen .= " x$4" if $4;
2551 $self->setfield($field,$phonen);
2553 warn "warning: don't know how to check phone numbers for country $country";
2554 return $self->ut_textn($field);
2561 Check/untaint hexadecimal values.
2566 my($self, $field) = @_;
2567 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2568 or return "Illegal (hex) $field: ". $self->getfield($field);
2569 $self->setfield($field, uc($1));
2573 =item ut_hexn COLUMN
2575 Check/untaint hexadecimal values. May be null.
2580 my($self, $field) = @_;
2581 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2582 or return "Illegal (hex) $field: ". $self->getfield($field);
2583 $self->setfield($field, uc($1));
2587 =item ut_mac_addr COLUMN
2589 Check/untaint mac addresses. May be null.
2594 my($self, $field) = @_;
2596 my $mac = $self->get($field);
2599 $self->set($field, $mac);
2601 my $e = $self->ut_hex($field);
2604 return "Illegal (mac address) $field: ". $self->getfield($field)
2605 unless length($self->getfield($field)) == 12;
2611 =item ut_mac_addrn COLUMN
2613 Check/untaint mac addresses. May be null.
2618 my($self, $field) = @_;
2619 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2624 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2630 my( $self, $field ) = @_;
2631 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2632 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2633 or return "Illegal (IP address) $field: ". $self->getfield($field);
2634 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2635 $self->setfield($field, "$1.$2.$3.$4");
2641 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2642 to 127.0.0.1. May be null.
2647 my( $self, $field ) = @_;
2648 if ( $self->getfield($field) =~ /^()$/ ) {
2649 $self->setfield($field,'');
2652 $self->ut_ip($field);
2656 =item ut_ip46 COLUMN
2658 Check/untaint IPv4 or IPv6 address.
2663 my( $self, $field ) = @_;
2664 my $ip = NetAddr::IP->new($self->getfield($field))
2665 or return "Illegal (IP address) $field: ".$self->getfield($field);
2666 $self->setfield($field, lc($ip->addr));
2672 Check/untaint IPv6 or IPv6 address. May be null.
2677 my( $self, $field ) = @_;
2678 if ( $self->getfield($field) =~ /^$/ ) {
2679 $self->setfield($field, '');
2682 $self->ut_ip46($field);
2685 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2687 Check/untaint coordinates.
2688 Accepts the following forms:
2698 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2699 The latter form (that is, the MMM are thousands of minutes) is
2700 assumed if the "MMM" is exactly three digits or two digits > 59.
2702 To be safe, just use the DDD.DDDDD form.
2704 If LOWER or UPPER are specified, then the coordinate is checked
2705 for lower and upper bounds, respectively.
2710 my ($self, $field) = (shift, shift);
2713 if ( $field =~ /latitude/ ) {
2714 $lower = $lat_lower;
2716 } elsif ( $field =~ /longitude/ ) {
2718 $upper = $lon_upper;
2721 my $coord = $self->getfield($field);
2722 my $neg = $coord =~ s/^(-)//;
2724 my ($d, $m, $s) = (0, 0, 0);
2727 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2728 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2729 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2731 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2734 return "Invalid (coordinate with minutes > 59) $field: "
2735 . $self->getfield($field);
2738 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2740 if (defined($lower) and ($coord < $lower)) {
2741 return "Invalid (coordinate < $lower) $field: "
2742 . $self->getfield($field);;
2745 if (defined($upper) and ($coord > $upper)) {
2746 return "Invalid (coordinate > $upper) $field: "
2747 . $self->getfield($field);;
2750 $self->setfield($field, $coord);
2754 return "Invalid (coordinate) $field: " . $self->getfield($field);
2758 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2760 Same as ut_coord, except optionally null.
2766 my ($self, $field) = (shift, shift);
2768 if ($self->getfield($field) =~ /^\s*$/) {
2771 return $self->ut_coord($field, @_);
2776 =item ut_domain COLUMN
2778 Check/untaint host and domain names. May not be null.
2783 my( $self, $field ) = @_;
2784 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2785 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2786 or return "Illegal (hostname) $field: ". $self->getfield($field);
2787 $self->setfield($field,$1);
2791 =item ut_domainn COLUMN
2793 Check/untaint host and domain names. May be null.
2798 my( $self, $field ) = @_;
2799 if ( $self->getfield($field) =~ /^()$/ ) {
2800 $self->setfield($field,'');
2803 $self->ut_domain($field);
2807 =item ut_name COLUMN
2809 Check/untaint proper names; allows alphanumerics, spaces and the following
2810 punctuation: , . - '
2817 my( $self, $field ) = @_;
2818 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2819 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
2820 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2825 $self->setfield($field, $name);
2829 =item ut_namen COLUMN
2831 Check/untaint proper names; allows alphanumerics, spaces and the following
2832 punctuation: , . - '
2839 my( $self, $field ) = @_;
2840 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2841 $self->ut_name($field);
2846 Check/untaint zip codes.
2850 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2853 my( $self, $field, $country ) = @_;
2855 if ( $country eq 'US' ) {
2857 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2858 or return gettext('illegal_zip'). " $field for country $country: ".
2859 $self->getfield($field);
2860 $self->setfield($field, $1);
2862 } elsif ( $country eq 'CA' ) {
2864 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2865 or return gettext('illegal_zip'). " $field for country $country: ".
2866 $self->getfield($field);
2867 $self->setfield($field, "$1 $2");
2871 if ( $self->getfield($field) =~ /^\s*$/
2872 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2875 $self->setfield($field,'');
2877 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2878 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2879 $self->setfield($field,$1);
2887 =item ut_country COLUMN
2889 Check/untaint country codes. Country names are changed to codes, if possible -
2890 see L<Locale::Country>.
2895 my( $self, $field ) = @_;
2896 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2897 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2898 && country2code($1) ) {
2899 $self->setfield($field,uc(country2code($1)));
2902 $self->getfield($field) =~ /^(\w\w)$/
2903 or return "Illegal (country) $field: ". $self->getfield($field);
2904 $self->setfield($field,uc($1));
2908 =item ut_anything COLUMN
2910 Untaints arbitrary data. Be careful.
2915 my( $self, $field ) = @_;
2916 $self->getfield($field) =~ /^(.*)$/s
2917 or return "Illegal $field: ". $self->getfield($field);
2918 $self->setfield($field,$1);
2922 =item ut_enum COLUMN CHOICES_ARRAYREF
2924 Check/untaint a column, supplying all possible choices, like the "enum" type.
2929 my( $self, $field, $choices ) = @_;
2930 foreach my $choice ( @$choices ) {
2931 if ( $self->getfield($field) eq $choice ) {
2932 $self->setfield($field, $choice);
2936 return "Illegal (enum) field $field: ". $self->getfield($field);
2939 =item ut_enumn COLUMN CHOICES_ARRAYREF
2941 Like ut_enum, except the null value is also allowed.
2946 my( $self, $field, $choices ) = @_;
2947 $self->getfield($field)
2948 ? $self->ut_enum($field, $choices)
2952 =item ut_flag COLUMN
2954 Check/untaint a column if it contains either an empty string or 'Y'. This
2955 is the standard form for boolean flags in Freeside.
2960 my( $self, $field ) = @_;
2961 my $value = uc($self->getfield($field));
2962 if ( $value eq '' or $value eq 'Y' ) {
2963 $self->setfield($field, $value);
2966 return "Illegal (flag) field $field: $value";
2969 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2971 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2972 on the column first.
2976 sub ut_foreign_key {
2977 my( $self, $field, $table, $foreign ) = @_;
2978 return '' if $no_check_foreign;
2979 qsearchs($table, { $foreign => $self->getfield($field) })
2980 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2981 " in $table.$foreign";
2985 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2987 Like ut_foreign_key, except the null value is also allowed.
2991 sub ut_foreign_keyn {
2992 my( $self, $field, $table, $foreign ) = @_;
2993 $self->getfield($field)
2994 ? $self->ut_foreign_key($field, $table, $foreign)
2998 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
3000 Checks this column as an agentnum, taking into account the current users's
3001 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
3002 right or rights allowing no agentnum.
3006 sub ut_agentnum_acl {
3007 my( $self, $field ) = (shift, shift);
3008 my $null_acl = scalar(@_) ? shift : [];
3009 $null_acl = [ $null_acl ] unless ref($null_acl);
3011 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
3012 return "Illegal agentnum: $error" if $error;
3014 my $curuser = $FS::CurrentUser::CurrentUser;
3016 if ( $self->$field() ) {
3018 return "Access denied"
3019 unless $curuser->agentnum($self->$field());
3023 return "Access denied"
3024 unless grep $curuser->access_right($_), @$null_acl;
3032 =item fields [ TABLE ]
3034 This is a wrapper for real_fields. Code that called
3035 fields before should probably continue to call fields.
3040 my $something = shift;
3042 if($something->isa('FS::Record')) {
3043 $table = $something->table;
3045 $table = $something;
3046 $something = "FS::$table";
3048 return (real_fields($table));
3052 =item encrypt($value)
3054 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
3056 Returns the encrypted string.
3058 You should generally not have to worry about calling this, as the system handles this for you.
3063 my ($self, $value) = @_;
3064 my $encrypted = $value;
3066 if ($conf_encryption) {
3067 if ($self->is_encrypted($value)) {
3068 # Return the original value if it isn't plaintext.
3069 $encrypted = $value;
3072 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3073 # RSA doesn't like the empty string so let's pack it up
3074 # The database doesn't like the RSA data so uuencode it
3075 my $length = length($value)+1;
3076 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3078 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3085 =item is_encrypted($value)
3087 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3093 my ($self, $value) = @_;
3094 # Possible Bug - Some work may be required here....
3096 if ($value =~ /^M/ && length($value) > 80) {
3103 =item decrypt($value)
3105 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3107 You should generally not have to worry about calling this, as the system handles this for you.
3112 my ($self,$value) = @_;
3113 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3114 if ($conf_encryption && $self->is_encrypted($value)) {
3116 if (ref($rsa_decrypt) =~ /::RSA/) {
3117 my $encrypted = unpack ("u*", $value);
3118 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3119 if ($@) {warn "Decryption Failed"};
3127 #Initialize the Module
3128 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3130 if ($conf_encryptionmodule && $conf_encryptionmodule ne '') {
3131 $rsa_module = $conf_encryptionmodule;
3135 eval ("require $rsa_module"); # No need to import the namespace
3138 # Initialize Encryption
3139 if ($conf_encryptionpublickey && $conf_encryptionpublickey ne '') {
3140 $rsa_encrypt = $rsa_module->new_public_key($conf_encryptionpublickey);
3143 # Intitalize Decryption
3144 if ($conf_encryptionprivatekey && $conf_encryptionprivatekey ne '') {
3145 $rsa_decrypt = $rsa_module->new_private_key($conf_encryptionprivatekey);
3149 =item h_search ACTION
3151 Given an ACTION, either "insert", or "delete", returns the appropriate history
3152 record corresponding to this record, if any.
3157 my( $self, $action ) = @_;
3159 my $table = $self->table;
3162 my $primary_key = dbdef->table($table)->primary_key;
3165 'table' => "h_$table",
3166 'hashref' => { $primary_key => $self->$primary_key(),
3167 'history_action' => $action,
3175 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3176 appropriate history record corresponding to this record, if any.
3181 my($self, $action) = @_;
3182 my $h = $self->h_search($action);
3183 $h ? $h->history_date : '';
3186 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3188 A class or object method. Executes the sql statement represented by SQL and
3189 returns a scalar representing the result: the first column of the first row.
3191 Dies on bogus SQL. Returns an empty string if no row is returned.
3193 Typically used for statments which return a single value such as "SELECT
3194 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3199 my($self, $sql) = (shift, shift);
3200 my $sth = dbh->prepare($sql) or die dbh->errstr;
3202 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3203 my $row = $sth->fetchrow_arrayref or return '';
3204 my $scalar = $row->[0];
3205 defined($scalar) ? $scalar : '';
3208 =item count [ WHERE [, PLACEHOLDER ...] ]
3210 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3211 with optional WHERE. Must be called as method on a class with an
3217 my($self, $where) = (shift, shift);
3218 my $table = $self->table or die 'count called on object of class '.ref($self);
3219 my $sql = "SELECT COUNT(*) FROM $table";
3220 $sql .= " WHERE $where" if $where;
3221 $self->scalar_sql($sql, @_);
3224 =item row_exists [ WHERE [, PLACEHOLDER ...] ]
3226 Convenience method for the common case of "SELECT 1 FROM table ... LIMIT 1"
3227 with optional (but almost always needed) WHERE.
3232 my($self, $where) = (shift, shift);
3233 my $table = $self->table or die 'row_exists called on object of class '.ref($self);
3234 my $sql = "SELECT 1 FROM $table";
3235 $sql .= " WHERE $where" if $where;
3237 $self->scalar_sql($sql, @_);
3246 =item real_fields [ TABLE ]
3248 Returns a list of the real columns in the specified table. Called only by
3249 fields() and other subroutines elsewhere in FS::Record.
3256 my($table_obj) = dbdef->table($table);
3257 confess "Unknown table $table" unless $table_obj;
3258 $table_obj->columns;
3261 =item pvf FIELD_NAME
3263 Returns the FS::part_virtual_field object corresponding to a field in the
3264 record (specified by FIELD_NAME).
3269 my ($self, $name) = (shift, shift);
3271 if(grep /^$name$/, $self->virtual_fields) {
3273 my $concat = [ "'cf_'", "name" ];
3274 return qsearchs({ table => 'part_virtual_field',
3275 hashref => { dbtable => $self->table,
3278 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3284 =item _quote VALUE, TABLE, COLUMN
3286 This is an internal function used to construct SQL statements. It returns
3287 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3288 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3293 my($value, $table, $column) = @_;
3294 my $column_obj = dbdef->table($table)->column($column);
3295 my $column_type = $column_obj->type;
3296 my $nullable = $column_obj->null;
3298 utf8::upgrade($value);
3300 warn " $table.$column: $value ($column_type".
3301 ( $nullable ? ' NULL' : ' NOT NULL' ).
3302 ")\n" if $DEBUG > 2;
3304 if ( $value eq '' && $nullable ) {
3306 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3307 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3310 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3311 ! $column_type =~ /(char|binary|text)$/i ) {
3313 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3314 && driver_name eq 'Pg'
3318 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3319 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3320 # single-quote the whole mess, and put an "E" in front.
3321 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3329 This is deprecated. Don't use it.
3331 It returns a hash-type list with the fields of this record's table set true.
3336 carp "warning: hfields is deprecated";
3339 foreach (fields($table)) {
3348 "$_: ". $self->getfield($_). "|"
3349 } (fields($self->table)) );
3352 sub DESTROY { return; }
3356 # #use Carp qw(cluck);
3357 # #cluck "DESTROYING $self";
3358 # warn "DESTROYING $self";
3362 # return ! eval { join('',@_), kill 0; 1; };
3365 =item str2time_sql [ DRIVER_NAME ]
3367 Returns a function to convert to unix time based on database type, such as
3368 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3369 the str2time_sql_closing method to return a closing string rather than just
3370 using a closing parenthesis as previously suggested.
3372 You can pass an optional driver name such as "Pg", "mysql" or
3373 $dbh->{Driver}->{Name} to return a function for that database instead of
3374 the current database.
3379 my $driver = shift || driver_name;
3381 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3382 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3384 warn "warning: unknown database type $driver; guessing how to convert ".
3385 "dates to UNIX timestamps";
3386 return 'EXTRACT(EPOCH FROM ';
3390 =item str2time_sql_closing [ DRIVER_NAME ]
3392 Returns the closing suffix of a function to convert to unix time based on
3393 database type, such as ")::integer" for Pg or ")" for mysql.
3395 You can pass an optional driver name such as "Pg", "mysql" or
3396 $dbh->{Driver}->{Name} to return a function for that database instead of
3397 the current database.
3401 sub str2time_sql_closing {
3402 my $driver = shift || driver_name;
3404 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3408 =item regexp_sql [ DRIVER_NAME ]
3410 Returns the operator to do a regular expression comparison based on database
3411 type, such as '~' for Pg or 'REGEXP' for mysql.
3413 You can pass an optional driver name such as "Pg", "mysql" or
3414 $dbh->{Driver}->{Name} to return a function for that database instead of
3415 the current database.
3420 my $driver = shift || driver_name;
3422 return '~' if $driver =~ /^Pg/i;
3423 return 'REGEXP' if $driver =~ /^mysql/i;
3425 die "don't know how to use regular expressions in ". driver_name." databases";
3429 =item not_regexp_sql [ DRIVER_NAME ]
3431 Returns the operator to do a regular expression negation based on database
3432 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3434 You can pass an optional driver name such as "Pg", "mysql" or
3435 $dbh->{Driver}->{Name} to return a function for that database instead of
3436 the current database.
3440 sub not_regexp_sql {
3441 my $driver = shift || driver_name;
3443 return '!~' if $driver =~ /^Pg/i;
3444 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3446 die "don't know how to use regular expressions in ". driver_name." databases";
3450 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3452 Returns the items concatenated based on database type, using "CONCAT()" for
3453 mysql and " || " for Pg and other databases.
3455 You can pass an optional driver name such as "Pg", "mysql" or
3456 $dbh->{Driver}->{Name} to return a function for that database instead of
3457 the current database.
3462 my $driver = ref($_[0]) ? driver_name : shift;
3465 if ( $driver =~ /^mysql/i ) {
3466 'CONCAT('. join(',', @$items). ')';
3468 join('||', @$items);
3473 =item group_concat_sql COLUMN, DELIMITER
3475 Returns an SQL expression to concatenate an aggregate column, using
3476 GROUP_CONCAT() for mysql and array_to_string() and array_agg() for Pg.
3480 sub group_concat_sql {
3481 my ($col, $delim) = @_;
3482 $delim = dbh->quote($delim);
3483 if ( driver_name() =~ /^mysql/i ) {
3484 # DISTINCT(foo) is valid as $col
3485 return "GROUP_CONCAT($col SEPARATOR $delim)";
3487 return "array_to_string(array_agg($col), $delim)";
3491 =item midnight_sql DATE
3493 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3494 on that day in the system timezone, using the default driver name.
3499 my $driver = driver_name;
3501 if ( $driver =~ /^mysql/i ) {
3502 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3505 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3513 This module should probably be renamed, since much of the functionality is
3514 of general use. It is not completely unlike Adapter::DBI (see below).
3516 Exported qsearch and qsearchs should be deprecated in favor of method calls
3517 (against an FS::Record object like the old search and searchs that qsearch
3518 and qsearchs were on top of.)
3520 The whole fields / hfields mess should be removed.
3522 The various WHERE clauses should be subroutined.
3524 table string should be deprecated in favor of DBIx::DBSchema::Table.
3526 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3527 true maps to the database (and WHERE clauses) would also help.
3529 The ut_ methods should ask the dbdef for a default length.
3531 ut_sqltype (like ut_varchar) should all be defined
3533 A fallback check method should be provided which uses the dbdef.
3535 The ut_money method assumes money has two decimal digits.
3537 The Pg money kludge in the new method only strips `$'.
3539 The ut_phonen method only checks US-style phone numbers.
3541 The _quote function should probably use ut_float instead of a regex.
3543 All the subroutines probably should be methods, here or elsewhere.
3545 Probably should borrow/use some dbdef methods where appropriate (like sub
3548 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3549 or allow it to be set. Working around it is ugly any way around - DBI should
3550 be fixed. (only affects RDBMS which return uppercase column names)
3552 ut_zip should take an optional country like ut_phone.
3556 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3558 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.