4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $conf $conf_encryption $me
7 $nowarn_identical $nowarn_classload
8 $no_update_diff $no_check_foreign
11 use Carp qw(carp cluck croak confess);
12 use Scalar::Util qw( blessed );
13 use File::CounterFile;
16 use File::Slurp qw( slurp );
17 use DBI qw(:sql_types);
18 use DBIx::DBSchema 0.38;
19 use FS::UID qw(dbh getotaker datasrc driver_name);
21 use FS::Schema qw(dbdef);
23 use FS::Msgcat qw(gettext);
24 #use FS::Conf; #dependency loop bs, in install_callback below instead
26 use FS::part_virtual_field;
32 #export dbdef for now... everything else expects to find it here
33 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
34 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql );
39 $nowarn_identical = 0;
40 $nowarn_classload = 0;
42 $no_check_foreign = 0;
50 $conf_encryption = '';
51 FS::UID->install_callback( sub {
54 $conf = FS::Conf->new;
55 $conf_encryption = $conf->exists('encryption');
56 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
57 if ( driver_name eq 'Pg' ) {
58 eval "use DBD::Pg ':pg_types'";
61 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
67 FS::Record - Database record objects
72 use FS::Record qw(dbh fields qsearch qsearchs);
74 $record = new FS::Record 'table', \%hash;
75 $record = new FS::Record 'table', { 'column' => 'value', ... };
77 $record = qsearchs FS::Record 'table', \%hash;
78 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
79 @records = qsearch FS::Record 'table', \%hash;
80 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
82 $table = $record->table;
83 $dbdef_table = $record->dbdef_table;
85 $value = $record->get('column');
86 $value = $record->getfield('column');
87 $value = $record->column;
89 $record->set( 'column' => 'value' );
90 $record->setfield( 'column' => 'value' );
91 $record->column('value');
93 %hash = $record->hash;
95 $hashref = $record->hashref;
97 $error = $record->insert;
99 $error = $record->delete;
101 $error = $new_record->replace($old_record);
103 # external use deprecated - handled by the database (at least for Pg, mysql)
104 $value = $record->unique('column');
106 $error = $record->ut_float('column');
107 $error = $record->ut_floatn('column');
108 $error = $record->ut_number('column');
109 $error = $record->ut_numbern('column');
110 $error = $record->ut_snumber('column');
111 $error = $record->ut_snumbern('column');
112 $error = $record->ut_money('column');
113 $error = $record->ut_text('column');
114 $error = $record->ut_textn('column');
115 $error = $record->ut_alpha('column');
116 $error = $record->ut_alphan('column');
117 $error = $record->ut_phonen('column');
118 $error = $record->ut_anything('column');
119 $error = $record->ut_name('column');
121 $quoted_value = _quote($value,'table','field');
124 $fields = hfields('table');
125 if ( $fields->{Field} ) { # etc.
127 @fields = fields 'table'; #as a subroutine
128 @fields = $record->fields; #as a method call
133 (Mostly) object-oriented interface to database records. Records are currently
134 implemented on top of DBI. FS::Record is intended as a base class for
135 table-specific classes to inherit from, i.e. FS::cust_main.
141 =item new [ TABLE, ] HASHREF
143 Creates a new record. It doesn't store it in the database, though. See
144 L<"insert"> for that.
146 Note that the object stores this hash reference, not a distinct copy of the
147 hash it points to. You can ask the object for a copy with the I<hash>
150 TABLE can only be omitted when a dervived class overrides the table method.
156 my $class = ref($proto) || $proto;
158 bless ($self, $class);
160 unless ( defined ( $self->table ) ) {
161 $self->{'Table'} = shift;
162 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
163 unless $nowarn_classload;
166 $self->{'Hash'} = shift;
168 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
169 $self->{'Hash'}{$field}='';
172 $self->_rebless if $self->can('_rebless');
174 $self->{'modified'} = 0;
176 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
183 my $class = ref($proto) || $proto;
185 bless ($self, $class);
187 $self->{'Table'} = shift unless defined ( $self->table );
189 my $hashref = $self->{'Hash'} = shift;
191 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
192 my $obj = $cache->cache->{$hashref->{$cache->key}};
193 $obj->_cache($hashref, $cache) if $obj->can('_cache');
196 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
203 my $class = ref($proto) || $proto;
205 bless ($self, $class);
206 if ( defined $self->table ) {
207 cluck "create constructor is deprecated, use new!";
210 croak "FS::Record::create called (not from a subclass)!";
214 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
216 Searches the database for all records matching (at least) the key/value pairs
217 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
218 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
221 The preferred usage is to pass a hash reference of named parameters:
223 @records = qsearch( {
224 'table' => 'table_name',
225 'hashref' => { 'field' => 'value'
226 'field' => { 'op' => '<',
231 #these are optional...
233 'extra_sql' => 'AND field = ? AND intfield = ?',
234 'extra_param' => [ 'value', [ 5, 'int' ] ],
235 'order_by' => 'ORDER BY something',
236 #'cache_obj' => '', #optional
237 'addl_from' => 'LEFT JOIN othtable USING ( field )',
242 Much code still uses old-style positional parameters, this is also probably
243 fine in the common case where there are only two parameters:
245 my @records = qsearch( 'table', { 'field' => 'value' } );
247 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
248 the individual PARAMS_HASHREF queries
250 ###oops, argh, FS::Record::new only lets us create database fields.
251 #Normal behaviour if SELECT is not specified is `*', as in
252 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
253 #feature where you can specify SELECT - remember, the objects returned,
254 #although blessed into the appropriate `FS::TABLE' package, will only have the
255 #fields you specify. This might have unwanted results if you then go calling
256 #regular FS::TABLE methods
261 my %TYPE = (); #for debugging
264 my($type, $value) = @_;
266 my $bind_type = { TYPE => SQL_VARCHAR };
268 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
270 $bind_type = { TYPE => SQL_INTEGER };
272 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
274 if ( driver_name eq 'Pg' ) {
276 $bind_type = { pg_type => PG_BYTEA };
278 # $bind_type = ? #SQL_VARCHAR could be fine?
281 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
282 #fixed by DBD::Pg 2.11.8
283 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
284 #(make a Tron test first)
285 } elsif ( _is_fs_float( $type, $value ) ) {
287 $bind_type = { TYPE => SQL_DECIMAL };
296 my($type, $value) = @_;
297 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
298 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
306 my( @stable, @record, @cache );
307 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
309 my %union_options = ();
310 if ( ref($_[0]) eq 'ARRAY' ) {
313 foreach my $href ( @$optlist ) {
314 push @stable, ( $href->{'table'} or die "table name is required" );
315 push @record, ( $href->{'hashref'} || {} );
316 push @select, ( $href->{'select'} || '*' );
317 push @extra_sql, ( $href->{'extra_sql'} || '' );
318 push @extra_param, ( $href->{'extra_param'} || [] );
319 push @order_by, ( $href->{'order_by'} || '' );
320 push @cache, ( $href->{'cache_obj'} || '' );
321 push @addl_from, ( $href->{'addl_from'} || '' );
322 push @debug, ( $href->{'debug'} || '' );
324 die "at least one hashref is required" unless scalar(@stable);
325 } elsif ( ref($_[0]) eq 'HASH' ) {
327 $stable[0] = $opt->{'table'} or die "table name is required";
328 $record[0] = $opt->{'hashref'} || {};
329 $select[0] = $opt->{'select'} || '*';
330 $extra_sql[0] = $opt->{'extra_sql'} || '';
331 $extra_param[0] = $opt->{'extra_param'} || [];
332 $order_by[0] = $opt->{'order_by'} || '';
333 $cache[0] = $opt->{'cache_obj'} || '';
334 $addl_from[0] = $opt->{'addl_from'} || '';
335 $debug[0] = $opt->{'debug'} || '';
346 my $cache = $cache[0];
352 foreach my $stable ( @stable ) {
353 #stop altering the caller's hashref
354 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
355 my $select = shift @select;
356 my $extra_sql = shift @extra_sql;
357 my $extra_param = shift @extra_param;
358 my $order_by = shift @order_by;
359 my $cache = shift @cache;
360 my $addl_from = shift @addl_from;
361 my $debug = shift @debug;
363 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
365 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
368 my $table = $cache ? $cache->table : $stable;
369 my $dbdef_table = dbdef->table($table)
370 or die "No schema for table $table found - ".
371 "do you need to run freeside-upgrade?";
372 my $pkey = $dbdef_table->primary_key;
374 my @real_fields = grep exists($record->{$_}), real_fields($table);
376 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
377 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
379 cluck "warning: FS::$table not loaded; virtual fields not searchable"
380 unless $nowarn_classload;
381 @virtual_fields = ();
384 my $statement .= "SELECT $select FROM $stable";
385 $statement .= " $addl_from" if $addl_from;
386 if ( @real_fields or @virtual_fields ) {
387 $statement .= ' WHERE '. join(' AND ',
388 get_real_fields($table, $record, \@real_fields) ,
389 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
393 $statement .= " $extra_sql" if defined($extra_sql);
394 $statement .= " $order_by" if defined($order_by);
396 push @statement, $statement;
398 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
402 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
405 my $value = $record->{$field};
406 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
407 $value = $value->{'value'} if ref($value);
408 my $type = dbdef->table($table)->column($field)->type;
410 my $bind_type = _bind_type($type, $value);
414 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
416 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
420 push @bind_type, $bind_type;
424 foreach my $param ( @$extra_param ) {
425 my $bind_type = { TYPE => SQL_VARCHAR };
428 $value = $param->[0];
429 my $type = $param->[1];
430 $bind_type = _bind_type($type, $value);
433 push @bind_type, $bind_type;
437 my $statement = join( ' ) UNION ( ', @statement );
438 $statement = "( $statement )" if scalar(@statement) > 1;
439 $statement .= " $union_options{order_by}" if $union_options{order_by};
441 my $sth = $dbh->prepare($statement)
442 or croak "$dbh->errstr doing $statement";
445 foreach my $value ( @value ) {
446 my $bind_type = shift @bind_type;
447 $sth->bind_param($bind++, $value, $bind_type );
450 # $sth->execute( map $record->{$_},
451 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
452 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
454 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
456 # virtual fields and blessings are nonsense in a heterogeneous UNION, right?
457 my $table = $stable[0];
459 $table = '' if grep { $_ ne $table } @stable;
460 $pkey = dbdef->table($table)->primary_key if $table;
462 my @virtual_fields = ();
463 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
464 @virtual_fields = "FS::$table"->virtual_fields;
466 cluck "warning: FS::$table not loaded; virtual fields not returned either"
467 unless $nowarn_classload;
468 @virtual_fields = ();
472 tie %result, "Tie::IxHash";
473 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
474 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
475 %result = map { $_->{$pkey}, $_ } @stuff;
477 @result{@stuff} = @stuff;
482 if ( keys(%result) and @virtual_fields ) {
484 "SELECT virtual_field.recnum, part_virtual_field.name, ".
485 "virtual_field.value ".
486 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
487 "WHERE part_virtual_field.dbtable = '$table' AND ".
488 "virtual_field.recnum IN (".
489 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
490 join(q!', '!, @virtual_fields) . "')";
491 warn "[debug]$me $statement\n" if $DEBUG > 1;
492 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
493 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
495 foreach (@{ $sth->fetchall_arrayref({}) }) {
496 my $recnum = $_->{recnum};
497 my $name = $_->{name};
498 my $value = $_->{value};
499 if (exists($result{$recnum})) {
500 $result{$recnum}->{$name} = $value;
505 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
506 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
507 #derivied class didn't override new method, so this optimization is safe
510 new_or_cached( "FS::$table", { %{$_} }, $cache )
514 new( "FS::$table", { %{$_} } )
518 #okay, its been tested
519 # warn "untested code (class FS::$table uses custom new method)";
521 eval 'FS::'. $table. '->new( { %{$_} } )';
525 # Check for encrypted fields and decrypt them.
526 ## only in the local copy, not the cached object
527 if ( $conf_encryption
528 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
529 foreach my $record (@return) {
530 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
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, { %{$_} } );
546 ## makes this easier to read
548 sub get_virtual_fields {
552 my $virtual_fields = shift;
558 if ( ref($record->{$_}) ) {
559 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
560 if ( uc($op) eq 'ILIKE' ) {
562 $record->{$_}{'value'} = lc($record->{$_}{'value'});
563 $column = "LOWER($_)";
565 $record->{$_} = $record->{$_}{'value'};
568 # ... EXISTS ( SELECT name, value FROM part_virtual_field
570 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
571 # WHERE recnum = svc_acct.svcnum
572 # AND (name, value) = ('egad', 'brain') )
574 my $value = $record->{$_};
578 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
579 "( SELECT part_virtual_field.name, virtual_field.value ".
580 "FROM part_virtual_field JOIN virtual_field ".
581 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
582 "WHERE virtual_field.recnum = ${table}.${pkey} ".
583 "AND part_virtual_field.name = '${column}'".
585 " AND virtual_field.value ${op} '${value}'"
589 } @{ $virtual_fields } ) ;
592 sub get_real_fields {
595 my $real_fields = shift;
597 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
603 my $type = dbdef->table($table)->column($column)->type;
604 my $value = $record->{$column};
605 $value = $value->{'value'} if ref($value);
606 if ( ref($record->{$_}) ) {
607 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
608 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
609 if ( uc($op) eq 'ILIKE' ) {
611 $record->{$_}{'value'} = lc($record->{$_}{'value'});
612 $column = "LOWER($_)";
614 $record->{$_} = $record->{$_}{'value'}
617 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
619 if ( driver_name eq 'Pg' ) {
620 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
621 qq-( $column IS NULL )-;
623 qq-( $column IS NULL OR $column = '' )-;
626 qq-( $column IS NULL OR $column = "" )-;
628 } elsif ( $op eq '!=' ) {
629 if ( driver_name eq 'Pg' ) {
630 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
631 qq-( $column IS NOT NULL )-;
633 qq-( $column IS NOT NULL AND $column != '' )-;
636 qq-( $column IS NOT NULL AND $column != "" )-;
639 if ( driver_name eq 'Pg' ) {
640 qq-( $column $op '' )-;
642 qq-( $column $op "" )-;
645 #if this needs to be re-enabled, it needs to use a custom op like
646 #"APPROX=" or something (better name?, not '=', to avoid affecting other
648 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
649 # ( "$column <= ?", "$column >= ?" );
653 } @{ $real_fields } );
656 =item by_key PRIMARY_KEY_VALUE
658 This is a class method that returns the record with the given primary key
659 value. This method is only useful in FS::Record subclasses. For example:
661 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
665 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
670 my ($class, $pkey_value) = @_;
672 my $table = $class->table
673 or croak "No table for $class found";
675 my $dbdef_table = dbdef->table($table)
676 or die "No schema for table $table found - ".
677 "do you need to create it or run dbdef-create?";
678 my $pkey = $dbdef_table->primary_key
679 or die "No primary key for table $table";
681 return qsearchs($table, { $pkey => $pkey_value });
684 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
686 Experimental JOINed search method. Using this method, you can execute a
687 single SELECT spanning multiple tables, and cache the results for subsequent
688 method calls. Interface will almost definately change in an incompatible
696 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
697 my $cache = FS::SearchCache->new( $ptable, $pkey );
700 grep { !$saw{$_->getfield($pkey)}++ }
701 qsearch($table, $record, $select, $extra_sql, $cache )
705 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
707 Same as qsearch, except that if more than one record matches, it B<carp>s but
708 returns the first. If this happens, you either made a logic error in asking
709 for a single item, or your data is corrupted.
713 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
715 my(@result) = qsearch(@_);
716 cluck "warning: Multiple records in scalar search ($table)"
717 if scalar(@result) > 1;
718 #should warn more vehemently if the search was on a primary key?
719 scalar(@result) ? ($result[0]) : ();
730 Returns the table name.
735 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
742 Returns the DBIx::DBSchema::Table object for the table.
748 my($table)=$self->table;
749 dbdef->table($table);
754 Returns the primary key for the table.
760 my $pkey = $self->dbdef_table->primary_key;
763 =item get, getfield COLUMN
765 Returns the value of the column/field/key COLUMN.
770 my($self,$field) = @_;
771 # to avoid "Use of unitialized value" errors
772 if ( defined ( $self->{Hash}->{$field} ) ) {
773 $self->{Hash}->{$field};
783 =item set, setfield COLUMN, VALUE
785 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
790 my($self,$field,$value) = @_;
791 $self->{'modified'} = 1;
792 $self->{'Hash'}->{$field} = $value;
801 Returns true if the column/field/key COLUMN exists.
806 my($self,$field) = @_;
807 exists($self->{Hash}->{$field});
810 =item AUTLOADED METHODS
812 $record->column is a synonym for $record->get('column');
814 $record->column('value') is a synonym for $record->set('column','value');
821 my($field)=$AUTOLOAD;
823 if ( defined($value) ) {
824 confess "errant AUTOLOAD $field for $self (arg $value)"
825 unless blessed($self) && $self->can('setfield');
826 $self->setfield($field,$value);
828 confess "errant AUTOLOAD $field for $self (no args)"
829 unless blessed($self) && $self->can('getfield');
830 $self->getfield($field);
836 # my $field = $AUTOLOAD;
838 # if ( defined($_[1]) ) {
839 # $_[0]->setfield($field, $_[1]);
841 # $_[0]->getfield($field);
847 Returns a list of the column/value pairs, usually for assigning to a new hash.
849 To make a distinct duplicate of an FS::Record object, you can do:
851 $new = new FS::Record ( $old->table, { $old->hash } );
857 confess $self. ' -> hash: Hash attribute is undefined'
858 unless defined($self->{'Hash'});
859 %{ $self->{'Hash'} };
864 Returns a reference to the column/value hash. This may be deprecated in the
865 future; if there's a reason you can't just use the autoloaded or get/set
877 Returns true if any of this object's values have been modified with set (or via
878 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
888 =item select_for_update
890 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
895 sub select_for_update {
897 my $primary_key = $self->primary_key;
900 'table' => $self->table,
901 'hashref' => { $primary_key => $self->$primary_key() },
902 'extra_sql' => 'FOR UPDATE',
908 Locks this table with a database-driver specific lock method. This is used
909 as a mutex in order to do a duplicate search.
911 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
913 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
915 Errors are fatal; no useful return value.
917 Note: To use this method for new tables other than svc_acct and svc_phone,
918 edit freeside-upgrade and add those tables to the duplicate_lock list.
924 my $table = $self->table;
926 warn "$me locking $table table\n" if $DEBUG;
928 if ( driver_name =~ /^Pg/i ) {
930 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
933 } elsif ( driver_name =~ /^mysql/i ) {
935 dbh->do("SELECT * FROM duplicate_lock
936 WHERE lockname = '$table'
938 ) or die dbh->errstr;
942 die "unknown database ". driver_name. "; don't know how to lock table";
946 warn "$me acquired $table table lock\n" if $DEBUG;
952 Inserts this record to the database. If there is an error, returns the error,
953 otherwise returns false.
961 warn "$self -> insert" if $DEBUG;
963 my $error = $self->check;
964 return $error if $error;
966 #single-field unique keys are given a value if false
967 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
968 foreach ( $self->dbdef_table->unique_singles) {
969 $self->unique($_) unless $self->getfield($_);
972 #and also the primary key, if the database isn't going to
973 my $primary_key = $self->dbdef_table->primary_key;
975 if ( $primary_key ) {
976 my $col = $self->dbdef_table->column($primary_key);
979 uc($col->type) =~ /^(BIG)?SERIAL\d?/
980 || ( driver_name eq 'Pg'
981 && defined($col->default)
982 && $col->quoted_default =~ /^nextval\(/i
984 || ( driver_name eq 'mysql'
985 && defined($col->local)
986 && $col->local =~ /AUTO_INCREMENT/i
988 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
991 my $table = $self->table;
993 # Encrypt before the database
994 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
995 && scalar( eval '@FS::'. $table . '::encrypted_fields')
996 && $conf->exists('encryption')
998 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
999 $self->{'saved'} = $self->getfield($field);
1000 $self->setfield($field, $self->encrypt($self->getfield($field)));
1004 #false laziness w/delete
1006 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1009 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1012 my $statement = "INSERT INTO $table ";
1013 if ( @real_fields ) {
1016 join( ', ', @real_fields ).
1018 join( ', ', @values ).
1022 $statement .= 'DEFAULT VALUES';
1024 warn "[debug]$me $statement\n" if $DEBUG > 1;
1025 my $sth = dbh->prepare($statement) or return dbh->errstr;
1027 local $SIG{HUP} = 'IGNORE';
1028 local $SIG{INT} = 'IGNORE';
1029 local $SIG{QUIT} = 'IGNORE';
1030 local $SIG{TERM} = 'IGNORE';
1031 local $SIG{TSTP} = 'IGNORE';
1032 local $SIG{PIPE} = 'IGNORE';
1034 $sth->execute or return $sth->errstr;
1036 # get inserted id from the database, if applicable & needed
1037 if ( $db_seq && ! $self->getfield($primary_key) ) {
1038 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1042 if ( driver_name eq 'Pg' ) {
1044 #my $oid = $sth->{'pg_oid_status'};
1045 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1047 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1048 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1049 dbh->rollback if $FS::UID::AutoCommit;
1050 return "can't parse $table.$primary_key default value".
1051 " for sequence name: $default";
1055 my $i_sql = "SELECT currval('$sequence')";
1056 my $i_sth = dbh->prepare($i_sql) or do {
1057 dbh->rollback if $FS::UID::AutoCommit;
1060 $i_sth->execute() or do { #$i_sth->execute($oid)
1061 dbh->rollback if $FS::UID::AutoCommit;
1062 return $i_sth->errstr;
1064 $insertid = $i_sth->fetchrow_arrayref->[0];
1066 } elsif ( driver_name eq 'mysql' ) {
1068 $insertid = dbh->{'mysql_insertid'};
1069 # work around mysql_insertid being null some of the time, ala RT :/
1070 unless ( $insertid ) {
1071 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1072 "using SELECT LAST_INSERT_ID();";
1073 my $i_sql = "SELECT LAST_INSERT_ID()";
1074 my $i_sth = dbh->prepare($i_sql) or do {
1075 dbh->rollback if $FS::UID::AutoCommit;
1078 $i_sth->execute or do {
1079 dbh->rollback if $FS::UID::AutoCommit;
1080 return $i_sth->errstr;
1082 $insertid = $i_sth->fetchrow_arrayref->[0];
1087 dbh->rollback if $FS::UID::AutoCommit;
1088 return "don't know how to retreive inserted ids from ". driver_name.
1089 ", try using counterfiles (maybe run dbdef-create?)";
1093 $self->setfield($primary_key, $insertid);
1097 my @virtual_fields =
1098 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1099 $self->virtual_fields;
1100 if (@virtual_fields) {
1101 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
1103 my $vfieldpart = $self->vfieldpart_hashref;
1105 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1108 my $v_sth = dbh->prepare($v_statement) or do {
1109 dbh->rollback if $FS::UID::AutoCommit;
1113 foreach (keys(%v_values)) {
1114 $v_sth->execute($self->getfield($primary_key),
1118 dbh->rollback if $FS::UID::AutoCommit;
1119 return $v_sth->errstr;
1126 if ( defined dbdef->table('h_'. $table) ) {
1127 my $h_statement = $self->_h_statement('insert');
1128 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1129 $h_sth = dbh->prepare($h_statement) or do {
1130 dbh->rollback if $FS::UID::AutoCommit;
1136 $h_sth->execute or return $h_sth->errstr if $h_sth;
1138 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1140 # Now that it has been saved, reset the encrypted fields so that $new
1141 # can still be used.
1142 foreach my $field (keys %{$saved}) {
1143 $self->setfield($field, $saved->{$field});
1151 Depriciated (use insert instead).
1156 cluck "warning: FS::Record::add deprecated!";
1157 insert @_; #call method in this scope
1162 Delete this record from the database. If there is an error, returns the error,
1163 otherwise returns false.
1170 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1172 $self->getfield($_) eq ''
1173 #? "( $_ IS NULL OR $_ = \"\" )"
1174 ? ( driver_name eq 'Pg'
1176 : "( $_ IS NULL OR $_ = \"\" )"
1178 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1179 } ( $self->dbdef_table->primary_key )
1180 ? ( $self->dbdef_table->primary_key)
1181 : real_fields($self->table)
1183 warn "[debug]$me $statement\n" if $DEBUG > 1;
1184 my $sth = dbh->prepare($statement) or return dbh->errstr;
1187 if ( defined dbdef->table('h_'. $self->table) ) {
1188 my $h_statement = $self->_h_statement('delete');
1189 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1190 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1195 my $primary_key = $self->dbdef_table->primary_key;
1198 my $vfp = $self->vfieldpart_hashref;
1199 foreach($self->virtual_fields) {
1200 next if $self->getfield($_) eq '';
1201 unless(@del_vfields) {
1202 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1203 $v_sth = dbh->prepare($st) or return dbh->errstr;
1205 push @del_vfields, $_;
1208 local $SIG{HUP} = 'IGNORE';
1209 local $SIG{INT} = 'IGNORE';
1210 local $SIG{QUIT} = 'IGNORE';
1211 local $SIG{TERM} = 'IGNORE';
1212 local $SIG{TSTP} = 'IGNORE';
1213 local $SIG{PIPE} = 'IGNORE';
1215 my $rc = $sth->execute or return $sth->errstr;
1216 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1217 $h_sth->execute or return $h_sth->errstr if $h_sth;
1218 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1219 or return $v_sth->errstr
1220 foreach (@del_vfields);
1222 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1224 #no need to needlessly destoy the data either (causes problems actually)
1225 #undef $self; #no need to keep object!
1232 Depriciated (use delete instead).
1237 cluck "warning: FS::Record::del deprecated!";
1238 &delete(@_); #call method in this scope
1241 =item replace OLD_RECORD
1243 Replace the OLD_RECORD with this one in the database. If there is an error,
1244 returns the error, otherwise returns false.
1249 my ($new, $old) = (shift, shift);
1251 $old = $new->replace_old unless defined($old);
1253 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1255 if ( $new->can('replace_check') ) {
1256 my $error = $new->replace_check($old);
1257 return $error if $error;
1260 return "Records not in same table!" unless $new->table eq $old->table;
1262 my $primary_key = $old->dbdef_table->primary_key;
1263 return "Can't change primary key $primary_key ".
1264 'from '. $old->getfield($primary_key).
1265 ' to ' . $new->getfield($primary_key)
1267 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1269 my $error = $new->check;
1270 return $error if $error;
1272 # Encrypt for replace
1274 if ( $conf->exists('encryption')
1275 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1276 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1278 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1279 $saved->{$field} = $new->getfield($field);
1280 $new->setfield($field, $new->encrypt($new->getfield($field)));
1284 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1285 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1286 ? ($_, $new->getfield($_)) : () } $old->fields;
1288 unless (keys(%diff) || $no_update_diff ) {
1289 carp "[warning]$me $new -> replace $old: records identical"
1290 unless $nowarn_identical;
1294 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1296 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1297 } real_fields($old->table)
1302 if ( $old->getfield($_) eq '' ) {
1304 #false laziness w/qsearch
1305 if ( driver_name eq 'Pg' ) {
1306 my $type = $old->dbdef_table->column($_)->type;
1307 if ( $type =~ /(int|(big)?serial)/i ) {
1310 qq-( $_ IS NULL OR $_ = '' )-;
1313 qq-( $_ IS NULL OR $_ = "" )-;
1317 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1320 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1323 warn "[debug]$me $statement\n" if $DEBUG > 1;
1324 my $sth = dbh->prepare($statement) or return dbh->errstr;
1327 if ( defined dbdef->table('h_'. $old->table) ) {
1328 my $h_old_statement = $old->_h_statement('replace_old');
1329 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1330 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1336 if ( defined dbdef->table('h_'. $new->table) ) {
1337 my $h_new_statement = $new->_h_statement('replace_new');
1338 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1339 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1344 # For virtual fields we have three cases with different SQL
1345 # statements: add, replace, delete
1349 my (@add_vfields, @rep_vfields, @del_vfields);
1350 my $vfp = $old->vfieldpart_hashref;
1351 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1352 if($diff{$_} eq '') {
1354 unless(@del_vfields) {
1355 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1356 "AND vfieldpart = ?";
1357 warn "[debug]$me $st\n" if $DEBUG > 2;
1358 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1360 push @del_vfields, $_;
1361 } elsif($old->getfield($_) eq '') {
1363 unless(@add_vfields) {
1364 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1366 warn "[debug]$me $st\n" if $DEBUG > 2;
1367 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1369 push @add_vfields, $_;
1372 unless(@rep_vfields) {
1373 my $st = "UPDATE virtual_field SET value = ? ".
1374 "WHERE recnum = ? AND vfieldpart = ?";
1375 warn "[debug]$me $st\n" if $DEBUG > 2;
1376 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1378 push @rep_vfields, $_;
1382 local $SIG{HUP} = 'IGNORE';
1383 local $SIG{INT} = 'IGNORE';
1384 local $SIG{QUIT} = 'IGNORE';
1385 local $SIG{TERM} = 'IGNORE';
1386 local $SIG{TSTP} = 'IGNORE';
1387 local $SIG{PIPE} = 'IGNORE';
1389 my $rc = $sth->execute or return $sth->errstr;
1390 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1391 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1392 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1394 $v_del_sth->execute($old->getfield($primary_key),
1396 or return $v_del_sth->errstr
1397 foreach(@del_vfields);
1399 $v_add_sth->execute($new->getfield($_),
1400 $old->getfield($primary_key),
1402 or return $v_add_sth->errstr
1403 foreach(@add_vfields);
1405 $v_rep_sth->execute($new->getfield($_),
1406 $old->getfield($primary_key),
1408 or return $v_rep_sth->errstr
1409 foreach(@rep_vfields);
1411 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1413 # Now that it has been saved, reset the encrypted fields so that $new
1414 # can still be used.
1415 foreach my $field (keys %{$saved}) {
1416 $new->setfield($field, $saved->{$field});
1424 my( $self ) = shift;
1425 warn "[$me] replace called with no arguments; autoloading old record\n"
1428 my $primary_key = $self->dbdef_table->primary_key;
1429 if ( $primary_key ) {
1430 $self->by_key( $self->$primary_key() ) #this is what's returned
1431 or croak "can't find ". $self->table. ".$primary_key ".
1432 $self->$primary_key();
1434 croak $self->table. " has no primary key; pass old record as argument";
1441 Depriciated (use replace instead).
1446 cluck "warning: FS::Record::rep deprecated!";
1447 replace @_; #call method in this scope
1452 Checks virtual fields (using check_blocks). Subclasses should still provide
1453 a check method to validate real fields, foreign keys, etc., and call this
1454 method via $self->SUPER::check.
1456 (FIXME: Should this method try to make sure that it I<is> being called from
1457 a subclass's check method, to keep the current semantics as far as possible?)
1462 #confess "FS::Record::check not implemented; supply one in subclass!";
1465 foreach my $field ($self->virtual_fields) {
1466 for ($self->getfield($field)) {
1467 # See notes on check_block in FS::part_virtual_field.
1468 eval $self->pvf($field)->check_block;
1470 #this is bad, probably want to follow the stack backtrace up and see
1472 my $err = "Fatal error checking $field for $self";
1474 return "$err (see log for backtrace): $@";
1477 $self->setfield($field, $_);
1483 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1485 Processes a batch import as a queued JSRPC job
1487 JOB is an FS::queue entry.
1489 OPTIONS_HASHREF can have the following keys:
1495 Table name (required).
1499 Listref of field names for static fields. They will be given values from the
1500 PARAMS hashref and passed as a "params" hashref to batch_import.
1504 Formats hashref. Keys are field names, values are listrefs that define the
1507 Each listref value can be a column name or a code reference. Coderefs are run
1508 with the row object, data and a FS::Conf object as the three parameters.
1509 For example, this coderef does the same thing as using the "columnname" string:
1512 my( $record, $data, $conf ) = @_;
1513 $record->columnname( $data );
1516 Coderefs are run after all "column name" fields are assigned.
1520 Optional format hashref of types. Keys are field names, values are "csv",
1521 "xls" or "fixedlength". Overrides automatic determination of file type
1524 =item format_headers
1526 Optional format hashref of header lines. Keys are field names, values are 0
1527 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1530 =item format_sep_chars
1532 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1533 CSV separation character.
1535 =item format_fixedlenth_formats
1537 Optional format hashref of fixed length format defintiions. Keys are field
1538 names, values Parse::FixedLength listrefs of field definitions.
1542 Set true to default to CSV file type if the filename does not contain a
1543 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1548 PARAMS is a base64-encoded Storable string containing the POSTed data as
1549 a hash ref. It normally contains at least one field, "uploaded files",
1550 generated by /elements/file-upload.html and containing the list of uploaded
1551 files. Currently only supports a single file named "file".
1555 use Storable qw(thaw);
1558 sub process_batch_import {
1559 my($job, $opt) = ( shift, shift );
1561 my $table = $opt->{table};
1562 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1563 my %formats = %{ $opt->{formats} };
1565 my $param = thaw(decode_base64(shift));
1566 warn Dumper($param) if $DEBUG;
1568 my $files = $param->{'uploaded_files'}
1569 or die "No files provided.\n";
1571 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1573 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1574 my $file = $dir. $files{'file'};
1579 formats => \%formats,
1580 format_types => $opt->{format_types},
1581 format_headers => $opt->{format_headers},
1582 format_sep_chars => $opt->{format_sep_chars},
1583 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1584 format_row_callbacks => $opt->{format_row_callbacks},
1589 format => $param->{format},
1590 params => { map { $_ => $param->{$_} } @pass_params },
1592 default_csv => $opt->{default_csv},
1595 if ( $opt->{'batch_namecol'} ) {
1596 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1597 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1600 my $error = FS::Record::batch_import( \%iopt );
1604 die "$error\n" if $error;
1607 =item batch_import PARAM_HASHREF
1609 Class method for batch imports. Available params:
1615 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1621 =item format_headers
1623 =item format_sep_chars
1625 =item format_fixedlength_formats
1627 =item format_row_callbacks
1629 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1631 =item postinsert_callback
1637 FS::queue object, will be updated with progress
1643 csv, xls or fixedlength
1654 warn "$me batch_import call with params: \n". Dumper($param)
1657 my $table = $param->{table};
1659 my $job = $param->{job};
1660 my $file = $param->{file};
1661 my $params = $param->{params} || {};
1663 my( $type, $header, $sep_char, $fixedlength_format, $row_callback, @fields );
1664 my $postinsert_callback = '';
1665 if ( $param->{'format'} ) {
1667 my $format = $param->{'format'};
1668 my $formats = $param->{formats};
1669 die "unknown format $format" unless exists $formats->{ $format };
1671 $type = $param->{'format_types'}
1672 ? $param->{'format_types'}{ $format }
1673 : $param->{type} || 'csv';
1676 $header = $param->{'format_headers'}
1677 ? $param->{'format_headers'}{ $param->{'format'} }
1680 $sep_char = $param->{'format_sep_chars'}
1681 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1684 $fixedlength_format =
1685 $param->{'format_fixedlength_formats'}
1686 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1690 $param->{'format_row_callbacks'}
1691 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1694 @fields = @{ $formats->{ $format } };
1696 } elsif ( $param->{'fields'} ) {
1698 $type = ''; #infer from filename
1701 $fixedlength_format = '';
1703 @fields = @{ $param->{'fields'} };
1705 $postinsert_callback = $param->{'postinsert_callback'}
1706 if $param->{'postinsert_callback'}
1709 die "neither format nor fields specified";
1712 #my $file = $param->{file};
1715 if ( $file =~ /\.(\w+)$/i ) {
1719 warn "can't parse file type from filename $file; defaulting to CSV";
1723 if $param->{'default_csv'} && $type ne 'xls';
1731 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1733 if ( $type eq 'csv' ) {
1736 $attr{sep_char} = $sep_char if $sep_char;
1737 $parser = new Text::CSV_XS \%attr;
1739 } elsif ( $type eq 'fixedlength' ) {
1741 eval "use Parse::FixedLength;";
1743 $parser = new Parse::FixedLength $fixedlength_format;
1746 die "Unknown file type $type\n";
1749 @buffer = split(/\r?\n/, slurp($file) );
1750 splice(@buffer, 0, ($header || 0) );
1751 $count = scalar(@buffer);
1753 } elsif ( $type eq 'xls' ) {
1755 eval "use Spreadsheet::ParseExcel;";
1758 eval "use DateTime::Format::Excel;";
1759 #for now, just let the error be thrown if it is used, since only CDR
1760 # formats bill_west and troop use it, not other excel-parsing things
1763 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1765 $parser = $excel->{Worksheet}[0]; #first sheet
1767 $count = $parser->{MaxRow} || $parser->{MinRow};
1770 $row = $header || 0;
1773 die "Unknown file type $type\n";
1778 local $SIG{HUP} = 'IGNORE';
1779 local $SIG{INT} = 'IGNORE';
1780 local $SIG{QUIT} = 'IGNORE';
1781 local $SIG{TERM} = 'IGNORE';
1782 local $SIG{TSTP} = 'IGNORE';
1783 local $SIG{PIPE} = 'IGNORE';
1785 my $oldAutoCommit = $FS::UID::AutoCommit;
1786 local $FS::UID::AutoCommit = 0;
1789 #my $params = $param->{params} || {};
1790 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1791 my $batch_col = $param->{'batch_keycol'};
1793 my $batch_class = 'FS::'. $param->{'batch_table'};
1794 my $batch = $batch_class->new({
1795 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1797 my $error = $batch->insert;
1799 $dbh->rollback if $oldAutoCommit;
1800 return "can't insert batch record: $error";
1802 #primary key via dbdef? (so the column names don't have to match)
1803 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1805 $params->{ $batch_col } = $batch_value;
1808 #my $job = $param->{job};
1811 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1815 if ( $type eq 'csv' ) {
1817 last unless scalar(@buffer);
1818 $line = shift(@buffer);
1820 next if $line =~ /^\s*$/; #skip empty lines
1822 $line = &{$row_callback}($line) if $row_callback;
1824 $parser->parse($line) or do {
1825 $dbh->rollback if $oldAutoCommit;
1826 return "can't parse: ". $parser->error_input();
1828 @columns = $parser->fields();
1830 } elsif ( $type eq 'fixedlength' ) {
1832 @columns = $parser->parse($line);
1834 } elsif ( $type eq 'xls' ) {
1836 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1837 || ! $parser->{Cells}[$row];
1839 my @row = @{ $parser->{Cells}[$row] };
1840 @columns = map $_->{Val}, @row;
1843 #warn $z++. ": $_\n" for @columns;
1846 die "Unknown file type $type\n";
1850 my %hash = %$params;
1852 foreach my $field ( @fields ) {
1854 my $value = shift @columns;
1856 if ( ref($field) eq 'CODE' ) {
1857 #&{$field}(\%hash, $value);
1858 push @later, $field, $value;
1860 #??? $hash{$field} = $value if length($value);
1861 $hash{$field} = $value if defined($value) && length($value);
1866 #my $table = $param->{table};
1867 my $class = "FS::$table";
1869 my $record = $class->new( \%hash );
1872 while ( scalar(@later) ) {
1873 my $sub = shift @later;
1874 my $data = shift @later;
1876 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
1879 $dbh->rollback if $oldAutoCommit;
1880 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
1882 last if exists( $param->{skiprow} );
1884 next if exists( $param->{skiprow} );
1886 my $error = $record->insert;
1889 $dbh->rollback if $oldAutoCommit;
1890 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1896 if ( $postinsert_callback ) {
1897 my $error = &{$postinsert_callback}($record, $param);
1899 $dbh->rollback if $oldAutoCommit;
1900 return "postinsert_callback error". ( $line ? " for $line" : '' ).
1905 if ( $job && time - $min_sec > $last ) { #progress bar
1906 $job->update_statustext( int(100 * $imported / $count) );
1912 unless ( $imported || $param->{empty_ok} ) {
1913 $dbh->rollback if $oldAutoCommit;
1914 return "Empty file!";
1917 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1924 my( $self, $action, $time ) = @_;
1928 my %nohistory = map { $_=>1 } $self->nohistory_fields;
1931 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1932 real_fields($self->table);
1935 # If we're encrypting then don't store the payinfo in the history
1936 if ( $conf && $conf->exists('encryption') ) {
1937 @fields = grep { $_ ne 'payinfo' } @fields;
1940 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1942 "INSERT INTO h_". $self->table. " ( ".
1943 join(', ', qw(history_date history_user history_action), @fields ).
1945 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1952 B<Warning>: External use is B<deprecated>.
1954 Replaces COLUMN in record with a unique number, using counters in the
1955 filesystem. Used by the B<insert> method on single-field unique columns
1956 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1957 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1959 Returns the new value.
1964 my($self,$field) = @_;
1965 my($table)=$self->table;
1967 croak "Unique called on field $field, but it is ",
1968 $self->getfield($field),
1970 if $self->getfield($field);
1972 #warn "table $table is tainted" if is_tainted($table);
1973 #warn "field $field is tainted" if is_tainted($field);
1975 my($counter) = new File::CounterFile "$table.$field",0;
1977 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1979 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1982 my $index = $counter->inc;
1983 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1985 $index =~ /^(\d*)$/;
1988 $self->setfield($field,$index);
1992 =item ut_float COLUMN
1994 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1995 null. If there is an error, returns the error, otherwise returns false.
2000 my($self,$field)=@_ ;
2001 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2002 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2003 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2004 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2005 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2006 $self->setfield($field,$1);
2009 =item ut_floatn COLUMN
2011 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2012 null. If there is an error, returns the error, otherwise returns false.
2016 #false laziness w/ut_ipn
2018 my( $self, $field ) = @_;
2019 if ( $self->getfield($field) =~ /^()$/ ) {
2020 $self->setfield($field,'');
2023 $self->ut_float($field);
2027 =item ut_sfloat COLUMN
2029 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2030 May not be null. If there is an error, returns the error, otherwise returns
2036 my($self,$field)=@_ ;
2037 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2038 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2039 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2040 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2041 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2042 $self->setfield($field,$1);
2045 =item ut_sfloatn COLUMN
2047 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2048 null. If there is an error, returns the error, otherwise returns false.
2053 my( $self, $field ) = @_;
2054 if ( $self->getfield($field) =~ /^()$/ ) {
2055 $self->setfield($field,'');
2058 $self->ut_sfloat($field);
2062 =item ut_snumber COLUMN
2064 Check/untaint signed numeric data (whole numbers). If there is an error,
2065 returns the error, otherwise returns false.
2070 my($self, $field) = @_;
2071 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2072 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2073 $self->setfield($field, "$1$2");
2077 =item ut_snumbern COLUMN
2079 Check/untaint signed numeric data (whole numbers). If there is an error,
2080 returns the error, otherwise returns false.
2085 my($self, $field) = @_;
2086 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2087 or return "Illegal (numeric) $field: ". $self->getfield($field);
2089 return "Illegal (numeric) $field: ". $self->getfield($field)
2092 $self->setfield($field, "$1$2");
2096 =item ut_number COLUMN
2098 Check/untaint simple numeric data (whole numbers). May not be null. If there
2099 is an error, returns the error, otherwise returns false.
2104 my($self,$field)=@_;
2105 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2106 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2107 $self->setfield($field,$1);
2111 =item ut_numbern COLUMN
2113 Check/untaint simple numeric data (whole numbers). May be null. If there is
2114 an error, returns the error, otherwise returns false.
2119 my($self,$field)=@_;
2120 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2121 or return "Illegal (numeric) $field: ". $self->getfield($field);
2122 $self->setfield($field,$1);
2126 =item ut_money COLUMN
2128 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2129 is an error, returns the error, otherwise returns false.
2134 my($self,$field)=@_;
2135 $self->setfield($field, 0) if $self->getfield($field) eq '';
2136 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
2137 or return "Illegal (money) $field: ". $self->getfield($field);
2138 #$self->setfield($field, "$1$2$3" || 0);
2139 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2143 =item ut_moneyn COLUMN
2145 Check/untaint monetary numbers. May be negative. If there
2146 is an error, returns the error, otherwise returns false.
2151 my($self,$field)=@_;
2152 if ($self->getfield($field) eq '') {
2153 $self->setfield($field, '');
2156 $self->ut_money($field);
2159 =item ut_text COLUMN
2161 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2162 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2163 May not be null. If there is an error, returns the error, otherwise returns
2169 my($self,$field)=@_;
2170 #warn "msgcat ". \&msgcat. "\n";
2171 #warn "notexist ". \¬exist. "\n";
2172 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2173 $self->getfield($field)
2174 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
2175 or return gettext('illegal_or_empty_text'). " $field: ".
2176 $self->getfield($field);
2177 $self->setfield($field,$1);
2181 =item ut_textn COLUMN
2183 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2184 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
2185 May be null. If there is an error, returns the error, otherwise returns false.
2190 my($self,$field)=@_;
2191 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2192 $self->ut_text($field);
2195 =item ut_alpha COLUMN
2197 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2198 an error, returns the error, otherwise returns false.
2203 my($self,$field)=@_;
2204 $self->getfield($field) =~ /^(\w+)$/
2205 or return "Illegal or empty (alphanumeric) $field: ".
2206 $self->getfield($field);
2207 $self->setfield($field,$1);
2211 =item ut_alphan COLUMN
2213 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2214 error, returns the error, otherwise returns false.
2219 my($self,$field)=@_;
2220 $self->getfield($field) =~ /^(\w*)$/
2221 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2222 $self->setfield($field,$1);
2226 =item ut_alphasn COLUMN
2228 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2229 an error, returns the error, otherwise returns false.
2234 my($self,$field)=@_;
2235 $self->getfield($field) =~ /^([\w ]*)$/
2236 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2237 $self->setfield($field,$1);
2242 =item ut_alpha_lower COLUMN
2244 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2245 there is an error, returns the error, otherwise returns false.
2249 sub ut_alpha_lower {
2250 my($self,$field)=@_;
2251 $self->getfield($field) =~ /[[:upper:]]/
2252 and return "Uppercase characters are not permitted in $field";
2253 $self->ut_alpha($field);
2256 =item ut_phonen COLUMN [ COUNTRY ]
2258 Check/untaint phone numbers. May be null. If there is an error, returns
2259 the error, otherwise returns false.
2261 Takes an optional two-letter ISO country code; without it or with unsupported
2262 countries, ut_phonen simply calls ut_alphan.
2267 my( $self, $field, $country ) = @_;
2268 return $self->ut_alphan($field) unless defined $country;
2269 my $phonen = $self->getfield($field);
2270 if ( $phonen eq '' ) {
2271 $self->setfield($field,'');
2272 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2274 $phonen = $conf->config('cust_main-default_areacode').$phonen
2275 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2276 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2277 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2278 $phonen = "$1-$2-$3";
2279 $phonen .= " x$4" if $4;
2280 $self->setfield($field,$phonen);
2282 warn "warning: don't know how to check phone numbers for country $country";
2283 return $self->ut_textn($field);
2290 Check/untaint hexadecimal values.
2295 my($self, $field) = @_;
2296 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2297 or return "Illegal (hex) $field: ". $self->getfield($field);
2298 $self->setfield($field, uc($1));
2302 =item ut_hexn COLUMN
2304 Check/untaint hexadecimal values. May be null.
2309 my($self, $field) = @_;
2310 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2311 or return "Illegal (hex) $field: ". $self->getfield($field);
2312 $self->setfield($field, uc($1));
2317 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2323 my( $self, $field ) = @_;
2324 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2325 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2326 or return "Illegal (IP address) $field: ". $self->getfield($field);
2327 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2328 $self->setfield($field, "$1.$2.$3.$4");
2334 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2335 to 127.0.0.1. May be null.
2340 my( $self, $field ) = @_;
2341 if ( $self->getfield($field) =~ /^()$/ ) {
2342 $self->setfield($field,'');
2345 $self->ut_ip($field);
2349 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2351 Check/untaint coordinates.
2352 Accepts the following forms:
2362 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2363 The latter form (that is, the MMM are thousands of minutes) is
2364 assumed if the "MMM" is exactly three digits or two digits > 59.
2366 To be safe, just use the DDD.DDDDD form.
2368 If LOWER or UPPER are specified, then the coordinate is checked
2369 for lower and upper bounds, respectively.
2375 my ($self, $field) = (shift, shift);
2377 my $lower = shift if scalar(@_);
2378 my $upper = shift if scalar(@_);
2379 my $coord = $self->getfield($field);
2380 my $neg = $coord =~ s/^(-)//;
2382 my ($d, $m, $s) = (0, 0, 0);
2385 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2386 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2387 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2389 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2392 return "Invalid (coordinate with minutes > 59) $field: "
2393 . $self->getfield($field);
2396 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2398 if (defined($lower) and ($coord < $lower)) {
2399 return "Invalid (coordinate < $lower) $field: "
2400 . $self->getfield($field);;
2403 if (defined($upper) and ($coord > $upper)) {
2404 return "Invalid (coordinate > $upper) $field: "
2405 . $self->getfield($field);;
2408 $self->setfield($field, $coord);
2412 return "Invalid (coordinate) $field: " . $self->getfield($field);
2416 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2418 Same as ut_coord, except optionally null.
2424 my ($self, $field) = (shift, shift);
2426 if ($self->getfield($field) =~ /^$/) {
2429 return $self->ut_coord($field, @_);
2435 =item ut_domain COLUMN
2437 Check/untaint host and domain names.
2442 my( $self, $field ) = @_;
2443 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2444 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2445 or return "Illegal (domain) $field: ". $self->getfield($field);
2446 $self->setfield($field,$1);
2450 =item ut_name COLUMN
2452 Check/untaint proper names; allows alphanumerics, spaces and the following
2453 punctuation: , . - '
2460 my( $self, $field ) = @_;
2461 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2462 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2463 $self->setfield($field,$1);
2469 Check/untaint zip codes.
2473 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2476 my( $self, $field, $country ) = @_;
2478 if ( $country eq 'US' ) {
2480 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2481 or return gettext('illegal_zip'). " $field for country $country: ".
2482 $self->getfield($field);
2483 $self->setfield($field, $1);
2485 } elsif ( $country eq 'CA' ) {
2487 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2488 or return gettext('illegal_zip'). " $field for country $country: ".
2489 $self->getfield($field);
2490 $self->setfield($field, "$1 $2");
2494 if ( $self->getfield($field) =~ /^\s*$/
2495 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2498 $self->setfield($field,'');
2500 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2501 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2502 $self->setfield($field,$1);
2510 =item ut_country COLUMN
2512 Check/untaint country codes. Country names are changed to codes, if possible -
2513 see L<Locale::Country>.
2518 my( $self, $field ) = @_;
2519 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2520 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2521 && country2code($1) ) {
2522 $self->setfield($field,uc(country2code($1)));
2525 $self->getfield($field) =~ /^(\w\w)$/
2526 or return "Illegal (country) $field: ". $self->getfield($field);
2527 $self->setfield($field,uc($1));
2531 =item ut_anything COLUMN
2533 Untaints arbitrary data. Be careful.
2538 my( $self, $field ) = @_;
2539 $self->getfield($field) =~ /^(.*)$/s
2540 or return "Illegal $field: ". $self->getfield($field);
2541 $self->setfield($field,$1);
2545 =item ut_enum COLUMN CHOICES_ARRAYREF
2547 Check/untaint a column, supplying all possible choices, like the "enum" type.
2552 my( $self, $field, $choices ) = @_;
2553 foreach my $choice ( @$choices ) {
2554 if ( $self->getfield($field) eq $choice ) {
2555 $self->setfield($field, $choice);
2559 return "Illegal (enum) field $field: ". $self->getfield($field);
2562 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2564 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2565 on the column first.
2569 sub ut_foreign_key {
2570 my( $self, $field, $table, $foreign ) = @_;
2571 return '' if $no_check_foreign;
2572 qsearchs($table, { $foreign => $self->getfield($field) })
2573 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2574 " in $table.$foreign";
2578 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2580 Like ut_foreign_key, except the null value is also allowed.
2584 sub ut_foreign_keyn {
2585 my( $self, $field, $table, $foreign ) = @_;
2586 $self->getfield($field)
2587 ? $self->ut_foreign_key($field, $table, $foreign)
2591 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2593 Checks this column as an agentnum, taking into account the current users's
2594 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2595 right or rights allowing no agentnum.
2599 sub ut_agentnum_acl {
2600 my( $self, $field ) = (shift, shift);
2601 my $null_acl = scalar(@_) ? shift : [];
2602 $null_acl = [ $null_acl ] unless ref($null_acl);
2604 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2605 return "Illegal agentnum: $error" if $error;
2607 my $curuser = $FS::CurrentUser::CurrentUser;
2609 if ( $self->$field() ) {
2611 return "Access denied"
2612 unless $curuser->agentnum($self->$field());
2616 return "Access denied"
2617 unless grep $curuser->access_right($_), @$null_acl;
2625 =item virtual_fields [ TABLE ]
2627 Returns a list of virtual fields defined for the table. This should not
2628 be exported, and should only be called as an instance or class method.
2632 sub virtual_fields {
2635 $table = $self->table or confess "virtual_fields called on non-table";
2637 confess "Unknown table $table" unless dbdef->table($table);
2639 return () unless dbdef->table('part_virtual_field');
2641 unless ( $virtual_fields_cache{$table} ) {
2642 my $query = 'SELECT name from part_virtual_field ' .
2643 "WHERE dbtable = '$table'";
2645 my $result = $dbh->selectcol_arrayref($query);
2646 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2648 $virtual_fields_cache{$table} = $result;
2651 @{$virtual_fields_cache{$table}};
2656 =item fields [ TABLE ]
2658 This is a wrapper for real_fields and virtual_fields. Code that called
2659 fields before should probably continue to call fields.
2664 my $something = shift;
2666 if($something->isa('FS::Record')) {
2667 $table = $something->table;
2669 $table = $something;
2670 $something = "FS::$table";
2672 return (real_fields($table), $something->virtual_fields());
2675 =item pvf FIELD_NAME
2677 Returns the FS::part_virtual_field object corresponding to a field in the
2678 record (specified by FIELD_NAME).
2683 my ($self, $name) = (shift, shift);
2685 if(grep /^$name$/, $self->virtual_fields) {
2686 return qsearchs('part_virtual_field', { dbtable => $self->table,
2692 =item vfieldpart_hashref TABLE
2694 Returns a hashref of virtual field names and vfieldparts applicable to the given
2699 sub vfieldpart_hashref {
2701 my $table = $self->table;
2703 return {} unless dbdef->table('part_virtual_field');
2706 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2707 "dbtable = '$table'";
2708 my $sth = $dbh->prepare($statement);
2709 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2710 return { map { $_->{name}, $_->{vfieldpart} }
2711 @{$sth->fetchall_arrayref({})} };
2715 =item encrypt($value)
2717 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2719 Returns the encrypted string.
2721 You should generally not have to worry about calling this, as the system handles this for you.
2726 my ($self, $value) = @_;
2729 if ($conf->exists('encryption')) {
2730 if ($self->is_encrypted($value)) {
2731 # Return the original value if it isn't plaintext.
2732 $encrypted = $value;
2735 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2736 # RSA doesn't like the empty string so let's pack it up
2737 # The database doesn't like the RSA data so uuencode it
2738 my $length = length($value)+1;
2739 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2741 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2748 =item is_encrypted($value)
2750 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2756 my ($self, $value) = @_;
2757 # Possible Bug - Some work may be required here....
2759 if ($value =~ /^M/ && length($value) > 80) {
2766 =item decrypt($value)
2768 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2770 You should generally not have to worry about calling this, as the system handles this for you.
2775 my ($self,$value) = @_;
2776 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2777 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2779 if (ref($rsa_decrypt) =~ /::RSA/) {
2780 my $encrypted = unpack ("u*", $value);
2781 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2782 if ($@) {warn "Decryption Failed"};
2790 #Initialize the Module
2791 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2793 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2794 $rsa_module = $conf->config('encryptionmodule');
2798 eval ("require $rsa_module"); # No need to import the namespace
2801 # Initialize Encryption
2802 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2803 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2804 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2807 # Intitalize Decryption
2808 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2809 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2810 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2814 =item h_search ACTION
2816 Given an ACTION, either "insert", or "delete", returns the appropriate history
2817 record corresponding to this record, if any.
2822 my( $self, $action ) = @_;
2824 my $table = $self->table;
2827 my $primary_key = dbdef->table($table)->primary_key;
2830 'table' => "h_$table",
2831 'hashref' => { $primary_key => $self->$primary_key(),
2832 'history_action' => $action,
2840 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2841 appropriate history record corresponding to this record, if any.
2846 my($self, $action) = @_;
2847 my $h = $self->h_search($action);
2848 $h ? $h->history_date : '';
2851 =item scalar_sql SQL [ PLACEHOLDER, ... ]
2853 A class or object method. Executes the sql statement represented by SQL and
2854 returns a scalar representing the result: the first column of the first row.
2856 Dies on bogus SQL. Returns an empty string if no row is returned.
2858 Typically used for statments which return a single value such as "SELECT
2859 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
2864 my($self, $sql) = (shift, shift);
2865 my $sth = dbh->prepare($sql) or die dbh->errstr;
2867 or die "Unexpected error executing statement $sql: ". $sth->errstr;
2868 my $scalar = $sth->fetchrow_arrayref->[0];
2869 defined($scalar) ? $scalar : '';
2878 =item real_fields [ TABLE ]
2880 Returns a list of the real columns in the specified table. Called only by
2881 fields() and other subroutines elsewhere in FS::Record.
2888 my($table_obj) = dbdef->table($table);
2889 confess "Unknown table $table" unless $table_obj;
2890 $table_obj->columns;
2893 =item _quote VALUE, TABLE, COLUMN
2895 This is an internal function used to construct SQL statements. It returns
2896 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2897 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2902 my($value, $table, $column) = @_;
2903 my $column_obj = dbdef->table($table)->column($column);
2904 my $column_type = $column_obj->type;
2905 my $nullable = $column_obj->null;
2907 warn " $table.$column: $value ($column_type".
2908 ( $nullable ? ' NULL' : ' NOT NULL' ).
2909 ")\n" if $DEBUG > 2;
2911 if ( $value eq '' && $nullable ) {
2913 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2914 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2917 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2918 ! $column_type =~ /(char|binary|text)$/i ) {
2920 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
2921 && driver_name eq 'Pg'
2925 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
2926 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
2927 # single-quote the whole mess, and put an "E" in front.
2928 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
2936 This is deprecated. Don't use it.
2938 It returns a hash-type list with the fields of this record's table set true.
2943 carp "warning: hfields is deprecated";
2946 foreach (fields($table)) {
2955 "$_: ". $self->getfield($_). "|"
2956 } (fields($self->table)) );
2959 sub DESTROY { return; }
2963 # #use Carp qw(cluck);
2964 # #cluck "DESTROYING $self";
2965 # warn "DESTROYING $self";
2969 # return ! eval { join('',@_), kill 0; 1; };
2972 =item str2time_sql [ DRIVER_NAME ]
2974 Returns a function to convert to unix time based on database type, such as
2975 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2976 the str2time_sql_closing method to return a closing string rather than just
2977 using a closing parenthesis as previously suggested.
2979 You can pass an optional driver name such as "Pg", "mysql" or
2980 $dbh->{Driver}->{Name} to return a function for that database instead of
2981 the current database.
2986 my $driver = shift || driver_name;
2988 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2989 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2991 warn "warning: unknown database type $driver; guessing how to convert ".
2992 "dates to UNIX timestamps";
2993 return 'EXTRACT(EPOCH FROM ';
2997 =item str2time_sql_closing [ DRIVER_NAME ]
2999 Returns the closing suffix of a function to convert to unix time based on
3000 database type, such as ")::integer" for Pg or ")" for mysql.
3002 You can pass an optional driver name such as "Pg", "mysql" or
3003 $dbh->{Driver}->{Name} to return a function for that database instead of
3004 the current database.
3008 sub str2time_sql_closing {
3009 my $driver = shift || driver_name;
3011 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3015 =item regexp_sql [ DRIVER_NAME ]
3017 Returns the operator to do a regular expression comparison based on database
3018 type, such as '~' for Pg or 'REGEXP' for mysql.
3020 You can pass an optional driver name such as "Pg", "mysql" or
3021 $dbh->{Driver}->{Name} to return a function for that database instead of
3022 the current database.
3027 my $driver = shift || driver_name;
3029 return '~' if $driver =~ /^Pg/i;
3030 return 'REGEXP' if $driver =~ /^mysql/i;
3032 die "don't know how to use regular expressions in ". driver_name." databases";
3036 =item not_regexp_sql [ DRIVER_NAME ]
3038 Returns the operator to do a regular expression negation based on database
3039 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3041 You can pass an optional driver name such as "Pg", "mysql" or
3042 $dbh->{Driver}->{Name} to return a function for that database instead of
3043 the current database.
3047 sub not_regexp_sql {
3048 my $driver = shift || driver_name;
3050 return '!~' if $driver =~ /^Pg/i;
3051 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3053 die "don't know how to use regular expressions in ". driver_name." databases";
3061 This module should probably be renamed, since much of the functionality is
3062 of general use. It is not completely unlike Adapter::DBI (see below).
3064 Exported qsearch and qsearchs should be deprecated in favor of method calls
3065 (against an FS::Record object like the old search and searchs that qsearch
3066 and qsearchs were on top of.)
3068 The whole fields / hfields mess should be removed.
3070 The various WHERE clauses should be subroutined.
3072 table string should be deprecated in favor of DBIx::DBSchema::Table.
3074 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3075 true maps to the database (and WHERE clauses) would also help.
3077 The ut_ methods should ask the dbdef for a default length.
3079 ut_sqltype (like ut_varchar) should all be defined
3081 A fallback check method should be provided which uses the dbdef.
3083 The ut_money method assumes money has two decimal digits.
3085 The Pg money kludge in the new method only strips `$'.
3087 The ut_phonen method only checks US-style phone numbers.
3089 The _quote function should probably use ut_float instead of a regex.
3091 All the subroutines probably should be methods, here or elsewhere.
3093 Probably should borrow/use some dbdef methods where appropriate (like sub
3096 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3097 or allow it to be set. Working around it is ugly any way around - DBI should
3098 be fixed. (only affects RDBMS which return uppercase column names)
3100 ut_zip should take an optional country like ut_phone.
3104 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3106 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.