4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
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;
47 FS::UID->install_callback( sub {
50 $conf = FS::Conf->new;
51 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
57 FS::Record - Database record objects
62 use FS::Record qw(dbh fields qsearch qsearchs);
64 $record = new FS::Record 'table', \%hash;
65 $record = new FS::Record 'table', { 'column' => 'value', ... };
67 $record = qsearchs FS::Record 'table', \%hash;
68 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
69 @records = qsearch FS::Record 'table', \%hash;
70 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
72 $table = $record->table;
73 $dbdef_table = $record->dbdef_table;
75 $value = $record->get('column');
76 $value = $record->getfield('column');
77 $value = $record->column;
79 $record->set( 'column' => 'value' );
80 $record->setfield( 'column' => 'value' );
81 $record->column('value');
83 %hash = $record->hash;
85 $hashref = $record->hashref;
87 $error = $record->insert;
89 $error = $record->delete;
91 $error = $new_record->replace($old_record);
93 # external use deprecated - handled by the database (at least for Pg, mysql)
94 $value = $record->unique('column');
96 $error = $record->ut_float('column');
97 $error = $record->ut_floatn('column');
98 $error = $record->ut_number('column');
99 $error = $record->ut_numbern('column');
100 $error = $record->ut_snumber('column');
101 $error = $record->ut_snumbern('column');
102 $error = $record->ut_money('column');
103 $error = $record->ut_text('column');
104 $error = $record->ut_textn('column');
105 $error = $record->ut_alpha('column');
106 $error = $record->ut_alphan('column');
107 $error = $record->ut_phonen('column');
108 $error = $record->ut_anything('column');
109 $error = $record->ut_name('column');
111 $quoted_value = _quote($value,'table','field');
114 $fields = hfields('table');
115 if ( $fields->{Field} ) { # etc.
117 @fields = fields 'table'; #as a subroutine
118 @fields = $record->fields; #as a method call
123 (Mostly) object-oriented interface to database records. Records are currently
124 implemented on top of DBI. FS::Record is intended as a base class for
125 table-specific classes to inherit from, i.e. FS::cust_main.
131 =item new [ TABLE, ] HASHREF
133 Creates a new record. It doesn't store it in the database, though. See
134 L<"insert"> for that.
136 Note that the object stores this hash reference, not a distinct copy of the
137 hash it points to. You can ask the object for a copy with the I<hash>
140 TABLE can only be omitted when a dervived class overrides the table method.
146 my $class = ref($proto) || $proto;
148 bless ($self, $class);
150 unless ( defined ( $self->table ) ) {
151 $self->{'Table'} = shift;
152 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
155 $self->{'Hash'} = shift;
157 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
158 $self->{'Hash'}{$field}='';
161 $self->_rebless if $self->can('_rebless');
163 $self->{'modified'} = 0;
165 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
172 my $class = ref($proto) || $proto;
174 bless ($self, $class);
176 $self->{'Table'} = shift unless defined ( $self->table );
178 my $hashref = $self->{'Hash'} = shift;
180 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
181 my $obj = $cache->cache->{$hashref->{$cache->key}};
182 $obj->_cache($hashref, $cache) if $obj->can('_cache');
185 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
192 my $class = ref($proto) || $proto;
194 bless ($self, $class);
195 if ( defined $self->table ) {
196 cluck "create constructor is deprecated, use new!";
199 croak "FS::Record::create called (not from a subclass)!";
203 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
205 Searches the database for all records matching (at least) the key/value pairs
206 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
207 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
210 The preferred usage is to pass a hash reference of named parameters:
212 my @records = qsearch( {
213 'table' => 'table_name',
214 'hashref' => { 'field' => 'value'
215 'field' => { 'op' => '<',
220 #these are optional...
222 'extra_sql' => 'AND field ',
223 'order_by' => 'ORDER BY something',
224 #'cache_obj' => '', #optional
225 'addl_from' => 'LEFT JOIN othtable USING ( field )',
230 Much code still uses old-style positional parameters, this is also probably
231 fine in the common case where there are only two parameters:
233 my @records = qsearch( 'table', { 'field' => 'value' } );
235 ###oops, argh, FS::Record::new only lets us create database fields.
236 #Normal behaviour if SELECT is not specified is `*', as in
237 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
238 #feature where you can specify SELECT - remember, the objects returned,
239 #although blessed into the appropriate `FS::TABLE' package, will only have the
240 #fields you specify. This might have unwanted results if you then go calling
241 #regular FS::TABLE methods
246 my %TYPE = (); #for debugging
249 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
251 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
253 $stable = $opt->{'table'} or die "table name is required";
254 $record = $opt->{'hashref'} || {};
255 $select = $opt->{'select'} || '*';
256 $extra_sql = $opt->{'extra_sql'} || '';
257 $order_by = $opt->{'order_by'} || '';
258 $cache = $opt->{'cache_obj'} || '';
259 $addl_from = $opt->{'addl_from'} || '';
260 $debug = $opt->{'debug'} || '';
262 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
266 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
268 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
272 my $table = $cache ? $cache->table : $stable;
273 my $dbdef_table = dbdef->table($table)
274 or die "No schema for table $table found - ".
275 "do you need to run freeside-upgrade?";
276 my $pkey = $dbdef_table->primary_key;
278 my @real_fields = grep exists($record->{$_}), real_fields($table);
280 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
281 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
283 cluck "warning: FS::$table not loaded; virtual fields not searchable";
284 @virtual_fields = ();
287 my $statement = "SELECT $select FROM $stable";
288 $statement .= " $addl_from" if $addl_from;
289 if ( @real_fields or @virtual_fields ) {
290 $statement .= ' WHERE '. join(' AND ',
291 get_real_fields($table, $record, \@real_fields) ,
292 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
296 $statement .= " $extra_sql" if defined($extra_sql);
297 $statement .= " $order_by" if defined($order_by);
299 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
300 my $sth = $dbh->prepare($statement)
301 or croak "$dbh->errstr doing $statement";
306 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
309 my $value = $record->{$field};
310 $value = $value->{'value'} if ref($value);
311 my $type = dbdef->table($table)->column($field)->type;
313 my $TYPE = SQL_VARCHAR;
314 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
317 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
318 } elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
319 || ( $type =~ /(real|float4)/i
320 && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
328 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
330 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
333 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
337 # $sth->execute( map $record->{$_},
338 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
339 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
341 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
343 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
344 @virtual_fields = "FS::$table"->virtual_fields;
346 cluck "warning: FS::$table not loaded; virtual fields not returned either";
347 @virtual_fields = ();
351 tie %result, "Tie::IxHash";
352 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
353 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
354 %result = map { $_->{$pkey}, $_ } @stuff;
356 @result{@stuff} = @stuff;
361 if ( keys(%result) and @virtual_fields ) {
363 "SELECT virtual_field.recnum, part_virtual_field.name, ".
364 "virtual_field.value ".
365 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
366 "WHERE part_virtual_field.dbtable = '$table' AND ".
367 "virtual_field.recnum IN (".
368 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
369 join(q!', '!, @virtual_fields) . "')";
370 warn "[debug]$me $statement\n" if $DEBUG > 1;
371 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
372 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
374 foreach (@{ $sth->fetchall_arrayref({}) }) {
375 my $recnum = $_->{recnum};
376 my $name = $_->{name};
377 my $value = $_->{value};
378 if (exists($result{$recnum})) {
379 $result{$recnum}->{$name} = $value;
384 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
385 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
386 #derivied class didn't override new method, so this optimization is safe
389 new_or_cached( "FS::$table", { %{$_} }, $cache )
393 new( "FS::$table", { %{$_} } )
397 #okay, its been tested
398 # warn "untested code (class FS::$table uses custom new method)";
400 eval 'FS::'. $table. '->new( { %{$_} } )';
404 # Check for encrypted fields and decrypt them.
405 ## only in the local copy, not the cached object
406 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
407 # the initial search for
409 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
410 foreach my $record (@return) {
411 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
412 # Set it directly... This may cause a problem in the future...
413 $record->setfield($field, $record->decrypt($record->getfield($field)));
418 cluck "warning: FS::$table not loaded; returning FS::Record objects";
420 FS::Record->new( $table, { %{$_} } );
426 ## makes this easier to read
428 sub get_virtual_fields {
432 my $virtual_fields = shift;
438 if ( ref($record->{$_}) ) {
439 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
440 if ( uc($op) eq 'ILIKE' ) {
442 $record->{$_}{'value'} = lc($record->{$_}{'value'});
443 $column = "LOWER($_)";
445 $record->{$_} = $record->{$_}{'value'};
448 # ... EXISTS ( SELECT name, value FROM part_virtual_field
450 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
451 # WHERE recnum = svc_acct.svcnum
452 # AND (name, value) = ('egad', 'brain') )
454 my $value = $record->{$_};
458 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
459 "( SELECT part_virtual_field.name, virtual_field.value ".
460 "FROM part_virtual_field JOIN virtual_field ".
461 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
462 "WHERE virtual_field.recnum = ${table}.${pkey} ".
463 "AND part_virtual_field.name = '${column}'".
465 " AND virtual_field.value ${op} '${value}'"
469 } @{ $virtual_fields } ) ;
472 sub get_real_fields {
475 my $real_fields = shift;
477 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
483 if ( ref($record->{$_}) ) {
484 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
485 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
486 if ( uc($op) eq 'ILIKE' ) {
488 $record->{$_}{'value'} = lc($record->{$_}{'value'});
489 $column = "LOWER($_)";
491 $record->{$_} = $record->{$_}{'value'}
494 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
496 if ( driver_name eq 'Pg' ) {
497 my $type = dbdef->table($table)->column($column)->type;
498 if ( $type =~ /(int|(big)?serial)/i ) {
499 qq-( $column IS NULL )-;
501 qq-( $column IS NULL OR $column = '' )-;
504 qq-( $column IS NULL OR $column = "" )-;
506 } elsif ( $op eq '!=' ) {
507 if ( driver_name eq 'Pg' ) {
508 my $type = dbdef->table($table)->column($column)->type;
509 if ( $type =~ /(int|(big)?serial)/i ) {
510 qq-( $column IS NOT NULL )-;
512 qq-( $column IS NOT NULL AND $column != '' )-;
515 qq-( $column IS NOT NULL AND $column != "" )-;
518 if ( driver_name eq 'Pg' ) {
519 qq-( $column $op '' )-;
521 qq-( $column $op "" )-;
527 } @{ $real_fields } );
530 =item by_key PRIMARY_KEY_VALUE
532 This is a class method that returns the record with the given primary key
533 value. This method is only useful in FS::Record subclasses. For example:
535 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
539 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
544 my ($class, $pkey_value) = @_;
546 my $table = $class->table
547 or croak "No table for $class found";
549 my $dbdef_table = dbdef->table($table)
550 or die "No schema for table $table found - ".
551 "do you need to create it or run dbdef-create?";
552 my $pkey = $dbdef_table->primary_key
553 or die "No primary key for table $table";
555 return qsearchs($table, { $pkey => $pkey_value });
558 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
560 Experimental JOINed search method. Using this method, you can execute a
561 single SELECT spanning multiple tables, and cache the results for subsequent
562 method calls. Interface will almost definately change in an incompatible
570 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
571 my $cache = FS::SearchCache->new( $ptable, $pkey );
574 grep { !$saw{$_->getfield($pkey)}++ }
575 qsearch($table, $record, $select, $extra_sql, $cache )
579 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
581 Same as qsearch, except that if more than one record matches, it B<carp>s but
582 returns the first. If this happens, you either made a logic error in asking
583 for a single item, or your data is corrupted.
587 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
589 my(@result) = qsearch(@_);
590 cluck "warning: Multiple records in scalar search ($table)"
591 if scalar(@result) > 1;
592 #should warn more vehemently if the search was on a primary key?
593 scalar(@result) ? ($result[0]) : ();
604 Returns the table name.
609 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
616 Returns the DBIx::DBSchema::Table object for the table.
622 my($table)=$self->table;
623 dbdef->table($table);
628 Returns the primary key for the table.
634 my $pkey = $self->dbdef_table->primary_key;
637 =item get, getfield COLUMN
639 Returns the value of the column/field/key COLUMN.
644 my($self,$field) = @_;
645 # to avoid "Use of unitialized value" errors
646 if ( defined ( $self->{Hash}->{$field} ) ) {
647 $self->{Hash}->{$field};
657 =item set, setfield COLUMN, VALUE
659 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
664 my($self,$field,$value) = @_;
665 $self->{'modified'} = 1;
666 $self->{'Hash'}->{$field} = $value;
673 =item AUTLOADED METHODS
675 $record->column is a synonym for $record->get('column');
677 $record->column('value') is a synonym for $record->set('column','value');
684 my($field)=$AUTOLOAD;
686 if ( defined($value) ) {
687 confess "errant AUTOLOAD $field for $self (arg $value)"
688 unless blessed($self) && $self->can('setfield');
689 $self->setfield($field,$value);
691 confess "errant AUTOLOAD $field for $self (no args)"
692 unless blessed($self) && $self->can('getfield');
693 $self->getfield($field);
699 # my $field = $AUTOLOAD;
701 # if ( defined($_[1]) ) {
702 # $_[0]->setfield($field, $_[1]);
704 # $_[0]->getfield($field);
710 Returns a list of the column/value pairs, usually for assigning to a new hash.
712 To make a distinct duplicate of an FS::Record object, you can do:
714 $new = new FS::Record ( $old->table, { $old->hash } );
720 confess $self. ' -> hash: Hash attribute is undefined'
721 unless defined($self->{'Hash'});
722 %{ $self->{'Hash'} };
727 Returns a reference to the column/value hash. This may be deprecated in the
728 future; if there's a reason you can't just use the autoloaded or get/set
740 Returns true if any of this object's values have been modified with set (or via
741 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
751 =item select_for_update
753 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
758 sub select_for_update {
760 my $primary_key = $self->primary_key;
763 'table' => $self->table,
764 'hashref' => { $primary_key => $self->$primary_key() },
765 'extra_sql' => 'FOR UPDATE',
771 Locks this table with a database-driver specific lock method. This is used
772 as a mutex in order to do a duplicate search.
774 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
776 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
778 Errors are fatal; no useful return value.
780 Note: To use this method for new tables other than svc_acct and svc_phone,
781 edit freeside-upgrade and add those tables to the duplicate_lock list.
787 my $table = $self->table;
789 warn "$me locking $table table\n" if $DEBUG;
791 if ( driver_name =~ /^Pg/i ) {
793 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
796 } elsif ( driver_name =~ /^mysql/i ) {
798 dbh->do("SELECT * FROM duplicate_lock
799 WHERE lockname = '$table'
801 ) or die dbh->errstr;
805 die "unknown database ". driver_name. "; don't know how to lock table";
809 warn "$me acquired $table table lock\n" if $DEBUG;
815 Inserts this record to the database. If there is an error, returns the error,
816 otherwise returns false.
824 warn "$self -> insert" if $DEBUG;
826 my $error = $self->check;
827 return $error if $error;
829 #single-field unique keys are given a value if false
830 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
831 foreach ( $self->dbdef_table->unique_singles) {
832 $self->unique($_) unless $self->getfield($_);
835 #and also the primary key, if the database isn't going to
836 my $primary_key = $self->dbdef_table->primary_key;
838 if ( $primary_key ) {
839 my $col = $self->dbdef_table->column($primary_key);
842 uc($col->type) =~ /^(BIG)?SERIAL\d?/
843 || ( driver_name eq 'Pg'
844 && defined($col->default)
845 && $col->default =~ /^nextval\(/i
847 || ( driver_name eq 'mysql'
848 && defined($col->local)
849 && $col->local =~ /AUTO_INCREMENT/i
851 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
854 my $table = $self->table;
856 # Encrypt before the database
857 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
858 && scalar( eval '@FS::'. $table . '::encrypted_fields')
859 && $conf->exists('encryption')
861 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
862 $self->{'saved'} = $self->getfield($field);
863 $self->setfield($field, $self->encrypt($self->getfield($field)));
867 #false laziness w/delete
869 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
872 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
875 my $statement = "INSERT INTO $table ";
876 if ( @real_fields ) {
879 join( ', ', @real_fields ).
881 join( ', ', @values ).
885 $statement .= 'DEFAULT VALUES';
887 warn "[debug]$me $statement\n" if $DEBUG > 1;
888 my $sth = dbh->prepare($statement) or return dbh->errstr;
890 local $SIG{HUP} = 'IGNORE';
891 local $SIG{INT} = 'IGNORE';
892 local $SIG{QUIT} = 'IGNORE';
893 local $SIG{TERM} = 'IGNORE';
894 local $SIG{TSTP} = 'IGNORE';
895 local $SIG{PIPE} = 'IGNORE';
897 $sth->execute or return $sth->errstr;
899 # get inserted id from the database, if applicable & needed
900 if ( $db_seq && ! $self->getfield($primary_key) ) {
901 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
905 if ( driver_name eq 'Pg' ) {
907 #my $oid = $sth->{'pg_oid_status'};
908 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
910 my $default = $self->dbdef_table->column($primary_key)->default;
911 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
912 dbh->rollback if $FS::UID::AutoCommit;
913 return "can't parse $table.$primary_key default value".
914 " for sequence name: $default";
918 my $i_sql = "SELECT currval('$sequence')";
919 my $i_sth = dbh->prepare($i_sql) or do {
920 dbh->rollback if $FS::UID::AutoCommit;
923 $i_sth->execute() or do { #$i_sth->execute($oid)
924 dbh->rollback if $FS::UID::AutoCommit;
925 return $i_sth->errstr;
927 $insertid = $i_sth->fetchrow_arrayref->[0];
929 } elsif ( driver_name eq 'mysql' ) {
931 $insertid = dbh->{'mysql_insertid'};
932 # work around mysql_insertid being null some of the time, ala RT :/
933 unless ( $insertid ) {
934 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
935 "using SELECT LAST_INSERT_ID();";
936 my $i_sql = "SELECT LAST_INSERT_ID()";
937 my $i_sth = dbh->prepare($i_sql) or do {
938 dbh->rollback if $FS::UID::AutoCommit;
941 $i_sth->execute or do {
942 dbh->rollback if $FS::UID::AutoCommit;
943 return $i_sth->errstr;
945 $insertid = $i_sth->fetchrow_arrayref->[0];
950 dbh->rollback if $FS::UID::AutoCommit;
951 return "don't know how to retreive inserted ids from ". driver_name.
952 ", try using counterfiles (maybe run dbdef-create?)";
956 $self->setfield($primary_key, $insertid);
961 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
962 $self->virtual_fields;
963 if (@virtual_fields) {
964 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
966 my $vfieldpart = $self->vfieldpart_hashref;
968 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
971 my $v_sth = dbh->prepare($v_statement) or do {
972 dbh->rollback if $FS::UID::AutoCommit;
976 foreach (keys(%v_values)) {
977 $v_sth->execute($self->getfield($primary_key),
981 dbh->rollback if $FS::UID::AutoCommit;
982 return $v_sth->errstr;
989 if ( defined dbdef->table('h_'. $table) ) {
990 my $h_statement = $self->_h_statement('insert');
991 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
992 $h_sth = dbh->prepare($h_statement) or do {
993 dbh->rollback if $FS::UID::AutoCommit;
999 $h_sth->execute or return $h_sth->errstr if $h_sth;
1001 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1003 # Now that it has been saved, reset the encrypted fields so that $new
1004 # can still be used.
1005 foreach my $field (keys %{$saved}) {
1006 $self->setfield($field, $saved->{$field});
1014 Depriciated (use insert instead).
1019 cluck "warning: FS::Record::add deprecated!";
1020 insert @_; #call method in this scope
1025 Delete this record from the database. If there is an error, returns the error,
1026 otherwise returns false.
1033 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1035 $self->getfield($_) eq ''
1036 #? "( $_ IS NULL OR $_ = \"\" )"
1037 ? ( driver_name eq 'Pg'
1039 : "( $_ IS NULL OR $_ = \"\" )"
1041 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1042 } ( $self->dbdef_table->primary_key )
1043 ? ( $self->dbdef_table->primary_key)
1044 : real_fields($self->table)
1046 warn "[debug]$me $statement\n" if $DEBUG > 1;
1047 my $sth = dbh->prepare($statement) or return dbh->errstr;
1050 if ( defined dbdef->table('h_'. $self->table) ) {
1051 my $h_statement = $self->_h_statement('delete');
1052 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1053 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1058 my $primary_key = $self->dbdef_table->primary_key;
1061 my $vfp = $self->vfieldpart_hashref;
1062 foreach($self->virtual_fields) {
1063 next if $self->getfield($_) eq '';
1064 unless(@del_vfields) {
1065 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1066 $v_sth = dbh->prepare($st) or return dbh->errstr;
1068 push @del_vfields, $_;
1071 local $SIG{HUP} = 'IGNORE';
1072 local $SIG{INT} = 'IGNORE';
1073 local $SIG{QUIT} = 'IGNORE';
1074 local $SIG{TERM} = 'IGNORE';
1075 local $SIG{TSTP} = 'IGNORE';
1076 local $SIG{PIPE} = 'IGNORE';
1078 my $rc = $sth->execute or return $sth->errstr;
1079 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1080 $h_sth->execute or return $h_sth->errstr if $h_sth;
1081 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1082 or return $v_sth->errstr
1083 foreach (@del_vfields);
1085 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1087 #no need to needlessly destoy the data either (causes problems actually)
1088 #undef $self; #no need to keep object!
1095 Depriciated (use delete instead).
1100 cluck "warning: FS::Record::del deprecated!";
1101 &delete(@_); #call method in this scope
1104 =item replace OLD_RECORD
1106 Replace the OLD_RECORD with this one in the database. If there is an error,
1107 returns the error, otherwise returns false.
1112 my ($new, $old) = (shift, shift);
1114 $old = $new->replace_old unless defined($old);
1116 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1118 if ( $new->can('replace_check') ) {
1119 my $error = $new->replace_check($old);
1120 return $error if $error;
1123 return "Records not in same table!" unless $new->table eq $old->table;
1125 my $primary_key = $old->dbdef_table->primary_key;
1126 return "Can't change primary key $primary_key ".
1127 'from '. $old->getfield($primary_key).
1128 ' to ' . $new->getfield($primary_key)
1130 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1132 my $error = $new->check;
1133 return $error if $error;
1135 # Encrypt for replace
1137 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1138 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1139 $saved->{$field} = $new->getfield($field);
1140 $new->setfield($field, $new->encrypt($new->getfield($field)));
1144 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1145 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1146 ? ($_, $new->getfield($_)) : () } $old->fields;
1148 unless (keys(%diff) || $no_update_diff ) {
1149 carp "[warning]$me $new -> replace $old: records identical"
1150 unless $nowarn_identical;
1154 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1156 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1157 } real_fields($old->table)
1162 if ( $old->getfield($_) eq '' ) {
1164 #false laziness w/qsearch
1165 if ( driver_name eq 'Pg' ) {
1166 my $type = $old->dbdef_table->column($_)->type;
1167 if ( $type =~ /(int|(big)?serial)/i ) {
1170 qq-( $_ IS NULL OR $_ = '' )-;
1173 qq-( $_ IS NULL OR $_ = "" )-;
1177 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1180 } ( $primary_key ? ( $primary_key ) : real_fields($old->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_'. $old->table) ) {
1188 my $h_old_statement = $old->_h_statement('replace_old');
1189 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1190 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1196 if ( defined dbdef->table('h_'. $new->table) ) {
1197 my $h_new_statement = $new->_h_statement('replace_new');
1198 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1199 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1204 # For virtual fields we have three cases with different SQL
1205 # statements: add, replace, delete
1209 my (@add_vfields, @rep_vfields, @del_vfields);
1210 my $vfp = $old->vfieldpart_hashref;
1211 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1212 if($diff{$_} eq '') {
1214 unless(@del_vfields) {
1215 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1216 "AND vfieldpart = ?";
1217 warn "[debug]$me $st\n" if $DEBUG > 2;
1218 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1220 push @del_vfields, $_;
1221 } elsif($old->getfield($_) eq '') {
1223 unless(@add_vfields) {
1224 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1226 warn "[debug]$me $st\n" if $DEBUG > 2;
1227 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1229 push @add_vfields, $_;
1232 unless(@rep_vfields) {
1233 my $st = "UPDATE virtual_field SET value = ? ".
1234 "WHERE recnum = ? AND vfieldpart = ?";
1235 warn "[debug]$me $st\n" if $DEBUG > 2;
1236 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1238 push @rep_vfields, $_;
1242 local $SIG{HUP} = 'IGNORE';
1243 local $SIG{INT} = 'IGNORE';
1244 local $SIG{QUIT} = 'IGNORE';
1245 local $SIG{TERM} = 'IGNORE';
1246 local $SIG{TSTP} = 'IGNORE';
1247 local $SIG{PIPE} = 'IGNORE';
1249 my $rc = $sth->execute or return $sth->errstr;
1250 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1251 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1252 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1254 $v_del_sth->execute($old->getfield($primary_key),
1256 or return $v_del_sth->errstr
1257 foreach(@del_vfields);
1259 $v_add_sth->execute($new->getfield($_),
1260 $old->getfield($primary_key),
1262 or return $v_add_sth->errstr
1263 foreach(@add_vfields);
1265 $v_rep_sth->execute($new->getfield($_),
1266 $old->getfield($primary_key),
1268 or return $v_rep_sth->errstr
1269 foreach(@rep_vfields);
1271 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1273 # Now that it has been saved, reset the encrypted fields so that $new
1274 # can still be used.
1275 foreach my $field (keys %{$saved}) {
1276 $new->setfield($field, $saved->{$field});
1284 my( $self ) = shift;
1285 warn "[$me] replace called with no arguments; autoloading old record\n"
1288 my $primary_key = $self->dbdef_table->primary_key;
1289 if ( $primary_key ) {
1290 $self->by_key( $self->$primary_key() ) #this is what's returned
1291 or croak "can't find ". $self->table. ".$primary_key ".
1292 $self->$primary_key();
1294 croak $self->table. " has no primary key; pass old record as argument";
1301 Depriciated (use replace instead).
1306 cluck "warning: FS::Record::rep deprecated!";
1307 replace @_; #call method in this scope
1312 Checks virtual fields (using check_blocks). Subclasses should still provide
1313 a check method to validate real fields, foreign keys, etc., and call this
1314 method via $self->SUPER::check.
1316 (FIXME: Should this method try to make sure that it I<is> being called from
1317 a subclass's check method, to keep the current semantics as far as possible?)
1322 #confess "FS::Record::check not implemented; supply one in subclass!";
1325 foreach my $field ($self->virtual_fields) {
1326 for ($self->getfield($field)) {
1327 # See notes on check_block in FS::part_virtual_field.
1328 eval $self->pvf($field)->check_block;
1330 #this is bad, probably want to follow the stack backtrace up and see
1332 my $err = "Fatal error checking $field for $self";
1334 return "$err (see log for backtrace): $@";
1337 $self->setfield($field, $_);
1343 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1345 Processes a batch import as a queued JSRPC job
1347 JOB is an FS::queue entry.
1349 OPTIONS_HASHREF can have the following keys:
1355 Table name (required).
1359 Listref of field names for static fields. They will be given values from the
1360 PARAMS hashref and passed as a "params" hashref to batch_import.
1364 Formats hashref. Keys are field names, values are listrefs that define the
1367 Each listref value can be a column name or a code reference. Coderefs are run
1368 with the row object and data as the two parameters. For example, this coderef
1369 does the same thing as using the "columnname" string:
1372 my( $record, $data ) = @_;
1373 $record->columnname( $data );
1378 Optional format hashref of types. Keys are field names, values are "csv",
1379 "xls" or "fixedlength". Overrides automatic determination of file type
1382 =item format_headers
1384 Optional format hashref of header lines. Keys are field names, values are 0
1385 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1388 =item format_sep_chars
1390 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1391 CSV separation character.
1393 =item format_fixedlenth_formats
1395 Optional format hashref of fixed length format defintiions. Keys are field
1396 names, values Parse::FixedLength listrefs of field definitions.
1400 Set true to default to CSV file type if the filename does not contain a
1401 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1406 PARAMS is a base64-encoded Storable string containing the POSTed data as
1407 a hash ref. It normally contains at least one field, "uploaded files",
1408 generated by /elements/file-upload.html and containing the list of uploaded
1409 files. Currently only supports a single file named "file".
1413 use Storable qw(thaw);
1416 sub process_batch_import {
1417 my($job, $opt) = ( shift, shift );
1419 my $table = $opt->{table};
1420 my @pass_params = @{ $opt->{params} };
1421 my %formats = %{ $opt->{formats} };
1423 my $param = thaw(decode_base64(shift));
1424 warn Dumper($param) if $DEBUG;
1426 my $files = $param->{'uploaded_files'}
1427 or die "No files provided.\n";
1429 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1431 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1432 my $file = $dir. $files{'file'};
1434 my $type = $opt->{'format_types'}
1435 ? $opt->{'format_types'}{ $param->{'format'} }
1439 if ( $file =~ /\.(\w+)$/i ) {
1443 warn "can't parse file type from filename $file; defaulting to CSV";
1447 if $opt->{'default_csv'} && $type ne 'xls';
1450 my $header = $opt->{'format_headers'}
1451 ? $opt->{'format_headers'}{ $param->{'format'} }
1454 my $sep_char = $opt->{'format_sep_chars'}
1455 ? $opt->{'format_sep_chars'}{ $param->{'format'} }
1458 my $fixedlength_format =
1459 $opt->{'format_fixedlength_formats'}
1460 ? $opt->{'format_fixedlength_formats'}{ $param->{'format'} }
1464 FS::Record::batch_import( {
1466 formats => \%formats,
1470 format => $param->{format},
1472 sep_char => $sep_char,
1473 fixedlength_format => $fixedlength_format,
1474 params => { map { $_ => $param->{$_} } @pass_params },
1479 die "$error\n" if $error;
1482 =item batch_import PARAM_HASHREF
1484 Class method for batch imports. Available params:
1496 FS::queue object, will be updated with progress
1502 csv, xls or fixedlength
1510 =item fixedlength_format
1521 warn "$me batch_import call with params: \n". Dumper($param)
1524 my $table = $param->{table};
1525 my $formats = $param->{formats};
1526 my $params = $param->{params};
1528 my $job = $param->{job};
1530 my $filename = $param->{file};
1531 my $type = $param->{type} || 'csv';
1533 my $format = $param->{'format'};
1535 die "unknown format $format" unless exists $formats->{ $format };
1536 my @fields = @{ $formats->{ $format } };
1542 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1544 if ( $type eq 'csv' ) {
1547 foreach ( grep exists($param->{$_}), qw( sep_char ) ) {
1548 $attr{$_} = $param->{$_};
1551 $parser = new Text::CSV_XS \%attr;
1553 } elsif ( $type eq 'fixedlength' ) {
1555 eval "use Parse::FixedLength;";
1557 $parser = new Parse::FixedLength $param->{'fixedlength_format'};
1560 die "Unknown file type $type\n";
1563 @buffer = split(/\r?\n/, slurp($filename) );
1564 splice(@buffer, 0, ($param->{'header'} || 0) );
1565 $count = scalar(@buffer);
1567 } elsif ( $type eq 'xls' ) {
1569 eval "use Spreadsheet::ParseExcel;";
1572 eval "use DateTime::Format::Excel;";
1573 #for now, just let the error be thrown if it is used, since only CDR
1574 # formats bill_west and troop use it, not other excel-parsing things
1577 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($filename);
1579 $parser = $excel->{Worksheet}[0]; #first sheet
1581 $count = $parser->{MaxRow} || $parser->{MinRow};
1584 $row = $param->{'header'} || 0;
1587 die "Unknown file type $type\n";
1592 local $SIG{HUP} = 'IGNORE';
1593 local $SIG{INT} = 'IGNORE';
1594 local $SIG{QUIT} = 'IGNORE';
1595 local $SIG{TERM} = 'IGNORE';
1596 local $SIG{TSTP} = 'IGNORE';
1597 local $SIG{PIPE} = 'IGNORE';
1599 my $oldAutoCommit = $FS::UID::AutoCommit;
1600 local $FS::UID::AutoCommit = 0;
1605 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1609 if ( $type eq 'csv' ) {
1611 last unless scalar(@buffer);
1612 $line = shift(@buffer);
1614 $parser->parse($line) or do {
1615 $dbh->rollback if $oldAutoCommit;
1616 return "can't parse: ". $parser->error_input();
1618 @columns = $parser->fields();
1620 } elsif ( $type eq 'fixedlength' ) {
1622 @columns = $parser->parse($line);
1624 } elsif ( $type eq 'xls' ) {
1626 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1627 || ! $parser->{Cells}[$row];
1629 my @row = @{ $parser->{Cells}[$row] };
1630 @columns = map $_->{Val}, @row;
1633 #warn $z++. ": $_\n" for @columns;
1636 die "Unknown file type $type\n";
1640 my %hash = %$params;
1642 foreach my $field ( @fields ) {
1644 my $value = shift @columns;
1646 if ( ref($field) eq 'CODE' ) {
1647 #&{$field}(\%hash, $value);
1648 push @later, $field, $value;
1650 $hash{$field} = $value if defined($value) && length($value);
1655 my $class = "FS::$table";
1657 my $record = $class->new( \%hash );
1659 while ( scalar(@later) ) {
1660 my $sub = shift @later;
1661 my $data = shift @later;
1662 &{$sub}($record, $data); # $record->&{$sub}($data);
1665 my $error = $record->insert;
1668 $dbh->rollback if $oldAutoCommit;
1669 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1675 if ( $job && time - $min_sec > $last ) { #progress bar
1676 $job->update_statustext( int(100 * $imported / $count) );
1682 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1684 return "Empty file!" unless $imported || $param->{empty_ok};
1691 my( $self, $action, $time ) = @_;
1696 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1697 real_fields($self->table);
1700 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1701 # You can see if it changed by the paymask...
1702 if ($conf && $conf->exists('encryption') ) {
1703 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1705 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1707 "INSERT INTO h_". $self->table. " ( ".
1708 join(', ', qw(history_date history_user history_action), @fields ).
1710 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1717 B<Warning>: External use is B<deprecated>.
1719 Replaces COLUMN in record with a unique number, using counters in the
1720 filesystem. Used by the B<insert> method on single-field unique columns
1721 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1722 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1724 Returns the new value.
1729 my($self,$field) = @_;
1730 my($table)=$self->table;
1732 croak "Unique called on field $field, but it is ",
1733 $self->getfield($field),
1735 if $self->getfield($field);
1737 #warn "table $table is tainted" if is_tainted($table);
1738 #warn "field $field is tainted" if is_tainted($field);
1740 my($counter) = new File::CounterFile "$table.$field",0;
1742 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1744 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1747 my $index = $counter->inc;
1748 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1750 $index =~ /^(\d*)$/;
1753 $self->setfield($field,$index);
1757 =item ut_float COLUMN
1759 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1760 null. If there is an error, returns the error, otherwise returns false.
1765 my($self,$field)=@_ ;
1766 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1767 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1768 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1769 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1770 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1771 $self->setfield($field,$1);
1774 =item ut_floatn COLUMN
1776 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1777 null. If there is an error, returns the error, otherwise returns false.
1781 #false laziness w/ut_ipn
1783 my( $self, $field ) = @_;
1784 if ( $self->getfield($field) =~ /^()$/ ) {
1785 $self->setfield($field,'');
1788 $self->ut_float($field);
1792 =item ut_sfloat COLUMN
1794 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1795 May not be null. If there is an error, returns the error, otherwise returns
1801 my($self,$field)=@_ ;
1802 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1803 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1804 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1805 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1806 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1807 $self->setfield($field,$1);
1810 =item ut_sfloatn COLUMN
1812 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1813 null. If there is an error, returns the error, otherwise returns false.
1818 my( $self, $field ) = @_;
1819 if ( $self->getfield($field) =~ /^()$/ ) {
1820 $self->setfield($field,'');
1823 $self->ut_sfloat($field);
1827 =item ut_snumber COLUMN
1829 Check/untaint signed numeric data (whole numbers). If there is an error,
1830 returns the error, otherwise returns false.
1835 my($self, $field) = @_;
1836 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1837 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1838 $self->setfield($field, "$1$2");
1842 =item ut_snumbern COLUMN
1844 Check/untaint signed numeric data (whole numbers). If there is an error,
1845 returns the error, otherwise returns false.
1850 my($self, $field) = @_;
1851 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1852 or return "Illegal (numeric) $field: ". $self->getfield($field);
1854 return "Illegal (numeric) $field: ". $self->getfield($field)
1857 $self->setfield($field, "$1$2");
1861 =item ut_number COLUMN
1863 Check/untaint simple numeric data (whole numbers). May not be null. If there
1864 is an error, returns the error, otherwise returns false.
1869 my($self,$field)=@_;
1870 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1871 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1872 $self->setfield($field,$1);
1876 =item ut_numbern COLUMN
1878 Check/untaint simple numeric data (whole numbers). May be null. If there is
1879 an error, returns the error, otherwise returns false.
1884 my($self,$field)=@_;
1885 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1886 or return "Illegal (numeric) $field: ". $self->getfield($field);
1887 $self->setfield($field,$1);
1891 =item ut_money COLUMN
1893 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1894 is an error, returns the error, otherwise returns false.
1899 my($self,$field)=@_;
1900 $self->setfield($field, 0) if $self->getfield($field) eq '';
1901 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1902 or return "Illegal (money) $field: ". $self->getfield($field);
1903 #$self->setfield($field, "$1$2$3" || 0);
1904 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1908 =item ut_text COLUMN
1910 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1911 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1912 May not be null. If there is an error, returns the error, otherwise returns
1918 my($self,$field)=@_;
1919 #warn "msgcat ". \&msgcat. "\n";
1920 #warn "notexist ". \¬exist. "\n";
1921 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1922 $self->getfield($field)
1923 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1924 or return gettext('illegal_or_empty_text'). " $field: ".
1925 $self->getfield($field);
1926 $self->setfield($field,$1);
1930 =item ut_textn COLUMN
1932 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1933 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1934 May be null. If there is an error, returns the error, otherwise returns false.
1939 my($self,$field)=@_;
1940 $self->getfield($field)
1941 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1942 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1943 $self->setfield($field,$1);
1947 =item ut_alpha COLUMN
1949 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1950 an error, returns the error, otherwise returns false.
1955 my($self,$field)=@_;
1956 $self->getfield($field) =~ /^(\w+)$/
1957 or return "Illegal or empty (alphanumeric) $field: ".
1958 $self->getfield($field);
1959 $self->setfield($field,$1);
1963 =item ut_alpha COLUMN
1965 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1966 error, returns the error, otherwise returns false.
1971 my($self,$field)=@_;
1972 $self->getfield($field) =~ /^(\w*)$/
1973 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1974 $self->setfield($field,$1);
1978 =item ut_alpha_lower COLUMN
1980 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1981 there is an error, returns the error, otherwise returns false.
1985 sub ut_alpha_lower {
1986 my($self,$field)=@_;
1987 $self->getfield($field) =~ /[[:upper:]]/
1988 and return "Uppercase characters are not permitted in $field";
1989 $self->ut_alpha($field);
1992 =item ut_phonen COLUMN [ COUNTRY ]
1994 Check/untaint phone numbers. May be null. If there is an error, returns
1995 the error, otherwise returns false.
1997 Takes an optional two-letter ISO country code; without it or with unsupported
1998 countries, ut_phonen simply calls ut_alphan.
2003 my( $self, $field, $country ) = @_;
2004 return $self->ut_alphan($field) unless defined $country;
2005 my $phonen = $self->getfield($field);
2006 if ( $phonen eq '' ) {
2007 $self->setfield($field,'');
2008 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2010 $phonen = $conf->config('cust_main-default_areacode').$phonen
2011 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2012 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2013 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2014 $phonen = "$1-$2-$3";
2015 $phonen .= " x$4" if $4;
2016 $self->setfield($field,$phonen);
2018 warn "warning: don't know how to check phone numbers for country $country";
2019 return $self->ut_textn($field);
2026 Check/untaint hexadecimal values.
2031 my($self, $field) = @_;
2032 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2033 or return "Illegal (hex) $field: ". $self->getfield($field);
2034 $self->setfield($field, uc($1));
2038 =item ut_hexn COLUMN
2040 Check/untaint hexadecimal values. May be null.
2045 my($self, $field) = @_;
2046 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2047 or return "Illegal (hex) $field: ". $self->getfield($field);
2048 $self->setfield($field, uc($1));
2053 Check/untaint ip addresses. IPv4 only for now.
2058 my( $self, $field ) = @_;
2059 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2060 or return "Illegal (IP address) $field: ". $self->getfield($field);
2061 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2062 $self->setfield($field, "$1.$2.$3.$4");
2068 Check/untaint ip addresses. IPv4 only for now. May be null.
2073 my( $self, $field ) = @_;
2074 if ( $self->getfield($field) =~ /^()$/ ) {
2075 $self->setfield($field,'');
2078 $self->ut_ip($field);
2082 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2084 Check/untaint coordinates.
2085 Accepts the following forms:
2095 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2096 The latter form (that is, the MMM are thousands of minutes) is
2097 assumed if the "MMM" is exactly three digits or two digits > 59.
2099 To be safe, just use the DDD.DDDDD form.
2101 If LOWER or UPPER are specified, then the coordinate is checked
2102 for lower and upper bounds, respectively.
2108 my ($self, $field) = (shift, shift);
2110 my $lower = shift if scalar(@_);
2111 my $upper = shift if scalar(@_);
2112 my $coord = $self->getfield($field);
2113 my $neg = $coord =~ s/^(-)//;
2115 my ($d, $m, $s) = (0, 0, 0);
2118 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2119 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2120 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2122 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2125 return "Invalid (coordinate with minutes > 59) $field: "
2126 . $self->getfield($field);
2129 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2131 if (defined($lower) and ($coord < $lower)) {
2132 return "Invalid (coordinate < $lower) $field: "
2133 . $self->getfield($field);;
2136 if (defined($upper) and ($coord > $upper)) {
2137 return "Invalid (coordinate > $upper) $field: "
2138 . $self->getfield($field);;
2141 $self->setfield($field, $coord);
2145 return "Invalid (coordinate) $field: " . $self->getfield($field);
2149 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2151 Same as ut_coord, except optionally null.
2157 my ($self, $field) = (shift, shift);
2159 if ($self->getfield($field) =~ /^$/) {
2162 return $self->ut_coord($field, @_);
2168 =item ut_domain COLUMN
2170 Check/untaint host and domain names.
2175 my( $self, $field ) = @_;
2176 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2177 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2178 or return "Illegal (domain) $field: ". $self->getfield($field);
2179 $self->setfield($field,$1);
2183 =item ut_name COLUMN
2185 Check/untaint proper names; allows alphanumerics, spaces and the following
2186 punctuation: , . - '
2193 my( $self, $field ) = @_;
2194 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2195 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2196 $self->setfield($field,$1);
2202 Check/untaint zip codes.
2206 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2209 my( $self, $field, $country ) = @_;
2211 if ( $country eq 'US' ) {
2213 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2214 or return gettext('illegal_zip'). " $field for country $country: ".
2215 $self->getfield($field);
2216 $self->setfield($field, $1);
2218 } elsif ( $country eq 'CA' ) {
2220 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2221 or return gettext('illegal_zip'). " $field for country $country: ".
2222 $self->getfield($field);
2223 $self->setfield($field, "$1 $2");
2227 if ( $self->getfield($field) =~ /^\s*$/
2228 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2231 $self->setfield($field,'');
2233 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2234 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2235 $self->setfield($field,$1);
2243 =item ut_country COLUMN
2245 Check/untaint country codes. Country names are changed to codes, if possible -
2246 see L<Locale::Country>.
2251 my( $self, $field ) = @_;
2252 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2253 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2254 && country2code($1) ) {
2255 $self->setfield($field,uc(country2code($1)));
2258 $self->getfield($field) =~ /^(\w\w)$/
2259 or return "Illegal (country) $field: ". $self->getfield($field);
2260 $self->setfield($field,uc($1));
2264 =item ut_anything COLUMN
2266 Untaints arbitrary data. Be careful.
2271 my( $self, $field ) = @_;
2272 $self->getfield($field) =~ /^(.*)$/s
2273 or return "Illegal $field: ". $self->getfield($field);
2274 $self->setfield($field,$1);
2278 =item ut_enum COLUMN CHOICES_ARRAYREF
2280 Check/untaint a column, supplying all possible choices, like the "enum" type.
2285 my( $self, $field, $choices ) = @_;
2286 foreach my $choice ( @$choices ) {
2287 if ( $self->getfield($field) eq $choice ) {
2288 $self->setfield($choice);
2292 return "Illegal (enum) field $field: ". $self->getfield($field);
2295 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2297 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2298 on the column first.
2302 sub ut_foreign_key {
2303 my( $self, $field, $table, $foreign ) = @_;
2304 return '' if $no_check_foreign;
2305 qsearchs($table, { $foreign => $self->getfield($field) })
2306 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2307 " in $table.$foreign";
2311 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2313 Like ut_foreign_key, except the null value is also allowed.
2317 sub ut_foreign_keyn {
2318 my( $self, $field, $table, $foreign ) = @_;
2319 $self->getfield($field)
2320 ? $self->ut_foreign_key($field, $table, $foreign)
2324 =item ut_agentnum_acl
2326 Checks this column as an agentnum, taking into account the current users's
2331 sub ut_agentnum_acl {
2332 my( $self, $field, $null_acl ) = @_;
2334 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2335 return "Illegal agentnum: $error" if $error;
2337 my $curuser = $FS::CurrentUser::CurrentUser;
2339 if ( $self->$field() ) {
2341 return "Access denied"
2342 unless $curuser->agentnum($self->$field());
2346 return "Access denied"
2347 unless $curuser->access_right($null_acl);
2355 =item virtual_fields [ TABLE ]
2357 Returns a list of virtual fields defined for the table. This should not
2358 be exported, and should only be called as an instance or class method.
2362 sub virtual_fields {
2365 $table = $self->table or confess "virtual_fields called on non-table";
2367 confess "Unknown table $table" unless dbdef->table($table);
2369 return () unless dbdef->table('part_virtual_field');
2371 unless ( $virtual_fields_cache{$table} ) {
2372 my $query = 'SELECT name from part_virtual_field ' .
2373 "WHERE dbtable = '$table'";
2375 my $result = $dbh->selectcol_arrayref($query);
2376 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2378 $virtual_fields_cache{$table} = $result;
2381 @{$virtual_fields_cache{$table}};
2386 =item fields [ TABLE ]
2388 This is a wrapper for real_fields and virtual_fields. Code that called
2389 fields before should probably continue to call fields.
2394 my $something = shift;
2396 if($something->isa('FS::Record')) {
2397 $table = $something->table;
2399 $table = $something;
2400 $something = "FS::$table";
2402 return (real_fields($table), $something->virtual_fields());
2405 =item pvf FIELD_NAME
2407 Returns the FS::part_virtual_field object corresponding to a field in the
2408 record (specified by FIELD_NAME).
2413 my ($self, $name) = (shift, shift);
2415 if(grep /^$name$/, $self->virtual_fields) {
2416 return qsearchs('part_virtual_field', { dbtable => $self->table,
2422 =item vfieldpart_hashref TABLE
2424 Returns a hashref of virtual field names and vfieldparts applicable to the given
2429 sub vfieldpart_hashref {
2431 my $table = $self->table;
2433 return {} unless dbdef->table('part_virtual_field');
2436 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2437 "dbtable = '$table'";
2438 my $sth = $dbh->prepare($statement);
2439 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2440 return { map { $_->{name}, $_->{vfieldpart} }
2441 @{$sth->fetchall_arrayref({})} };
2445 =item encrypt($value)
2447 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2449 Returns the encrypted string.
2451 You should generally not have to worry about calling this, as the system handles this for you.
2456 my ($self, $value) = @_;
2459 if ($conf->exists('encryption')) {
2460 if ($self->is_encrypted($value)) {
2461 # Return the original value if it isn't plaintext.
2462 $encrypted = $value;
2465 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2466 # RSA doesn't like the empty string so let's pack it up
2467 # The database doesn't like the RSA data so uuencode it
2468 my $length = length($value)+1;
2469 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2471 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2478 =item is_encrypted($value)
2480 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2486 my ($self, $value) = @_;
2487 # Possible Bug - Some work may be required here....
2489 if ($value =~ /^M/ && length($value) > 80) {
2496 =item decrypt($value)
2498 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2500 You should generally not have to worry about calling this, as the system handles this for you.
2505 my ($self,$value) = @_;
2506 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2507 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2509 if (ref($rsa_decrypt) =~ /::RSA/) {
2510 my $encrypted = unpack ("u*", $value);
2511 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2512 if ($@) {warn "Decryption Failed"};
2520 #Initialize the Module
2521 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2523 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2524 $rsa_module = $conf->config('encryptionmodule');
2528 eval ("require $rsa_module"); # No need to import the namespace
2531 # Initialize Encryption
2532 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2533 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2534 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2537 # Intitalize Decryption
2538 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2539 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2540 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2544 =item h_search ACTION
2546 Given an ACTION, either "insert", or "delete", returns the appropriate history
2547 record corresponding to this record, if any.
2552 my( $self, $action ) = @_;
2554 my $table = $self->table;
2557 my $primary_key = dbdef->table($table)->primary_key;
2560 'table' => "h_$table",
2561 'hashref' => { $primary_key => $self->$primary_key(),
2562 'history_action' => $action,
2570 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2571 appropriate history record corresponding to this record, if any.
2576 my($self, $action) = @_;
2577 my $h = $self->h_search($action);
2578 $h ? $h->history_date : '';
2587 =item real_fields [ TABLE ]
2589 Returns a list of the real columns in the specified table. Called only by
2590 fields() and other subroutines elsewhere in FS::Record.
2597 my($table_obj) = dbdef->table($table);
2598 confess "Unknown table $table" unless $table_obj;
2599 $table_obj->columns;
2602 =item _quote VALUE, TABLE, COLUMN
2604 This is an internal function used to construct SQL statements. It returns
2605 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2606 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2611 my($value, $table, $column) = @_;
2612 my $column_obj = dbdef->table($table)->column($column);
2613 my $column_type = $column_obj->type;
2614 my $nullable = $column_obj->null;
2616 warn " $table.$column: $value ($column_type".
2617 ( $nullable ? ' NULL' : ' NOT NULL' ).
2618 ")\n" if $DEBUG > 2;
2620 if ( $value eq '' && $nullable ) {
2622 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2623 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2626 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2627 ! $column_type =~ /(char|binary|text)$/i ) {
2636 This is deprecated. Don't use it.
2638 It returns a hash-type list with the fields of this record's table set true.
2643 carp "warning: hfields is deprecated";
2646 foreach (fields($table)) {
2655 "$_: ". $self->getfield($_). "|"
2656 } (fields($self->table)) );
2659 sub DESTROY { return; }
2663 # #use Carp qw(cluck);
2664 # #cluck "DESTROYING $self";
2665 # warn "DESTROYING $self";
2669 # return ! eval { join('',@_), kill 0; 1; };
2672 =item str2time_sql [ DRIVER_NAME ]
2674 Returns a function to convert to unix time based on database type, such as
2675 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2676 the str2time_sql_closing method to return a closing string rather than just
2677 using a closing parenthesis as previously suggested.
2679 You can pass an optional driver name such as "Pg", "mysql" or
2680 $dbh->{Driver}->{Name} to return a function for that database instead of
2681 the current database.
2686 my $driver = shift || driver_name;
2688 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2689 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2691 warn "warning: unknown database type $driver; guessing how to convert ".
2692 "dates to UNIX timestamps";
2693 return 'EXTRACT(EPOCH FROM ';
2697 =item str2time_sql_closing [ DRIVER_NAME ]
2699 Returns the closing suffix of a function to convert to unix time based on
2700 database type, such as ")::integer" for Pg or ")" for mysql.
2702 You can pass an optional driver name such as "Pg", "mysql" or
2703 $dbh->{Driver}->{Name} to return a function for that database instead of
2704 the current database.
2708 sub str2time_sql_closing {
2709 my $driver = shift || driver_name;
2711 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2719 This module should probably be renamed, since much of the functionality is
2720 of general use. It is not completely unlike Adapter::DBI (see below).
2722 Exported qsearch and qsearchs should be deprecated in favor of method calls
2723 (against an FS::Record object like the old search and searchs that qsearch
2724 and qsearchs were on top of.)
2726 The whole fields / hfields mess should be removed.
2728 The various WHERE clauses should be subroutined.
2730 table string should be deprecated in favor of DBIx::DBSchema::Table.
2732 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2733 true maps to the database (and WHERE clauses) would also help.
2735 The ut_ methods should ask the dbdef for a default length.
2737 ut_sqltype (like ut_varchar) should all be defined
2739 A fallback check method should be provided which uses the dbdef.
2741 The ut_money method assumes money has two decimal digits.
2743 The Pg money kludge in the new method only strips `$'.
2745 The ut_phonen method only checks US-style phone numbers.
2747 The _quote function should probably use ut_float instead of a regex.
2749 All the subroutines probably should be methods, here or elsewhere.
2751 Probably should borrow/use some dbdef methods where appropriate (like sub
2754 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2755 or allow it to be set. Working around it is ugly any way around - DBI should
2756 be fixed. (only affects RDBMS which return uppercase column names)
2758 ut_zip should take an optional country like ut_phone.
2762 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2764 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.