4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $conf $conf_encryption $me
7 $nowarn_identical $no_update_diff $no_check_foreign
10 use Carp qw(carp cluck croak confess);
11 use Scalar::Util qw( blessed );
12 use File::CounterFile;
15 use File::Slurp qw( slurp );
16 use DBI qw(:sql_types);
17 use DBIx::DBSchema 0.33;
18 use FS::UID qw(dbh getotaker datasrc driver_name);
20 use FS::Schema qw(dbdef);
22 use FS::Msgcat qw(gettext);
23 #use FS::Conf; #dependency loop bs, in install_callback below instead
25 use FS::part_virtual_field;
31 #export dbdef for now... everything else expects to find it here
32 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
33 str2time_sql str2time_sql_closing );
38 $nowarn_identical = 0;
40 $no_check_foreign = 0;
48 $conf_encryption = '';
49 FS::UID->install_callback( sub {
52 $conf = FS::Conf->new;
53 $conf_encryption = $conf->exists('encryption');
54 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
60 FS::Record - Database record objects
65 use FS::Record qw(dbh fields qsearch qsearchs);
67 $record = new FS::Record 'table', \%hash;
68 $record = new FS::Record 'table', { 'column' => 'value', ... };
70 $record = qsearchs FS::Record 'table', \%hash;
71 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
72 @records = qsearch FS::Record 'table', \%hash;
73 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
75 $table = $record->table;
76 $dbdef_table = $record->dbdef_table;
78 $value = $record->get('column');
79 $value = $record->getfield('column');
80 $value = $record->column;
82 $record->set( 'column' => 'value' );
83 $record->setfield( 'column' => 'value' );
84 $record->column('value');
86 %hash = $record->hash;
88 $hashref = $record->hashref;
90 $error = $record->insert;
92 $error = $record->delete;
94 $error = $new_record->replace($old_record);
96 # external use deprecated - handled by the database (at least for Pg, mysql)
97 $value = $record->unique('column');
99 $error = $record->ut_float('column');
100 $error = $record->ut_floatn('column');
101 $error = $record->ut_number('column');
102 $error = $record->ut_numbern('column');
103 $error = $record->ut_snumber('column');
104 $error = $record->ut_snumbern('column');
105 $error = $record->ut_money('column');
106 $error = $record->ut_text('column');
107 $error = $record->ut_textn('column');
108 $error = $record->ut_alpha('column');
109 $error = $record->ut_alphan('column');
110 $error = $record->ut_phonen('column');
111 $error = $record->ut_anything('column');
112 $error = $record->ut_name('column');
114 $quoted_value = _quote($value,'table','field');
117 $fields = hfields('table');
118 if ( $fields->{Field} ) { # etc.
120 @fields = fields 'table'; #as a subroutine
121 @fields = $record->fields; #as a method call
126 (Mostly) object-oriented interface to database records. Records are currently
127 implemented on top of DBI. FS::Record is intended as a base class for
128 table-specific classes to inherit from, i.e. FS::cust_main.
134 =item new [ TABLE, ] HASHREF
136 Creates a new record. It doesn't store it in the database, though. See
137 L<"insert"> for that.
139 Note that the object stores this hash reference, not a distinct copy of the
140 hash it points to. You can ask the object for a copy with the I<hash>
143 TABLE can only be omitted when a dervived class overrides the table method.
149 my $class = ref($proto) || $proto;
151 bless ($self, $class);
153 unless ( defined ( $self->table ) ) {
154 $self->{'Table'} = shift;
155 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
158 $self->{'Hash'} = shift;
160 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
161 $self->{'Hash'}{$field}='';
164 $self->_rebless if $self->can('_rebless');
166 $self->{'modified'} = 0;
168 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
175 my $class = ref($proto) || $proto;
177 bless ($self, $class);
179 $self->{'Table'} = shift unless defined ( $self->table );
181 my $hashref = $self->{'Hash'} = shift;
183 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
184 my $obj = $cache->cache->{$hashref->{$cache->key}};
185 $obj->_cache($hashref, $cache) if $obj->can('_cache');
188 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
195 my $class = ref($proto) || $proto;
197 bless ($self, $class);
198 if ( defined $self->table ) {
199 cluck "create constructor is deprecated, use new!";
202 croak "FS::Record::create called (not from a subclass)!";
206 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
208 Searches the database for all records matching (at least) the key/value pairs
209 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
210 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
213 The preferred usage is to pass a hash reference of named parameters:
215 my @records = qsearch( {
216 'table' => 'table_name',
217 'hashref' => { 'field' => 'value'
218 'field' => { 'op' => '<',
223 #these are optional...
225 'extra_sql' => 'AND field ',
226 'order_by' => 'ORDER BY something',
227 #'cache_obj' => '', #optional
228 'addl_from' => 'LEFT JOIN othtable USING ( field )',
233 Much code still uses old-style positional parameters, this is also probably
234 fine in the common case where there are only two parameters:
236 my @records = qsearch( 'table', { 'field' => 'value' } );
238 ###oops, argh, FS::Record::new only lets us create database fields.
239 #Normal behaviour if SELECT is not specified is `*', as in
240 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
241 #feature where you can specify SELECT - remember, the objects returned,
242 #although blessed into the appropriate `FS::TABLE' package, will only have the
243 #fields you specify. This might have unwanted results if you then go calling
244 #regular FS::TABLE methods
249 my %TYPE = (); #for debugging
252 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
254 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
256 $stable = $opt->{'table'} or die "table name is required";
257 $record = $opt->{'hashref'} || {};
258 $select = $opt->{'select'} || '*';
259 $extra_sql = $opt->{'extra_sql'} || '';
260 $order_by = $opt->{'order_by'} || '';
261 $cache = $opt->{'cache_obj'} || '';
262 $addl_from = $opt->{'addl_from'} || '';
263 $debug = $opt->{'debug'} || '';
265 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
269 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
271 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
275 my $table = $cache ? $cache->table : $stable;
276 my $dbdef_table = dbdef->table($table)
277 or die "No schema for table $table found - ".
278 "do you need to run freeside-upgrade?";
279 my $pkey = $dbdef_table->primary_key;
281 my @real_fields = grep exists($record->{$_}), real_fields($table);
283 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
284 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
286 cluck "warning: FS::$table not loaded; virtual fields not searchable";
287 @virtual_fields = ();
290 my $statement = "SELECT $select FROM $stable";
291 $statement .= " $addl_from" if $addl_from;
292 if ( @real_fields or @virtual_fields ) {
293 $statement .= ' WHERE '. join(' AND ',
294 get_real_fields($table, $record, \@real_fields) ,
295 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
299 $statement .= " $extra_sql" if defined($extra_sql);
300 $statement .= " $order_by" if defined($order_by);
302 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
303 my $sth = $dbh->prepare($statement)
304 or croak "$dbh->errstr doing $statement";
309 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
312 my $value = $record->{$field};
313 $value = $value->{'value'} if ref($value);
314 my $type = dbdef->table($table)->column($field)->type;
316 my $TYPE = SQL_VARCHAR;
317 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
320 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
321 } elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
322 || ( $type =~ /(real|float4)/i
323 && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
331 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
333 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
336 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
340 # $sth->execute( map $record->{$_},
341 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
342 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
344 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
346 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
347 @virtual_fields = "FS::$table"->virtual_fields;
349 cluck "warning: FS::$table not loaded; virtual fields not returned either";
350 @virtual_fields = ();
354 tie %result, "Tie::IxHash";
355 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
356 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
357 %result = map { $_->{$pkey}, $_ } @stuff;
359 @result{@stuff} = @stuff;
364 if ( keys(%result) and @virtual_fields ) {
366 "SELECT virtual_field.recnum, part_virtual_field.name, ".
367 "virtual_field.value ".
368 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
369 "WHERE part_virtual_field.dbtable = '$table' AND ".
370 "virtual_field.recnum IN (".
371 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
372 join(q!', '!, @virtual_fields) . "')";
373 warn "[debug]$me $statement\n" if $DEBUG > 1;
374 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
375 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
377 foreach (@{ $sth->fetchall_arrayref({}) }) {
378 my $recnum = $_->{recnum};
379 my $name = $_->{name};
380 my $value = $_->{value};
381 if (exists($result{$recnum})) {
382 $result{$recnum}->{$name} = $value;
387 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
388 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
389 #derivied class didn't override new method, so this optimization is safe
392 new_or_cached( "FS::$table", { %{$_} }, $cache )
396 new( "FS::$table", { %{$_} } )
400 #okay, its been tested
401 # warn "untested code (class FS::$table uses custom new method)";
403 eval 'FS::'. $table. '->new( { %{$_} } )';
407 # Check for encrypted fields and decrypt them.
408 ## only in the local copy, not the cached object
409 if ( $conf_encryption
410 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
411 foreach my $record (@return) {
412 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
413 # Set it directly... This may cause a problem in the future...
414 $record->setfield($field, $record->decrypt($record->getfield($field)));
419 cluck "warning: FS::$table not loaded; returning FS::Record objects";
421 FS::Record->new( $table, { %{$_} } );
427 ## makes this easier to read
429 sub get_virtual_fields {
433 my $virtual_fields = shift;
439 if ( ref($record->{$_}) ) {
440 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
441 if ( uc($op) eq 'ILIKE' ) {
443 $record->{$_}{'value'} = lc($record->{$_}{'value'});
444 $column = "LOWER($_)";
446 $record->{$_} = $record->{$_}{'value'};
449 # ... EXISTS ( SELECT name, value FROM part_virtual_field
451 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
452 # WHERE recnum = svc_acct.svcnum
453 # AND (name, value) = ('egad', 'brain') )
455 my $value = $record->{$_};
459 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
460 "( SELECT part_virtual_field.name, virtual_field.value ".
461 "FROM part_virtual_field JOIN virtual_field ".
462 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
463 "WHERE virtual_field.recnum = ${table}.${pkey} ".
464 "AND part_virtual_field.name = '${column}'".
466 " AND virtual_field.value ${op} '${value}'"
470 } @{ $virtual_fields } ) ;
473 sub get_real_fields {
476 my $real_fields = shift;
478 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
484 if ( ref($record->{$_}) ) {
485 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
486 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
487 if ( uc($op) eq 'ILIKE' ) {
489 $record->{$_}{'value'} = lc($record->{$_}{'value'});
490 $column = "LOWER($_)";
492 $record->{$_} = $record->{$_}{'value'}
495 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
497 if ( driver_name eq 'Pg' ) {
498 my $type = dbdef->table($table)->column($column)->type;
499 if ( $type =~ /(int|(big)?serial)/i ) {
500 qq-( $column IS NULL )-;
502 qq-( $column IS NULL OR $column = '' )-;
505 qq-( $column IS NULL OR $column = "" )-;
507 } elsif ( $op eq '!=' ) {
508 if ( driver_name eq 'Pg' ) {
509 my $type = dbdef->table($table)->column($column)->type;
510 if ( $type =~ /(int|(big)?serial)/i ) {
511 qq-( $column IS NOT NULL )-;
513 qq-( $column IS NOT NULL AND $column != '' )-;
516 qq-( $column IS NOT NULL AND $column != "" )-;
519 if ( driver_name eq 'Pg' ) {
520 qq-( $column $op '' )-;
522 qq-( $column $op "" )-;
528 } @{ $real_fields } );
531 =item by_key PRIMARY_KEY_VALUE
533 This is a class method that returns the record with the given primary key
534 value. This method is only useful in FS::Record subclasses. For example:
536 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
540 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
545 my ($class, $pkey_value) = @_;
547 my $table = $class->table
548 or croak "No table for $class found";
550 my $dbdef_table = dbdef->table($table)
551 or die "No schema for table $table found - ".
552 "do you need to create it or run dbdef-create?";
553 my $pkey = $dbdef_table->primary_key
554 or die "No primary key for table $table";
556 return qsearchs($table, { $pkey => $pkey_value });
559 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
561 Experimental JOINed search method. Using this method, you can execute a
562 single SELECT spanning multiple tables, and cache the results for subsequent
563 method calls. Interface will almost definately change in an incompatible
571 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
572 my $cache = FS::SearchCache->new( $ptable, $pkey );
575 grep { !$saw{$_->getfield($pkey)}++ }
576 qsearch($table, $record, $select, $extra_sql, $cache )
580 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
582 Same as qsearch, except that if more than one record matches, it B<carp>s but
583 returns the first. If this happens, you either made a logic error in asking
584 for a single item, or your data is corrupted.
588 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
590 my(@result) = qsearch(@_);
591 cluck "warning: Multiple records in scalar search ($table)"
592 if scalar(@result) > 1;
593 #should warn more vehemently if the search was on a primary key?
594 scalar(@result) ? ($result[0]) : ();
605 Returns the table name.
610 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
617 Returns the DBIx::DBSchema::Table object for the table.
623 my($table)=$self->table;
624 dbdef->table($table);
629 Returns the primary key for the table.
635 my $pkey = $self->dbdef_table->primary_key;
638 =item get, getfield COLUMN
640 Returns the value of the column/field/key COLUMN.
645 my($self,$field) = @_;
646 # to avoid "Use of unitialized value" errors
647 if ( defined ( $self->{Hash}->{$field} ) ) {
648 $self->{Hash}->{$field};
658 =item set, setfield COLUMN, VALUE
660 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
665 my($self,$field,$value) = @_;
666 $self->{'modified'} = 1;
667 $self->{'Hash'}->{$field} = $value;
674 =item AUTLOADED METHODS
676 $record->column is a synonym for $record->get('column');
678 $record->column('value') is a synonym for $record->set('column','value');
685 my($field)=$AUTOLOAD;
687 if ( defined($value) ) {
688 confess "errant AUTOLOAD $field for $self (arg $value)"
689 unless blessed($self) && $self->can('setfield');
690 $self->setfield($field,$value);
692 confess "errant AUTOLOAD $field for $self (no args)"
693 unless blessed($self) && $self->can('getfield');
694 $self->getfield($field);
700 # my $field = $AUTOLOAD;
702 # if ( defined($_[1]) ) {
703 # $_[0]->setfield($field, $_[1]);
705 # $_[0]->getfield($field);
711 Returns a list of the column/value pairs, usually for assigning to a new hash.
713 To make a distinct duplicate of an FS::Record object, you can do:
715 $new = new FS::Record ( $old->table, { $old->hash } );
721 confess $self. ' -> hash: Hash attribute is undefined'
722 unless defined($self->{'Hash'});
723 %{ $self->{'Hash'} };
728 Returns a reference to the column/value hash. This may be deprecated in the
729 future; if there's a reason you can't just use the autoloaded or get/set
741 Returns true if any of this object's values have been modified with set (or via
742 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
752 =item select_for_update
754 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
759 sub select_for_update {
761 my $primary_key = $self->primary_key;
764 'table' => $self->table,
765 'hashref' => { $primary_key => $self->$primary_key() },
766 'extra_sql' => 'FOR UPDATE',
772 Locks this table with a database-driver specific lock method. This is used
773 as a mutex in order to do a duplicate search.
775 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
777 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
779 Errors are fatal; no useful return value.
781 Note: To use this method for new tables other than svc_acct and svc_phone,
782 edit freeside-upgrade and add those tables to the duplicate_lock list.
788 my $table = $self->table;
790 warn "$me locking $table table\n" if $DEBUG;
792 if ( driver_name =~ /^Pg/i ) {
794 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
797 } elsif ( driver_name =~ /^mysql/i ) {
799 dbh->do("SELECT * FROM duplicate_lock
800 WHERE lockname = '$table'
802 ) or die dbh->errstr;
806 die "unknown database ". driver_name. "; don't know how to lock table";
810 warn "$me acquired $table table lock\n" if $DEBUG;
816 Inserts this record to the database. If there is an error, returns the error,
817 otherwise returns false.
825 warn "$self -> insert" if $DEBUG;
827 my $error = $self->check;
828 return $error if $error;
830 #single-field unique keys are given a value if false
831 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
832 foreach ( $self->dbdef_table->unique_singles) {
833 $self->unique($_) unless $self->getfield($_);
836 #and also the primary key, if the database isn't going to
837 my $primary_key = $self->dbdef_table->primary_key;
839 if ( $primary_key ) {
840 my $col = $self->dbdef_table->column($primary_key);
843 uc($col->type) =~ /^(BIG)?SERIAL\d?/
844 || ( driver_name eq 'Pg'
845 && defined($col->default)
846 && $col->default =~ /^nextval\(/i
848 || ( driver_name eq 'mysql'
849 && defined($col->local)
850 && $col->local =~ /AUTO_INCREMENT/i
852 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
855 my $table = $self->table;
857 # Encrypt before the database
858 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
859 && scalar( eval '@FS::'. $table . '::encrypted_fields')
860 && $conf->exists('encryption')
862 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
863 $self->{'saved'} = $self->getfield($field);
864 $self->setfield($field, $self->encrypt($self->getfield($field)));
868 #false laziness w/delete
870 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
873 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
876 my $statement = "INSERT INTO $table ";
877 if ( @real_fields ) {
880 join( ', ', @real_fields ).
882 join( ', ', @values ).
886 $statement .= 'DEFAULT VALUES';
888 warn "[debug]$me $statement\n" if $DEBUG > 1;
889 my $sth = dbh->prepare($statement) or return dbh->errstr;
891 local $SIG{HUP} = 'IGNORE';
892 local $SIG{INT} = 'IGNORE';
893 local $SIG{QUIT} = 'IGNORE';
894 local $SIG{TERM} = 'IGNORE';
895 local $SIG{TSTP} = 'IGNORE';
896 local $SIG{PIPE} = 'IGNORE';
898 $sth->execute or return $sth->errstr;
900 # get inserted id from the database, if applicable & needed
901 if ( $db_seq && ! $self->getfield($primary_key) ) {
902 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
906 if ( driver_name eq 'Pg' ) {
908 #my $oid = $sth->{'pg_oid_status'};
909 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
911 my $default = $self->dbdef_table->column($primary_key)->default;
912 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
913 dbh->rollback if $FS::UID::AutoCommit;
914 return "can't parse $table.$primary_key default value".
915 " for sequence name: $default";
919 my $i_sql = "SELECT currval('$sequence')";
920 my $i_sth = dbh->prepare($i_sql) or do {
921 dbh->rollback if $FS::UID::AutoCommit;
924 $i_sth->execute() or do { #$i_sth->execute($oid)
925 dbh->rollback if $FS::UID::AutoCommit;
926 return $i_sth->errstr;
928 $insertid = $i_sth->fetchrow_arrayref->[0];
930 } elsif ( driver_name eq 'mysql' ) {
932 $insertid = dbh->{'mysql_insertid'};
933 # work around mysql_insertid being null some of the time, ala RT :/
934 unless ( $insertid ) {
935 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
936 "using SELECT LAST_INSERT_ID();";
937 my $i_sql = "SELECT LAST_INSERT_ID()";
938 my $i_sth = dbh->prepare($i_sql) or do {
939 dbh->rollback if $FS::UID::AutoCommit;
942 $i_sth->execute or do {
943 dbh->rollback if $FS::UID::AutoCommit;
944 return $i_sth->errstr;
946 $insertid = $i_sth->fetchrow_arrayref->[0];
951 dbh->rollback if $FS::UID::AutoCommit;
952 return "don't know how to retreive inserted ids from ". driver_name.
953 ", try using counterfiles (maybe run dbdef-create?)";
957 $self->setfield($primary_key, $insertid);
962 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
963 $self->virtual_fields;
964 if (@virtual_fields) {
965 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
967 my $vfieldpart = $self->vfieldpart_hashref;
969 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
972 my $v_sth = dbh->prepare($v_statement) or do {
973 dbh->rollback if $FS::UID::AutoCommit;
977 foreach (keys(%v_values)) {
978 $v_sth->execute($self->getfield($primary_key),
982 dbh->rollback if $FS::UID::AutoCommit;
983 return $v_sth->errstr;
990 if ( defined dbdef->table('h_'. $table) ) {
991 my $h_statement = $self->_h_statement('insert');
992 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
993 $h_sth = dbh->prepare($h_statement) or do {
994 dbh->rollback if $FS::UID::AutoCommit;
1000 $h_sth->execute or return $h_sth->errstr if $h_sth;
1002 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1004 # Now that it has been saved, reset the encrypted fields so that $new
1005 # can still be used.
1006 foreach my $field (keys %{$saved}) {
1007 $self->setfield($field, $saved->{$field});
1015 Depriciated (use insert instead).
1020 cluck "warning: FS::Record::add deprecated!";
1021 insert @_; #call method in this scope
1026 Delete this record from the database. If there is an error, returns the error,
1027 otherwise returns false.
1034 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1036 $self->getfield($_) eq ''
1037 #? "( $_ IS NULL OR $_ = \"\" )"
1038 ? ( driver_name eq 'Pg'
1040 : "( $_ IS NULL OR $_ = \"\" )"
1042 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1043 } ( $self->dbdef_table->primary_key )
1044 ? ( $self->dbdef_table->primary_key)
1045 : real_fields($self->table)
1047 warn "[debug]$me $statement\n" if $DEBUG > 1;
1048 my $sth = dbh->prepare($statement) or return dbh->errstr;
1051 if ( defined dbdef->table('h_'. $self->table) ) {
1052 my $h_statement = $self->_h_statement('delete');
1053 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1054 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1059 my $primary_key = $self->dbdef_table->primary_key;
1062 my $vfp = $self->vfieldpart_hashref;
1063 foreach($self->virtual_fields) {
1064 next if $self->getfield($_) eq '';
1065 unless(@del_vfields) {
1066 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1067 $v_sth = dbh->prepare($st) or return dbh->errstr;
1069 push @del_vfields, $_;
1072 local $SIG{HUP} = 'IGNORE';
1073 local $SIG{INT} = 'IGNORE';
1074 local $SIG{QUIT} = 'IGNORE';
1075 local $SIG{TERM} = 'IGNORE';
1076 local $SIG{TSTP} = 'IGNORE';
1077 local $SIG{PIPE} = 'IGNORE';
1079 my $rc = $sth->execute or return $sth->errstr;
1080 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1081 $h_sth->execute or return $h_sth->errstr if $h_sth;
1082 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1083 or return $v_sth->errstr
1084 foreach (@del_vfields);
1086 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1088 #no need to needlessly destoy the data either (causes problems actually)
1089 #undef $self; #no need to keep object!
1096 Depriciated (use delete instead).
1101 cluck "warning: FS::Record::del deprecated!";
1102 &delete(@_); #call method in this scope
1105 =item replace OLD_RECORD
1107 Replace the OLD_RECORD with this one in the database. If there is an error,
1108 returns the error, otherwise returns false.
1113 my ($new, $old) = (shift, shift);
1115 $old = $new->replace_old unless defined($old);
1117 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1119 if ( $new->can('replace_check') ) {
1120 my $error = $new->replace_check($old);
1121 return $error if $error;
1124 return "Records not in same table!" unless $new->table eq $old->table;
1126 my $primary_key = $old->dbdef_table->primary_key;
1127 return "Can't change primary key $primary_key ".
1128 'from '. $old->getfield($primary_key).
1129 ' to ' . $new->getfield($primary_key)
1131 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1133 my $error = $new->check;
1134 return $error if $error;
1136 # Encrypt for replace
1138 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1139 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1140 $saved->{$field} = $new->getfield($field);
1141 $new->setfield($field, $new->encrypt($new->getfield($field)));
1145 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1146 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1147 ? ($_, $new->getfield($_)) : () } $old->fields;
1149 unless (keys(%diff) || $no_update_diff ) {
1150 carp "[warning]$me $new -> replace $old: records identical"
1151 unless $nowarn_identical;
1155 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1157 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1158 } real_fields($old->table)
1163 if ( $old->getfield($_) eq '' ) {
1165 #false laziness w/qsearch
1166 if ( driver_name eq 'Pg' ) {
1167 my $type = $old->dbdef_table->column($_)->type;
1168 if ( $type =~ /(int|(big)?serial)/i ) {
1171 qq-( $_ IS NULL OR $_ = '' )-;
1174 qq-( $_ IS NULL OR $_ = "" )-;
1178 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1181 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1184 warn "[debug]$me $statement\n" if $DEBUG > 1;
1185 my $sth = dbh->prepare($statement) or return dbh->errstr;
1188 if ( defined dbdef->table('h_'. $old->table) ) {
1189 my $h_old_statement = $old->_h_statement('replace_old');
1190 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1191 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1197 if ( defined dbdef->table('h_'. $new->table) ) {
1198 my $h_new_statement = $new->_h_statement('replace_new');
1199 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1200 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1205 # For virtual fields we have three cases with different SQL
1206 # statements: add, replace, delete
1210 my (@add_vfields, @rep_vfields, @del_vfields);
1211 my $vfp = $old->vfieldpart_hashref;
1212 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1213 if($diff{$_} eq '') {
1215 unless(@del_vfields) {
1216 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1217 "AND vfieldpart = ?";
1218 warn "[debug]$me $st\n" if $DEBUG > 2;
1219 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1221 push @del_vfields, $_;
1222 } elsif($old->getfield($_) eq '') {
1224 unless(@add_vfields) {
1225 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1227 warn "[debug]$me $st\n" if $DEBUG > 2;
1228 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1230 push @add_vfields, $_;
1233 unless(@rep_vfields) {
1234 my $st = "UPDATE virtual_field SET value = ? ".
1235 "WHERE recnum = ? AND vfieldpart = ?";
1236 warn "[debug]$me $st\n" if $DEBUG > 2;
1237 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1239 push @rep_vfields, $_;
1243 local $SIG{HUP} = 'IGNORE';
1244 local $SIG{INT} = 'IGNORE';
1245 local $SIG{QUIT} = 'IGNORE';
1246 local $SIG{TERM} = 'IGNORE';
1247 local $SIG{TSTP} = 'IGNORE';
1248 local $SIG{PIPE} = 'IGNORE';
1250 my $rc = $sth->execute or return $sth->errstr;
1251 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1252 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1253 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1255 $v_del_sth->execute($old->getfield($primary_key),
1257 or return $v_del_sth->errstr
1258 foreach(@del_vfields);
1260 $v_add_sth->execute($new->getfield($_),
1261 $old->getfield($primary_key),
1263 or return $v_add_sth->errstr
1264 foreach(@add_vfields);
1266 $v_rep_sth->execute($new->getfield($_),
1267 $old->getfield($primary_key),
1269 or return $v_rep_sth->errstr
1270 foreach(@rep_vfields);
1272 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1274 # Now that it has been saved, reset the encrypted fields so that $new
1275 # can still be used.
1276 foreach my $field (keys %{$saved}) {
1277 $new->setfield($field, $saved->{$field});
1285 my( $self ) = shift;
1286 warn "[$me] replace called with no arguments; autoloading old record\n"
1289 my $primary_key = $self->dbdef_table->primary_key;
1290 if ( $primary_key ) {
1291 $self->by_key( $self->$primary_key() ) #this is what's returned
1292 or croak "can't find ". $self->table. ".$primary_key ".
1293 $self->$primary_key();
1295 croak $self->table. " has no primary key; pass old record as argument";
1302 Depriciated (use replace instead).
1307 cluck "warning: FS::Record::rep deprecated!";
1308 replace @_; #call method in this scope
1313 Checks virtual fields (using check_blocks). Subclasses should still provide
1314 a check method to validate real fields, foreign keys, etc., and call this
1315 method via $self->SUPER::check.
1317 (FIXME: Should this method try to make sure that it I<is> being called from
1318 a subclass's check method, to keep the current semantics as far as possible?)
1323 #confess "FS::Record::check not implemented; supply one in subclass!";
1326 foreach my $field ($self->virtual_fields) {
1327 for ($self->getfield($field)) {
1328 # See notes on check_block in FS::part_virtual_field.
1329 eval $self->pvf($field)->check_block;
1331 #this is bad, probably want to follow the stack backtrace up and see
1333 my $err = "Fatal error checking $field for $self";
1335 return "$err (see log for backtrace): $@";
1338 $self->setfield($field, $_);
1344 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1346 Processes a batch import as a queued JSRPC job
1348 JOB is an FS::queue entry.
1350 OPTIONS_HASHREF can have the following keys:
1356 Table name (required).
1360 Listref of field names for static fields. They will be given values from the
1361 PARAMS hashref and passed as a "params" hashref to batch_import.
1365 Formats hashref. Keys are field names, values are listrefs that define the
1368 Each listref value can be a column name or a code reference. Coderefs are run
1369 with the row object, data and a FS::Conf object as the three parameters.
1370 For example, this coderef does the same thing as using the "columnname" string:
1373 my( $record, $data, $conf ) = @_;
1374 $record->columnname( $data );
1377 Coderefs are run after all "column name" fields are assigned.
1381 Optional format hashref of types. Keys are field names, values are "csv",
1382 "xls" or "fixedlength". Overrides automatic determination of file type
1385 =item format_headers
1387 Optional format hashref of header lines. Keys are field names, values are 0
1388 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1391 =item format_sep_chars
1393 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1394 CSV separation character.
1396 =item format_fixedlenth_formats
1398 Optional format hashref of fixed length format defintiions. Keys are field
1399 names, values Parse::FixedLength listrefs of field definitions.
1403 Set true to default to CSV file type if the filename does not contain a
1404 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1409 PARAMS is a base64-encoded Storable string containing the POSTed data as
1410 a hash ref. It normally contains at least one field, "uploaded files",
1411 generated by /elements/file-upload.html and containing the list of uploaded
1412 files. Currently only supports a single file named "file".
1416 use Storable qw(thaw);
1419 sub process_batch_import {
1420 my($job, $opt) = ( shift, shift );
1422 my $table = $opt->{table};
1423 my @pass_params = @{ $opt->{params} };
1424 my %formats = %{ $opt->{formats} };
1426 my $param = thaw(decode_base64(shift));
1427 warn Dumper($param) if $DEBUG;
1429 my $files = $param->{'uploaded_files'}
1430 or die "No files provided.\n";
1432 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1434 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1435 my $file = $dir. $files{'file'};
1438 FS::Record::batch_import( {
1441 formats => \%formats,
1442 format_types => $opt->{format_types},
1443 format_headers => $opt->{format_headers},
1444 format_sep_chars => $opt->{format_sep_chars},
1445 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1450 format => $param->{format},
1451 params => { map { $_ => $param->{$_} } @pass_params },
1453 default_csv => $opt->{default_csv},
1458 die "$error\n" if $error;
1461 =item batch_import PARAM_HASHREF
1463 Class method for batch imports. Available params:
1473 =item format_headers
1475 =item format_sep_chars
1477 =item format_fixedlength_formats
1483 FS::queue object, will be updated with progress
1489 csv, xls or fixedlength
1502 warn "$me batch_import call with params: \n". Dumper($param)
1505 my $table = $param->{table};
1506 my $formats = $param->{formats};
1508 my $job = $param->{job};
1509 my $file = $param->{file};
1510 my $format = $param->{'format'};
1511 my $params = $param->{params} || {};
1513 die "unknown format $format" unless exists $formats->{ $format };
1515 my $type = $param->{'format_types'}
1516 ? $param->{'format_types'}{ $format }
1517 : $param->{type} || 'csv';
1520 if ( $file =~ /\.(\w+)$/i ) {
1524 warn "can't parse file type from filename $file; defaulting to CSV";
1528 if $param->{'default_csv'} && $type ne 'xls';
1531 my $header = $param->{'format_headers'}
1532 ? $param->{'format_headers'}{ $param->{'format'} }
1535 my $sep_char = $param->{'format_sep_chars'}
1536 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1539 my $fixedlength_format =
1540 $param->{'format_fixedlength_formats'}
1541 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1544 my @fields = @{ $formats->{ $format } };
1550 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1552 if ( $type eq 'csv' ) {
1555 $attr{sep_char} = $sep_char if $sep_char;
1556 $parser = new Text::CSV_XS \%attr;
1558 } elsif ( $type eq 'fixedlength' ) {
1560 eval "use Parse::FixedLength;";
1562 $parser = new Parse::FixedLength $fixedlength_format;
1565 die "Unknown file type $type\n";
1568 @buffer = split(/\r?\n/, slurp($file) );
1569 splice(@buffer, 0, ($header || 0) );
1570 $count = scalar(@buffer);
1572 } elsif ( $type eq 'xls' ) {
1574 eval "use Spreadsheet::ParseExcel;";
1577 eval "use DateTime::Format::Excel;";
1578 #for now, just let the error be thrown if it is used, since only CDR
1579 # formats bill_west and troop use it, not other excel-parsing things
1582 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1584 $parser = $excel->{Worksheet}[0]; #first sheet
1586 $count = $parser->{MaxRow} || $parser->{MinRow};
1589 $row = $header || 0;
1592 die "Unknown file type $type\n";
1597 local $SIG{HUP} = 'IGNORE';
1598 local $SIG{INT} = 'IGNORE';
1599 local $SIG{QUIT} = 'IGNORE';
1600 local $SIG{TERM} = 'IGNORE';
1601 local $SIG{TSTP} = 'IGNORE';
1602 local $SIG{PIPE} = 'IGNORE';
1604 my $oldAutoCommit = $FS::UID::AutoCommit;
1605 local $FS::UID::AutoCommit = 0;
1610 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1614 if ( $type eq 'csv' ) {
1616 last unless scalar(@buffer);
1617 $line = shift(@buffer);
1619 $parser->parse($line) or do {
1620 $dbh->rollback if $oldAutoCommit;
1621 return "can't parse: ". $parser->error_input();
1623 @columns = $parser->fields();
1625 } elsif ( $type eq 'fixedlength' ) {
1627 @columns = $parser->parse($line);
1629 } elsif ( $type eq 'xls' ) {
1631 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1632 || ! $parser->{Cells}[$row];
1634 my @row = @{ $parser->{Cells}[$row] };
1635 @columns = map $_->{Val}, @row;
1638 #warn $z++. ": $_\n" for @columns;
1641 die "Unknown file type $type\n";
1645 my %hash = %$params;
1647 foreach my $field ( @fields ) {
1649 my $value = shift @columns;
1651 if ( ref($field) eq 'CODE' ) {
1652 #&{$field}(\%hash, $value);
1653 push @later, $field, $value;
1655 #??? $hash{$field} = $value if length($value);
1656 $hash{$field} = $value if defined($value) && length($value);
1661 my $class = "FS::$table";
1663 my $record = $class->new( \%hash );
1665 while ( scalar(@later) ) {
1666 my $sub = shift @later;
1667 my $data = shift @later;
1668 &{$sub}($record, $data, $conf); # $record->&{$sub}($data, $conf);
1671 my $error = $record->insert;
1674 $dbh->rollback if $oldAutoCommit;
1675 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1681 if ( $job && time - $min_sec > $last ) { #progress bar
1682 $job->update_statustext( int(100 * $imported / $count) );
1688 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1690 return "Empty file!" unless $imported || $param->{empty_ok};
1697 my( $self, $action, $time ) = @_;
1702 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1703 real_fields($self->table);
1706 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1707 # You can see if it changed by the paymask...
1708 if ($conf && $conf->exists('encryption') ) {
1709 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1711 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1713 "INSERT INTO h_". $self->table. " ( ".
1714 join(', ', qw(history_date history_user history_action), @fields ).
1716 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1723 B<Warning>: External use is B<deprecated>.
1725 Replaces COLUMN in record with a unique number, using counters in the
1726 filesystem. Used by the B<insert> method on single-field unique columns
1727 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1728 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1730 Returns the new value.
1735 my($self,$field) = @_;
1736 my($table)=$self->table;
1738 croak "Unique called on field $field, but it is ",
1739 $self->getfield($field),
1741 if $self->getfield($field);
1743 #warn "table $table is tainted" if is_tainted($table);
1744 #warn "field $field is tainted" if is_tainted($field);
1746 my($counter) = new File::CounterFile "$table.$field",0;
1748 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1750 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1753 my $index = $counter->inc;
1754 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1756 $index =~ /^(\d*)$/;
1759 $self->setfield($field,$index);
1763 =item ut_float COLUMN
1765 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1766 null. If there is an error, returns the error, otherwise returns false.
1771 my($self,$field)=@_ ;
1772 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1773 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1774 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1775 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1776 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1777 $self->setfield($field,$1);
1780 =item ut_floatn COLUMN
1782 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1783 null. If there is an error, returns the error, otherwise returns false.
1787 #false laziness w/ut_ipn
1789 my( $self, $field ) = @_;
1790 if ( $self->getfield($field) =~ /^()$/ ) {
1791 $self->setfield($field,'');
1794 $self->ut_float($field);
1798 =item ut_sfloat COLUMN
1800 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1801 May not be null. If there is an error, returns the error, otherwise returns
1807 my($self,$field)=@_ ;
1808 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1809 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1810 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1811 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1812 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1813 $self->setfield($field,$1);
1816 =item ut_sfloatn COLUMN
1818 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1819 null. If there is an error, returns the error, otherwise returns false.
1824 my( $self, $field ) = @_;
1825 if ( $self->getfield($field) =~ /^()$/ ) {
1826 $self->setfield($field,'');
1829 $self->ut_sfloat($field);
1833 =item ut_snumber COLUMN
1835 Check/untaint signed numeric data (whole numbers). If there is an error,
1836 returns the error, otherwise returns false.
1841 my($self, $field) = @_;
1842 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1843 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1844 $self->setfield($field, "$1$2");
1848 =item ut_snumbern COLUMN
1850 Check/untaint signed numeric data (whole numbers). If there is an error,
1851 returns the error, otherwise returns false.
1856 my($self, $field) = @_;
1857 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1858 or return "Illegal (numeric) $field: ". $self->getfield($field);
1860 return "Illegal (numeric) $field: ". $self->getfield($field)
1863 $self->setfield($field, "$1$2");
1867 =item ut_number COLUMN
1869 Check/untaint simple numeric data (whole numbers). May not be null. If there
1870 is an error, returns the error, otherwise returns false.
1875 my($self,$field)=@_;
1876 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1877 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1878 $self->setfield($field,$1);
1882 =item ut_numbern COLUMN
1884 Check/untaint simple numeric data (whole numbers). May be null. If there is
1885 an error, returns the error, otherwise returns false.
1890 my($self,$field)=@_;
1891 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1892 or return "Illegal (numeric) $field: ". $self->getfield($field);
1893 $self->setfield($field,$1);
1897 =item ut_money COLUMN
1899 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1900 is an error, returns the error, otherwise returns false.
1905 my($self,$field)=@_;
1906 $self->setfield($field, 0) if $self->getfield($field) eq '';
1907 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1908 or return "Illegal (money) $field: ". $self->getfield($field);
1909 #$self->setfield($field, "$1$2$3" || 0);
1910 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1914 =item ut_text COLUMN
1916 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1917 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1918 May not be null. If there is an error, returns the error, otherwise returns
1924 my($self,$field)=@_;
1925 #warn "msgcat ". \&msgcat. "\n";
1926 #warn "notexist ". \¬exist. "\n";
1927 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1928 $self->getfield($field)
1929 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1930 or return gettext('illegal_or_empty_text'). " $field: ".
1931 $self->getfield($field);
1932 $self->setfield($field,$1);
1936 =item ut_textn COLUMN
1938 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1939 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1940 May be null. If there is an error, returns the error, otherwise returns false.
1945 my($self,$field)=@_;
1946 $self->getfield($field)
1947 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1948 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1949 $self->setfield($field,$1);
1953 =item ut_alpha COLUMN
1955 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1956 an error, returns the error, otherwise returns false.
1961 my($self,$field)=@_;
1962 $self->getfield($field) =~ /^(\w+)$/
1963 or return "Illegal or empty (alphanumeric) $field: ".
1964 $self->getfield($field);
1965 $self->setfield($field,$1);
1969 =item ut_alpha COLUMN
1971 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1972 error, returns the error, otherwise returns false.
1977 my($self,$field)=@_;
1978 $self->getfield($field) =~ /^(\w*)$/
1979 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1980 $self->setfield($field,$1);
1984 =item ut_alpha_lower COLUMN
1986 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1987 there is an error, returns the error, otherwise returns false.
1991 sub ut_alpha_lower {
1992 my($self,$field)=@_;
1993 $self->getfield($field) =~ /[[:upper:]]/
1994 and return "Uppercase characters are not permitted in $field";
1995 $self->ut_alpha($field);
1998 =item ut_phonen COLUMN [ COUNTRY ]
2000 Check/untaint phone numbers. May be null. If there is an error, returns
2001 the error, otherwise returns false.
2003 Takes an optional two-letter ISO country code; without it or with unsupported
2004 countries, ut_phonen simply calls ut_alphan.
2009 my( $self, $field, $country ) = @_;
2010 return $self->ut_alphan($field) unless defined $country;
2011 my $phonen = $self->getfield($field);
2012 if ( $phonen eq '' ) {
2013 $self->setfield($field,'');
2014 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2016 $phonen = $conf->config('cust_main-default_areacode').$phonen
2017 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2018 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2019 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2020 $phonen = "$1-$2-$3";
2021 $phonen .= " x$4" if $4;
2022 $self->setfield($field,$phonen);
2024 warn "warning: don't know how to check phone numbers for country $country";
2025 return $self->ut_textn($field);
2032 Check/untaint hexadecimal values.
2037 my($self, $field) = @_;
2038 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2039 or return "Illegal (hex) $field: ". $self->getfield($field);
2040 $self->setfield($field, uc($1));
2044 =item ut_hexn COLUMN
2046 Check/untaint hexadecimal values. May be null.
2051 my($self, $field) = @_;
2052 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2053 or return "Illegal (hex) $field: ". $self->getfield($field);
2054 $self->setfield($field, uc($1));
2059 Check/untaint ip addresses. IPv4 only for now.
2064 my( $self, $field ) = @_;
2065 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2066 or return "Illegal (IP address) $field: ". $self->getfield($field);
2067 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2068 $self->setfield($field, "$1.$2.$3.$4");
2074 Check/untaint ip addresses. IPv4 only for now. May be null.
2079 my( $self, $field ) = @_;
2080 if ( $self->getfield($field) =~ /^()$/ ) {
2081 $self->setfield($field,'');
2084 $self->ut_ip($field);
2088 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2090 Check/untaint coordinates.
2091 Accepts the following forms:
2101 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2102 The latter form (that is, the MMM are thousands of minutes) is
2103 assumed if the "MMM" is exactly three digits or two digits > 59.
2105 To be safe, just use the DDD.DDDDD form.
2107 If LOWER or UPPER are specified, then the coordinate is checked
2108 for lower and upper bounds, respectively.
2114 my ($self, $field) = (shift, shift);
2116 my $lower = shift if scalar(@_);
2117 my $upper = shift if scalar(@_);
2118 my $coord = $self->getfield($field);
2119 my $neg = $coord =~ s/^(-)//;
2121 my ($d, $m, $s) = (0, 0, 0);
2124 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2125 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2126 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2128 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2131 return "Invalid (coordinate with minutes > 59) $field: "
2132 . $self->getfield($field);
2135 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2137 if (defined($lower) and ($coord < $lower)) {
2138 return "Invalid (coordinate < $lower) $field: "
2139 . $self->getfield($field);;
2142 if (defined($upper) and ($coord > $upper)) {
2143 return "Invalid (coordinate > $upper) $field: "
2144 . $self->getfield($field);;
2147 $self->setfield($field, $coord);
2151 return "Invalid (coordinate) $field: " . $self->getfield($field);
2155 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2157 Same as ut_coord, except optionally null.
2163 my ($self, $field) = (shift, shift);
2165 if ($self->getfield($field) =~ /^$/) {
2168 return $self->ut_coord($field, @_);
2174 =item ut_domain COLUMN
2176 Check/untaint host and domain names.
2181 my( $self, $field ) = @_;
2182 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2183 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2184 or return "Illegal (domain) $field: ". $self->getfield($field);
2185 $self->setfield($field,$1);
2189 =item ut_name COLUMN
2191 Check/untaint proper names; allows alphanumerics, spaces and the following
2192 punctuation: , . - '
2199 my( $self, $field ) = @_;
2200 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2201 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2202 $self->setfield($field,$1);
2208 Check/untaint zip codes.
2212 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2215 my( $self, $field, $country ) = @_;
2217 if ( $country eq 'US' ) {
2219 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2220 or return gettext('illegal_zip'). " $field for country $country: ".
2221 $self->getfield($field);
2222 $self->setfield($field, $1);
2224 } elsif ( $country eq 'CA' ) {
2226 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2227 or return gettext('illegal_zip'). " $field for country $country: ".
2228 $self->getfield($field);
2229 $self->setfield($field, "$1 $2");
2233 if ( $self->getfield($field) =~ /^\s*$/
2234 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2237 $self->setfield($field,'');
2239 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2240 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2241 $self->setfield($field,$1);
2249 =item ut_country COLUMN
2251 Check/untaint country codes. Country names are changed to codes, if possible -
2252 see L<Locale::Country>.
2257 my( $self, $field ) = @_;
2258 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2259 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2260 && country2code($1) ) {
2261 $self->setfield($field,uc(country2code($1)));
2264 $self->getfield($field) =~ /^(\w\w)$/
2265 or return "Illegal (country) $field: ". $self->getfield($field);
2266 $self->setfield($field,uc($1));
2270 =item ut_anything COLUMN
2272 Untaints arbitrary data. Be careful.
2277 my( $self, $field ) = @_;
2278 $self->getfield($field) =~ /^(.*)$/s
2279 or return "Illegal $field: ". $self->getfield($field);
2280 $self->setfield($field,$1);
2284 =item ut_enum COLUMN CHOICES_ARRAYREF
2286 Check/untaint a column, supplying all possible choices, like the "enum" type.
2291 my( $self, $field, $choices ) = @_;
2292 foreach my $choice ( @$choices ) {
2293 if ( $self->getfield($field) eq $choice ) {
2294 $self->setfield($choice);
2298 return "Illegal (enum) field $field: ". $self->getfield($field);
2301 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2303 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2304 on the column first.
2308 sub ut_foreign_key {
2309 my( $self, $field, $table, $foreign ) = @_;
2310 return '' if $no_check_foreign;
2311 qsearchs($table, { $foreign => $self->getfield($field) })
2312 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2313 " in $table.$foreign";
2317 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2319 Like ut_foreign_key, except the null value is also allowed.
2323 sub ut_foreign_keyn {
2324 my( $self, $field, $table, $foreign ) = @_;
2325 $self->getfield($field)
2326 ? $self->ut_foreign_key($field, $table, $foreign)
2330 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2332 Checks this column as an agentnum, taking into account the current users's
2333 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2334 right or rights allowing no agentnum.
2338 sub ut_agentnum_acl {
2339 my( $self, $field ) = (shift, shift);
2340 my $null_acl = scalar(@_) ? shift : [];
2341 $null_acl = [ $null_acl ] unless ref($null_acl);
2343 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2344 return "Illegal agentnum: $error" if $error;
2346 my $curuser = $FS::CurrentUser::CurrentUser;
2348 if ( $self->$field() ) {
2350 return "Access denied"
2351 unless $curuser->agentnum($self->$field());
2355 return "Access denied"
2356 unless grep $curuser->access_right($_), @$null_acl;
2364 =item virtual_fields [ TABLE ]
2366 Returns a list of virtual fields defined for the table. This should not
2367 be exported, and should only be called as an instance or class method.
2371 sub virtual_fields {
2374 $table = $self->table or confess "virtual_fields called on non-table";
2376 confess "Unknown table $table" unless dbdef->table($table);
2378 return () unless dbdef->table('part_virtual_field');
2380 unless ( $virtual_fields_cache{$table} ) {
2381 my $query = 'SELECT name from part_virtual_field ' .
2382 "WHERE dbtable = '$table'";
2384 my $result = $dbh->selectcol_arrayref($query);
2385 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2387 $virtual_fields_cache{$table} = $result;
2390 @{$virtual_fields_cache{$table}};
2395 =item fields [ TABLE ]
2397 This is a wrapper for real_fields and virtual_fields. Code that called
2398 fields before should probably continue to call fields.
2403 my $something = shift;
2405 if($something->isa('FS::Record')) {
2406 $table = $something->table;
2408 $table = $something;
2409 $something = "FS::$table";
2411 return (real_fields($table), $something->virtual_fields());
2414 =item pvf FIELD_NAME
2416 Returns the FS::part_virtual_field object corresponding to a field in the
2417 record (specified by FIELD_NAME).
2422 my ($self, $name) = (shift, shift);
2424 if(grep /^$name$/, $self->virtual_fields) {
2425 return qsearchs('part_virtual_field', { dbtable => $self->table,
2431 =item vfieldpart_hashref TABLE
2433 Returns a hashref of virtual field names and vfieldparts applicable to the given
2438 sub vfieldpart_hashref {
2440 my $table = $self->table;
2442 return {} unless dbdef->table('part_virtual_field');
2445 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2446 "dbtable = '$table'";
2447 my $sth = $dbh->prepare($statement);
2448 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2449 return { map { $_->{name}, $_->{vfieldpart} }
2450 @{$sth->fetchall_arrayref({})} };
2454 =item encrypt($value)
2456 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2458 Returns the encrypted string.
2460 You should generally not have to worry about calling this, as the system handles this for you.
2465 my ($self, $value) = @_;
2468 if ($conf->exists('encryption')) {
2469 if ($self->is_encrypted($value)) {
2470 # Return the original value if it isn't plaintext.
2471 $encrypted = $value;
2474 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2475 # RSA doesn't like the empty string so let's pack it up
2476 # The database doesn't like the RSA data so uuencode it
2477 my $length = length($value)+1;
2478 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2480 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2487 =item is_encrypted($value)
2489 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2495 my ($self, $value) = @_;
2496 # Possible Bug - Some work may be required here....
2498 if ($value =~ /^M/ && length($value) > 80) {
2505 =item decrypt($value)
2507 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2509 You should generally not have to worry about calling this, as the system handles this for you.
2514 my ($self,$value) = @_;
2515 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2516 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2518 if (ref($rsa_decrypt) =~ /::RSA/) {
2519 my $encrypted = unpack ("u*", $value);
2520 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2521 if ($@) {warn "Decryption Failed"};
2529 #Initialize the Module
2530 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2532 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2533 $rsa_module = $conf->config('encryptionmodule');
2537 eval ("require $rsa_module"); # No need to import the namespace
2540 # Initialize Encryption
2541 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2542 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2543 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2546 # Intitalize Decryption
2547 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2548 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2549 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2553 =item h_search ACTION
2555 Given an ACTION, either "insert", or "delete", returns the appropriate history
2556 record corresponding to this record, if any.
2561 my( $self, $action ) = @_;
2563 my $table = $self->table;
2566 my $primary_key = dbdef->table($table)->primary_key;
2569 'table' => "h_$table",
2570 'hashref' => { $primary_key => $self->$primary_key(),
2571 'history_action' => $action,
2579 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2580 appropriate history record corresponding to this record, if any.
2585 my($self, $action) = @_;
2586 my $h = $self->h_search($action);
2587 $h ? $h->history_date : '';
2596 =item real_fields [ TABLE ]
2598 Returns a list of the real columns in the specified table. Called only by
2599 fields() and other subroutines elsewhere in FS::Record.
2606 my($table_obj) = dbdef->table($table);
2607 confess "Unknown table $table" unless $table_obj;
2608 $table_obj->columns;
2611 =item _quote VALUE, TABLE, COLUMN
2613 This is an internal function used to construct SQL statements. It returns
2614 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2615 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2620 my($value, $table, $column) = @_;
2621 my $column_obj = dbdef->table($table)->column($column);
2622 my $column_type = $column_obj->type;
2623 my $nullable = $column_obj->null;
2625 warn " $table.$column: $value ($column_type".
2626 ( $nullable ? ' NULL' : ' NOT NULL' ).
2627 ")\n" if $DEBUG > 2;
2629 if ( $value eq '' && $nullable ) {
2631 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2632 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2635 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2636 ! $column_type =~ /(char|binary|text)$/i ) {
2645 This is deprecated. Don't use it.
2647 It returns a hash-type list with the fields of this record's table set true.
2652 carp "warning: hfields is deprecated";
2655 foreach (fields($table)) {
2664 "$_: ". $self->getfield($_). "|"
2665 } (fields($self->table)) );
2668 sub DESTROY { return; }
2672 # #use Carp qw(cluck);
2673 # #cluck "DESTROYING $self";
2674 # warn "DESTROYING $self";
2678 # return ! eval { join('',@_), kill 0; 1; };
2681 =item str2time_sql [ DRIVER_NAME ]
2683 Returns a function to convert to unix time based on database type, such as
2684 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2685 the str2time_sql_closing method to return a closing string rather than just
2686 using a closing parenthesis as previously suggested.
2688 You can pass an optional driver name such as "Pg", "mysql" or
2689 $dbh->{Driver}->{Name} to return a function for that database instead of
2690 the current database.
2695 my $driver = shift || driver_name;
2697 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2698 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2700 warn "warning: unknown database type $driver; guessing how to convert ".
2701 "dates to UNIX timestamps";
2702 return 'EXTRACT(EPOCH FROM ';
2706 =item str2time_sql_closing [ DRIVER_NAME ]
2708 Returns the closing suffix of a function to convert to unix time based on
2709 database type, such as ")::integer" for Pg or ")" for mysql.
2711 You can pass an optional driver name such as "Pg", "mysql" or
2712 $dbh->{Driver}->{Name} to return a function for that database instead of
2713 the current database.
2717 sub str2time_sql_closing {
2718 my $driver = shift || driver_name;
2720 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2728 This module should probably be renamed, since much of the functionality is
2729 of general use. It is not completely unlike Adapter::DBI (see below).
2731 Exported qsearch and qsearchs should be deprecated in favor of method calls
2732 (against an FS::Record object like the old search and searchs that qsearch
2733 and qsearchs were on top of.)
2735 The whole fields / hfields mess should be removed.
2737 The various WHERE clauses should be subroutined.
2739 table string should be deprecated in favor of DBIx::DBSchema::Table.
2741 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2742 true maps to the database (and WHERE clauses) would also help.
2744 The ut_ methods should ask the dbdef for a default length.
2746 ut_sqltype (like ut_varchar) should all be defined
2748 A fallback check method should be provided which uses the dbdef.
2750 The ut_money method assumes money has two decimal digits.
2752 The Pg money kludge in the new method only strips `$'.
2754 The ut_phonen method only checks US-style phone numbers.
2756 The _quote function should probably use ut_float instead of a regex.
2758 All the subroutines probably should be methods, here or elsewhere.
2760 Probably should borrow/use some dbdef methods where appropriate (like sub
2763 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2764 or allow it to be set. Working around it is ugly any way around - DBI should
2765 be fixed. (only affects RDBMS which return uppercase column names)
2767 ut_zip should take an optional country like ut_phone.
2771 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2773 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.