4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 %virtual_fields_cache $nowarn_identical $no_update_diff );
8 use Carp qw(carp cluck croak confess);
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.25;
13 #use DBIx::DBSchema 0.33; #when check for ->can('unique_singles') is sub insert
15 use FS::UID qw(dbh getotaker datasrc driver_name);
17 use FS::Schema qw(dbdef);
19 use FS::Msgcat qw(gettext);
22 use FS::part_virtual_field;
28 #export dbdef for now... everything else expects to find it here
29 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
30 str2time_sql str2time_sql_closing );
35 $nowarn_identical = 0;
43 FS::UID->install_callback( sub {
45 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
51 FS::Record - Database record objects
56 use FS::Record qw(dbh fields qsearch qsearchs);
58 $record = new FS::Record 'table', \%hash;
59 $record = new FS::Record 'table', { 'column' => 'value', ... };
61 $record = qsearchs FS::Record 'table', \%hash;
62 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
63 @records = qsearch FS::Record 'table', \%hash;
64 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
66 $table = $record->table;
67 $dbdef_table = $record->dbdef_table;
69 $value = $record->get('column');
70 $value = $record->getfield('column');
71 $value = $record->column;
73 $record->set( 'column' => 'value' );
74 $record->setfield( 'column' => 'value' );
75 $record->column('value');
77 %hash = $record->hash;
79 $hashref = $record->hashref;
81 $error = $record->insert;
83 $error = $record->delete;
85 $error = $new_record->replace($old_record);
87 # external use deprecated - handled by the database (at least for Pg, mysql)
88 $value = $record->unique('column');
90 $error = $record->ut_float('column');
91 $error = $record->ut_floatn('column');
92 $error = $record->ut_number('column');
93 $error = $record->ut_numbern('column');
94 $error = $record->ut_snumber('column');
95 $error = $record->ut_snumbern('column');
96 $error = $record->ut_money('column');
97 $error = $record->ut_text('column');
98 $error = $record->ut_textn('column');
99 $error = $record->ut_alpha('column');
100 $error = $record->ut_alphan('column');
101 $error = $record->ut_phonen('column');
102 $error = $record->ut_anything('column');
103 $error = $record->ut_name('column');
105 $quoted_value = _quote($value,'table','field');
108 $fields = hfields('table');
109 if ( $fields->{Field} ) { # etc.
111 @fields = fields 'table'; #as a subroutine
112 @fields = $record->fields; #as a method call
117 (Mostly) object-oriented interface to database records. Records are currently
118 implemented on top of DBI. FS::Record is intended as a base class for
119 table-specific classes to inherit from, i.e. FS::cust_main.
125 =item new [ TABLE, ] HASHREF
127 Creates a new record. It doesn't store it in the database, though. See
128 L<"insert"> for that.
130 Note that the object stores this hash reference, not a distinct copy of the
131 hash it points to. You can ask the object for a copy with the I<hash>
134 TABLE can only be omitted when a dervived class overrides the table method.
140 my $class = ref($proto) || $proto;
142 bless ($self, $class);
144 unless ( defined ( $self->table ) ) {
145 $self->{'Table'} = shift;
146 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
149 $self->{'Hash'} = shift;
151 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
152 $self->{'Hash'}{$field}='';
155 $self->_rebless if $self->can('_rebless');
157 $self->{'modified'} = 0;
159 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
166 my $class = ref($proto) || $proto;
168 bless ($self, $class);
170 $self->{'Table'} = shift unless defined ( $self->table );
172 my $hashref = $self->{'Hash'} = shift;
174 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
175 my $obj = $cache->cache->{$hashref->{$cache->key}};
176 $obj->_cache($hashref, $cache) if $obj->can('_cache');
179 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
186 my $class = ref($proto) || $proto;
188 bless ($self, $class);
189 if ( defined $self->table ) {
190 cluck "create constructor is deprecated, use new!";
193 croak "FS::Record::create called (not from a subclass)!";
197 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
199 Searches the database for all records matching (at least) the key/value pairs
200 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
201 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
204 The preferred usage is to pass a hash reference of named parameters:
206 my @records = qsearch( {
207 'table' => 'table_name',
208 'hashref' => { 'field' => 'value'
209 'field' => { 'op' => '<',
214 #these are optional...
216 'extra_sql' => 'AND field ',
217 'order_by' => 'ORDER BY something',
218 #'cache_obj' => '', #optional
219 'addl_from' => 'LEFT JOIN othtable USING ( field )',
223 Much code still uses old-style positional parameters, this is also probably
224 fine in the common case where there are only two parameters:
226 my @records = qsearch( 'table', { 'field' => 'value' } );
228 ###oops, argh, FS::Record::new only lets us create database fields.
229 #Normal behaviour if SELECT is not specified is `*', as in
230 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
231 #feature where you can specify SELECT - remember, the objects returned,
232 #although blessed into the appropriate `FS::TABLE' package, will only have the
233 #fields you specify. This might have unwanted results if you then go calling
234 #regular FS::TABLE methods
240 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
241 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
243 $stable = $opt->{'table'} or die "table name is required";
244 $record = $opt->{'hashref'} || {};
245 $select = $opt->{'select'} || '*';
246 $extra_sql = $opt->{'extra_sql'} || '';
247 $order_by = $opt->{'order_by'} || '';
248 $cache = $opt->{'cache_obj'} || '';
249 $addl_from = $opt->{'addl_from'} || '';
251 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
255 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
257 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
261 my $table = $cache ? $cache->table : $stable;
262 my $dbdef_table = dbdef->table($table)
263 or die "No schema for table $table found - ".
264 "do you need to run freeside-upgrade?";
265 my $pkey = $dbdef_table->primary_key;
267 my @real_fields = grep exists($record->{$_}), real_fields($table);
269 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
270 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
272 cluck "warning: FS::$table not loaded; virtual fields not searchable";
273 @virtual_fields = ();
276 my $statement = "SELECT $select FROM $stable";
277 $statement .= " $addl_from" if $addl_from;
278 if ( @real_fields or @virtual_fields ) {
279 $statement .= ' WHERE '. join(' AND ',
284 if ( ref($record->{$_}) ) {
285 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
286 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
287 if ( uc($op) eq 'ILIKE' ) {
289 $record->{$_}{'value'} = lc($record->{$_}{'value'});
290 $column = "LOWER($_)";
292 $record->{$_} = $record->{$_}{'value'}
295 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
297 if ( driver_name eq 'Pg' ) {
298 my $type = dbdef->table($table)->column($column)->type;
299 if ( $type =~ /(int|(big)?serial)/i ) {
300 qq-( $column IS NULL )-;
302 qq-( $column IS NULL OR $column = '' )-;
305 qq-( $column IS NULL OR $column = "" )-;
307 } elsif ( $op eq '!=' ) {
308 if ( driver_name eq 'Pg' ) {
309 my $type = dbdef->table($table)->column($column)->type;
310 if ( $type =~ /(int|(big)?serial)/i ) {
311 qq-( $column IS NOT NULL )-;
313 qq-( $column IS NOT NULL AND $column != '' )-;
316 qq-( $column IS NOT NULL AND $column != "" )-;
319 if ( driver_name eq 'Pg' ) {
320 qq-( $column $op '' )-;
322 qq-( $column $op "" )-;
332 if ( ref($record->{$_}) ) {
333 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
334 if ( uc($op) eq 'ILIKE' ) {
336 $record->{$_}{'value'} = lc($record->{$_}{'value'});
337 $column = "LOWER($_)";
339 $record->{$_} = $record->{$_}{'value'};
342 # ... EXISTS ( SELECT name, value FROM part_virtual_field
344 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
345 # WHERE recnum = svc_acct.svcnum
346 # AND (name, value) = ('egad', 'brain') )
348 my $value = $record->{$_};
352 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
353 "( SELECT part_virtual_field.name, virtual_field.value ".
354 "FROM part_virtual_field JOIN virtual_field ".
355 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
356 "WHERE virtual_field.recnum = ${table}.${pkey} ".
357 "AND part_virtual_field.name = '${column}'".
359 " AND virtual_field.value ${op} '${value}'"
363 } @virtual_fields ) );
367 $statement .= " $extra_sql" if defined($extra_sql);
368 $statement .= " $order_by" if defined($order_by);
370 warn "[debug]$me $statement\n" if $DEBUG > 1;
371 my $sth = $dbh->prepare($statement)
372 or croak "$dbh->errstr doing $statement";
377 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
379 my $value = $record->{$field};
380 #done above in 1.7# $value = $value->{'value'} if ref($value);
381 my $type = dbdef->table($table)->column($field)->type;
383 my $TYPE = SQL_VARCHAR;
384 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
387 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
388 } elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
389 || ( $type =~ /(real|float4)/i
390 && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
396 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
400 # $sth->execute( map $record->{$_},
401 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
402 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
404 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
406 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
407 @virtual_fields = "FS::$table"->virtual_fields;
409 cluck "warning: FS::$table not loaded; virtual fields not returned either";
410 @virtual_fields = ();
414 tie %result, "Tie::IxHash";
415 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
416 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
417 %result = map { $_->{$pkey}, $_ } @stuff;
419 @result{@stuff} = @stuff;
424 if ( keys(%result) and @virtual_fields ) {
426 "SELECT virtual_field.recnum, part_virtual_field.name, ".
427 "virtual_field.value ".
428 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
429 "WHERE part_virtual_field.dbtable = '$table' AND ".
430 "virtual_field.recnum IN (".
431 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
432 join(q!', '!, @virtual_fields) . "')";
433 warn "[debug]$me $statement\n" if $DEBUG > 1;
434 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
435 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
437 foreach (@{ $sth->fetchall_arrayref({}) }) {
438 my $recnum = $_->{recnum};
439 my $name = $_->{name};
440 my $value = $_->{value};
441 if (exists($result{$recnum})) {
442 $result{$recnum}->{$name} = $value;
447 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
448 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
449 #derivied class didn't override new method, so this optimization is safe
452 new_or_cached( "FS::$table", { %{$_} }, $cache )
456 new( "FS::$table", { %{$_} } )
460 #okay, its been tested
461 # warn "untested code (class FS::$table uses custom new method)";
463 eval 'FS::'. $table. '->new( { %{$_} } )';
467 # Check for encrypted fields and decrypt them.
468 ## only in the local copy, not the cached object
469 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
470 # the initial search for
472 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
473 foreach my $record (@return) {
474 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
475 # Set it directly... This may cause a problem in the future...
476 $record->setfield($field, $record->decrypt($record->getfield($field)));
481 cluck "warning: FS::$table not loaded; returning FS::Record objects";
483 FS::Record->new( $table, { %{$_} } );
489 =item by_key PRIMARY_KEY_VALUE
491 This is a class method that returns the record with the given primary key
492 value. This method is only useful in FS::Record subclasses. For example:
494 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
498 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
503 my ($class, $pkey_value) = @_;
505 my $table = $class->table
506 or croak "No table for $class found";
508 my $dbdef_table = dbdef->table($table)
509 or die "No schema for table $table found - ".
510 "do you need to create it or run dbdef-create?";
511 my $pkey = $dbdef_table->primary_key
512 or die "No primary key for table $table";
514 return qsearchs($table, { $pkey => $pkey_value });
517 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
519 Experimental JOINed search method. Using this method, you can execute a
520 single SELECT spanning multiple tables, and cache the results for subsequent
521 method calls. Interface will almost definately change in an incompatible
529 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
530 my $cache = FS::SearchCache->new( $ptable, $pkey );
533 grep { !$saw{$_->getfield($pkey)}++ }
534 qsearch($table, $record, $select, $extra_sql, $cache )
538 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
540 Same as qsearch, except that if more than one record matches, it B<carp>s but
541 returns the first. If this happens, you either made a logic error in asking
542 for a single item, or your data is corrupted.
546 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
548 my(@result) = qsearch(@_);
549 cluck "warning: Multiple records in scalar search ($table)"
550 if scalar(@result) > 1;
551 #should warn more vehemently if the search was on a primary key?
552 scalar(@result) ? ($result[0]) : ();
563 Returns the table name.
568 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
575 Returns the DBIx::DBSchema::Table object for the table.
581 my($table)=$self->table;
582 dbdef->table($table);
587 Returns the primary key for the table.
593 my $pkey = $self->dbdef_table->primary_key;
596 =item get, getfield COLUMN
598 Returns the value of the column/field/key COLUMN.
603 my($self,$field) = @_;
604 # to avoid "Use of unitialized value" errors
605 if ( defined ( $self->{Hash}->{$field} ) ) {
606 $self->{Hash}->{$field};
616 =item set, setfield COLUMN, VALUE
618 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
623 my($self,$field,$value) = @_;
624 $self->{'modified'} = 1;
625 $self->{'Hash'}->{$field} = $value;
632 =item AUTLOADED METHODS
634 $record->column is a synonym for $record->get('column');
636 $record->column('value') is a synonym for $record->set('column','value');
643 my($field)=$AUTOLOAD;
645 if ( defined($value) ) {
646 confess "errant AUTOLOAD $field for $self (arg $value)"
647 unless ref($self) && $self->can('setfield');
648 $self->setfield($field,$value);
650 confess "errant AUTOLOAD $field for $self (no args)"
651 unless ref($self) && $self->can('getfield');
652 $self->getfield($field);
658 # my $field = $AUTOLOAD;
660 # if ( defined($_[1]) ) {
661 # $_[0]->setfield($field, $_[1]);
663 # $_[0]->getfield($field);
669 Returns a list of the column/value pairs, usually for assigning to a new hash.
671 To make a distinct duplicate of an FS::Record object, you can do:
673 $new = new FS::Record ( $old->table, { $old->hash } );
679 confess $self. ' -> hash: Hash attribute is undefined'
680 unless defined($self->{'Hash'});
681 %{ $self->{'Hash'} };
686 Returns a reference to the column/value hash. This may be deprecated in the
687 future; if there's a reason you can't just use the autoloaded or get/set
699 Returns true if any of this object's values have been modified with set (or via
700 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
710 =item select_for_update
712 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
717 sub select_for_update {
719 my $primary_key = $self->primary_key;
722 'table' => $self->table,
723 'hashref' => { $primary_key => $self->$primary_key() },
724 'extra_sql' => 'FOR UPDATE',
730 Inserts this record to the database. If there is an error, returns the error,
731 otherwise returns false.
739 warn "$self -> insert" if $DEBUG;
741 my $error = $self->check;
742 return $error if $error;
744 #single-field unique keys are given a value if false
745 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
746 foreach ( $self->dbdef_table->can('unique_singles')
747 ? $self->dbdef_table->unique_singles
748 : $self->dbdef_table->unique->singles
750 $self->unique($_) unless $self->getfield($_);
753 #and also the primary key, if the database isn't going to
754 my $primary_key = $self->dbdef_table->primary_key;
756 if ( $primary_key ) {
757 my $col = $self->dbdef_table->column($primary_key);
760 uc($col->type) =~ /^(BIG)?SERIAL\d?/
761 || ( driver_name eq 'Pg'
762 && defined($col->default)
763 && $col->default =~ /^nextval\(/i
765 || ( driver_name eq 'mysql'
766 && defined($col->local)
767 && $col->local =~ /AUTO_INCREMENT/i
769 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
772 my $table = $self->table;
775 # Encrypt before the database
776 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
777 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
778 $self->{'saved'} = $self->getfield($field);
779 $self->setfield($field, $self->encrypt($self->getfield($field)));
784 #false laziness w/delete
786 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
789 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
792 my $statement = "INSERT INTO $table ";
793 if ( @real_fields ) {
796 join( ', ', @real_fields ).
798 join( ', ', @values ).
802 $statement .= 'DEFAULT VALUES';
804 warn "[debug]$me $statement\n" if $DEBUG > 1;
805 my $sth = dbh->prepare($statement) or return dbh->errstr;
807 local $SIG{HUP} = 'IGNORE';
808 local $SIG{INT} = 'IGNORE';
809 local $SIG{QUIT} = 'IGNORE';
810 local $SIG{TERM} = 'IGNORE';
811 local $SIG{TSTP} = 'IGNORE';
812 local $SIG{PIPE} = 'IGNORE';
814 $sth->execute or return $sth->errstr;
816 # get inserted id from the database, if applicable & needed
817 if ( $db_seq && ! $self->getfield($primary_key) ) {
818 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
822 if ( driver_name eq 'Pg' ) {
824 #my $oid = $sth->{'pg_oid_status'};
825 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
827 my $default = $self->dbdef_table->column($primary_key)->default;
828 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
829 dbh->rollback if $FS::UID::AutoCommit;
830 return "can't parse $table.$primary_key default value".
831 " for sequence name: $default";
835 my $i_sql = "SELECT currval('$sequence')";
836 my $i_sth = dbh->prepare($i_sql) or do {
837 dbh->rollback if $FS::UID::AutoCommit;
840 $i_sth->execute() or do { #$i_sth->execute($oid)
841 dbh->rollback if $FS::UID::AutoCommit;
842 return $i_sth->errstr;
844 $insertid = $i_sth->fetchrow_arrayref->[0];
846 } elsif ( driver_name eq 'mysql' ) {
848 $insertid = dbh->{'mysql_insertid'};
849 # work around mysql_insertid being null some of the time, ala RT :/
850 unless ( $insertid ) {
851 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
852 "using SELECT LAST_INSERT_ID();";
853 my $i_sql = "SELECT LAST_INSERT_ID()";
854 my $i_sth = dbh->prepare($i_sql) or do {
855 dbh->rollback if $FS::UID::AutoCommit;
858 $i_sth->execute or do {
859 dbh->rollback if $FS::UID::AutoCommit;
860 return $i_sth->errstr;
862 $insertid = $i_sth->fetchrow_arrayref->[0];
867 dbh->rollback if $FS::UID::AutoCommit;
868 return "don't know how to retreive inserted ids from ". driver_name.
869 ", try using counterfiles (maybe run dbdef-create?)";
873 $self->setfield($primary_key, $insertid);
878 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
879 $self->virtual_fields;
880 if (@virtual_fields) {
881 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
883 my $vfieldpart = $self->vfieldpart_hashref;
885 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
888 my $v_sth = dbh->prepare($v_statement) or do {
889 dbh->rollback if $FS::UID::AutoCommit;
893 foreach (keys(%v_values)) {
894 $v_sth->execute($self->getfield($primary_key),
898 dbh->rollback if $FS::UID::AutoCommit;
899 return $v_sth->errstr;
906 if ( defined dbdef->table('h_'. $table) ) {
907 my $h_statement = $self->_h_statement('insert');
908 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
909 $h_sth = dbh->prepare($h_statement) or do {
910 dbh->rollback if $FS::UID::AutoCommit;
916 $h_sth->execute or return $h_sth->errstr if $h_sth;
918 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
920 # Now that it has been saved, reset the encrypted fields so that $new
922 foreach my $field (keys %{$saved}) {
923 $self->setfield($field, $saved->{$field});
931 Depriciated (use insert instead).
936 cluck "warning: FS::Record::add deprecated!";
937 insert @_; #call method in this scope
942 Delete this record from the database. If there is an error, returns the error,
943 otherwise returns false.
950 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
952 $self->getfield($_) eq ''
953 #? "( $_ IS NULL OR $_ = \"\" )"
954 ? ( driver_name eq 'Pg'
956 : "( $_ IS NULL OR $_ = \"\" )"
958 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
959 } ( $self->dbdef_table->primary_key )
960 ? ( $self->dbdef_table->primary_key)
961 : real_fields($self->table)
963 warn "[debug]$me $statement\n" if $DEBUG > 1;
964 my $sth = dbh->prepare($statement) or return dbh->errstr;
967 if ( defined dbdef->table('h_'. $self->table) ) {
968 my $h_statement = $self->_h_statement('delete');
969 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
970 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
975 my $primary_key = $self->dbdef_table->primary_key;
978 my $vfp = $self->vfieldpart_hashref;
979 foreach($self->virtual_fields) {
980 next if $self->getfield($_) eq '';
981 unless(@del_vfields) {
982 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
983 $v_sth = dbh->prepare($st) or return dbh->errstr;
985 push @del_vfields, $_;
988 local $SIG{HUP} = 'IGNORE';
989 local $SIG{INT} = 'IGNORE';
990 local $SIG{QUIT} = 'IGNORE';
991 local $SIG{TERM} = 'IGNORE';
992 local $SIG{TSTP} = 'IGNORE';
993 local $SIG{PIPE} = 'IGNORE';
995 my $rc = $sth->execute or return $sth->errstr;
996 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
997 $h_sth->execute or return $h_sth->errstr if $h_sth;
998 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
999 or return $v_sth->errstr
1000 foreach (@del_vfields);
1002 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1004 #no need to needlessly destoy the data either (causes problems actually)
1005 #undef $self; #no need to keep object!
1012 Depriciated (use delete instead).
1017 cluck "warning: FS::Record::del deprecated!";
1018 &delete(@_); #call method in this scope
1021 =item replace OLD_RECORD
1023 Replace the OLD_RECORD with this one in the database. If there is an error,
1024 returns the error, otherwise returns false.
1029 my ($new, $old) = (shift, shift);
1031 $old = $new->replace_old unless defined($old);
1033 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1035 if ( $new->can('replace_check') ) {
1036 my $error = $new->replace_check($old);
1037 return $error if $error;
1040 return "Records not in same table!" unless $new->table eq $old->table;
1042 my $primary_key = $old->dbdef_table->primary_key;
1043 return "Can't change primary key $primary_key ".
1044 'from '. $old->getfield($primary_key).
1045 ' to ' . $new->getfield($primary_key)
1047 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1049 my $error = $new->check;
1050 return $error if $error;
1052 # Encrypt for replace
1053 my $conf = new FS::Conf;
1055 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1056 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1057 $saved->{$field} = $new->getfield($field);
1058 $new->setfield($field, $new->encrypt($new->getfield($field)));
1062 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1063 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1064 ? ($_, $new->getfield($_)) : () } $old->fields;
1066 unless (keys(%diff) || $no_update_diff ) {
1067 carp "[warning]$me $new -> replace $old: records identical"
1068 unless $nowarn_identical;
1072 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1074 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1075 } real_fields($old->table)
1080 if ( $old->getfield($_) eq '' ) {
1082 #false laziness w/qsearch
1083 if ( driver_name eq 'Pg' ) {
1084 my $type = $old->dbdef_table->column($_)->type;
1085 if ( $type =~ /(int|(big)?serial)/i ) {
1088 qq-( $_ IS NULL OR $_ = '' )-;
1091 qq-( $_ IS NULL OR $_ = "" )-;
1095 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1098 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1101 warn "[debug]$me $statement\n" if $DEBUG > 1;
1102 my $sth = dbh->prepare($statement) or return dbh->errstr;
1105 if ( defined dbdef->table('h_'. $old->table) ) {
1106 my $h_old_statement = $old->_h_statement('replace_old');
1107 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1108 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1114 if ( defined dbdef->table('h_'. $new->table) ) {
1115 my $h_new_statement = $new->_h_statement('replace_new');
1116 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1117 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1122 # For virtual fields we have three cases with different SQL
1123 # statements: add, replace, delete
1127 my (@add_vfields, @rep_vfields, @del_vfields);
1128 my $vfp = $old->vfieldpart_hashref;
1129 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1130 if($diff{$_} eq '') {
1132 unless(@del_vfields) {
1133 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1134 "AND vfieldpart = ?";
1135 warn "[debug]$me $st\n" if $DEBUG > 2;
1136 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1138 push @del_vfields, $_;
1139 } elsif($old->getfield($_) eq '') {
1141 unless(@add_vfields) {
1142 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1144 warn "[debug]$me $st\n" if $DEBUG > 2;
1145 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1147 push @add_vfields, $_;
1150 unless(@rep_vfields) {
1151 my $st = "UPDATE virtual_field SET value = ? ".
1152 "WHERE recnum = ? AND vfieldpart = ?";
1153 warn "[debug]$me $st\n" if $DEBUG > 2;
1154 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1156 push @rep_vfields, $_;
1160 local $SIG{HUP} = 'IGNORE';
1161 local $SIG{INT} = 'IGNORE';
1162 local $SIG{QUIT} = 'IGNORE';
1163 local $SIG{TERM} = 'IGNORE';
1164 local $SIG{TSTP} = 'IGNORE';
1165 local $SIG{PIPE} = 'IGNORE';
1167 my $rc = $sth->execute or return $sth->errstr;
1168 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1169 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1170 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1172 $v_del_sth->execute($old->getfield($primary_key),
1174 or return $v_del_sth->errstr
1175 foreach(@del_vfields);
1177 $v_add_sth->execute($new->getfield($_),
1178 $old->getfield($primary_key),
1180 or return $v_add_sth->errstr
1181 foreach(@add_vfields);
1183 $v_rep_sth->execute($new->getfield($_),
1184 $old->getfield($primary_key),
1186 or return $v_rep_sth->errstr
1187 foreach(@rep_vfields);
1189 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1191 # Now that it has been saved, reset the encrypted fields so that $new
1192 # can still be used.
1193 foreach my $field (keys %{$saved}) {
1194 $new->setfield($field, $saved->{$field});
1202 my( $self ) = shift;
1203 warn "[$me] replace called with no arguments; autoloading old record\n"
1206 my $primary_key = $self->dbdef_table->primary_key;
1207 if ( $primary_key ) {
1208 $self->by_key( $self->$primary_key() ) #this is what's returned
1209 or croak "can't find ". $self->table. ".$primary_key ".
1210 $self->$primary_key();
1212 croak $self->table. " has no primary key; pass old record as argument";
1219 Depriciated (use replace instead).
1224 cluck "warning: FS::Record::rep deprecated!";
1225 replace @_; #call method in this scope
1230 Checks virtual fields (using check_blocks). Subclasses should still provide
1231 a check method to validate real fields, foreign keys, etc., and call this
1232 method via $self->SUPER::check.
1234 (FIXME: Should this method try to make sure that it I<is> being called from
1235 a subclass's check method, to keep the current semantics as far as possible?)
1240 #confess "FS::Record::check not implemented; supply one in subclass!";
1243 foreach my $field ($self->virtual_fields) {
1244 for ($self->getfield($field)) {
1245 # See notes on check_block in FS::part_virtual_field.
1246 eval $self->pvf($field)->check_block;
1248 #this is bad, probably want to follow the stack backtrace up and see
1250 my $err = "Fatal error checking $field for $self";
1252 return "$err (see log for backtrace): $@";
1255 $self->setfield($field, $_);
1262 my( $self, $action, $time ) = @_;
1266 my %nohistory = map { $_=>1 } $self->nohistory_fields;
1269 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1270 real_fields($self->table);
1273 # If we're encrypting then don't store the payinfo in the history
1274 if ( $conf->exists('encryption') ) {
1275 @fields = grep { $_ ne 'payinfo' } @fields;
1278 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1280 "INSERT INTO h_". $self->table. " ( ".
1281 join(', ', qw(history_date history_user history_action), @fields ).
1283 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1290 B<Warning>: External use is B<deprecated>.
1292 Replaces COLUMN in record with a unique number, using counters in the
1293 filesystem. Used by the B<insert> method on single-field unique columns
1294 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1295 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1297 Returns the new value.
1302 my($self,$field) = @_;
1303 my($table)=$self->table;
1305 croak "Unique called on field $field, but it is ",
1306 $self->getfield($field),
1308 if $self->getfield($field);
1310 #warn "table $table is tainted" if is_tainted($table);
1311 #warn "field $field is tainted" if is_tainted($field);
1313 my($counter) = new File::CounterFile "$table.$field",0;
1315 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1317 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1320 my $index = $counter->inc;
1321 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1323 $index =~ /^(\d*)$/;
1326 $self->setfield($field,$index);
1330 =item ut_float COLUMN
1332 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1333 null. If there is an error, returns the error, otherwise returns false.
1338 my($self,$field)=@_ ;
1339 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1340 $self->getfield($field) =~ /^(\d+)$/ ||
1341 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1342 $self->getfield($field) =~ /^(\d+e\d+)$/)
1343 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1344 $self->setfield($field,$1);
1347 =item ut_floatn COLUMN
1349 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1350 null. If there is an error, returns the error, otherwise returns false.
1354 #false laziness w/ut_ipn
1356 my( $self, $field ) = @_;
1357 if ( $self->getfield($field) =~ /^()$/ ) {
1358 $self->setfield($field,'');
1361 $self->ut_float($field);
1365 =item ut_snumber COLUMN
1367 Check/untaint signed numeric data (whole numbers). If there is an error,
1368 returns the error, otherwise returns false.
1373 my($self, $field) = @_;
1374 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1375 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1376 $self->setfield($field, "$1$2");
1380 =item ut_snumbern COLUMN
1382 Check/untaint signed numeric data (whole numbers). If there is an error,
1383 returns the error, otherwise returns false.
1388 my($self, $field) = @_;
1389 $self->getfield($field) =~ /^(-?)\s*(\d*)$/
1390 or return "Illegal (numeric) $field: ". $self->getfield($field);
1392 return "Illegal (numeric) $field: ". $self->getfield($field)
1395 $self->setfield($field, "$1$2");
1399 =item ut_number COLUMN
1401 Check/untaint simple numeric data (whole numbers). May not be null. If there
1402 is an error, returns the error, otherwise returns false.
1407 my($self,$field)=@_;
1408 $self->getfield($field) =~ /^(\d+)$/
1409 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1410 $self->setfield($field,$1);
1414 =item ut_numbern COLUMN
1416 Check/untaint simple numeric data (whole numbers). May be null. If there is
1417 an error, returns the error, otherwise returns false.
1422 my($self,$field)=@_;
1423 $self->getfield($field) =~ /^(\d*)$/
1424 or return "Illegal (numeric) $field: ". $self->getfield($field);
1425 $self->setfield($field,$1);
1429 =item ut_money COLUMN
1431 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1432 is an error, returns the error, otherwise returns false.
1437 my($self,$field)=@_;
1438 $self->setfield($field, 0) if $self->getfield($field) eq '';
1439 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1440 or return "Illegal (money) $field: ". $self->getfield($field);
1441 #$self->setfield($field, "$1$2$3" || 0);
1442 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1446 =item ut_text COLUMN
1448 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1449 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
1450 May not be null. If there is an error, returns the error, otherwise returns
1456 my($self,$field)=@_;
1457 #warn "msgcat ". \&msgcat. "\n";
1458 #warn "notexist ". \¬exist. "\n";
1459 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1460 $self->getfield($field)
1461 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
1462 or return gettext('illegal_or_empty_text'). " $field: ".
1463 $self->getfield($field);
1464 $self->setfield($field,$1);
1468 =item ut_textn COLUMN
1470 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1471 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1472 May be null. If there is an error, returns the error, otherwise returns false.
1477 my($self,$field)=@_;
1478 $self->getfield($field)
1479 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1480 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1481 $self->setfield($field,$1);
1485 =item ut_alpha COLUMN
1487 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1488 an error, returns the error, otherwise returns false.
1493 my($self,$field)=@_;
1494 $self->getfield($field) =~ /^(\w+)$/
1495 or return "Illegal or empty (alphanumeric) $field: ".
1496 $self->getfield($field);
1497 $self->setfield($field,$1);
1501 =item ut_alpha COLUMN
1503 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1504 error, returns the error, otherwise returns false.
1509 my($self,$field)=@_;
1510 $self->getfield($field) =~ /^(\w*)$/
1511 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1512 $self->setfield($field,$1);
1516 =item ut_alpha_lower COLUMN
1518 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1519 there is an error, returns the error, otherwise returns false.
1523 sub ut_alpha_lower {
1524 my($self,$field)=@_;
1525 $self->getfield($field) =~ /[[:upper:]]/
1526 and return "Uppercase characters are not permitted in $field";
1527 $self->ut_alpha($field);
1530 =item ut_phonen COLUMN [ COUNTRY ]
1532 Check/untaint phone numbers. May be null. If there is an error, returns
1533 the error, otherwise returns false.
1535 Takes an optional two-letter ISO country code; without it or with unsupported
1536 countries, ut_phonen simply calls ut_alphan.
1541 my( $self, $field, $country ) = @_;
1542 return $self->ut_alphan($field) unless defined $country;
1543 my $phonen = $self->getfield($field);
1544 if ( $phonen eq '' ) {
1545 $self->setfield($field,'');
1546 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1548 $phonen = $conf->config('cust_main-default_areacode').$phonen
1549 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
1550 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1551 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1552 $phonen = "$1-$2-$3";
1553 $phonen .= " x$4" if $4;
1554 $self->setfield($field,$phonen);
1556 warn "warning: don't know how to check phone numbers for country $country";
1557 return $self->ut_textn($field);
1564 Check/untaint hexadecimal values.
1569 my($self, $field) = @_;
1570 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1571 or return "Illegal (hex) $field: ". $self->getfield($field);
1572 $self->setfield($field, uc($1));
1576 =item ut_hexn COLUMN
1578 Check/untaint hexadecimal values. May be null.
1583 my($self, $field) = @_;
1584 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1585 or return "Illegal (hex) $field: ". $self->getfield($field);
1586 $self->setfield($field, uc($1));
1591 Check/untaint ip addresses. IPv4 only for now.
1596 my( $self, $field ) = @_;
1597 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1598 or return "Illegal (IP address) $field: ". $self->getfield($field);
1599 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1600 $self->setfield($field, "$1.$2.$3.$4");
1606 Check/untaint ip addresses. IPv4 only for now. May be null.
1611 my( $self, $field ) = @_;
1612 if ( $self->getfield($field) =~ /^()$/ ) {
1613 $self->setfield($field,'');
1616 $self->ut_ip($field);
1620 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
1622 Check/untaint coordinates.
1623 Accepts the following forms:
1633 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
1634 The latter form (that is, the MMM are thousands of minutes) is
1635 assumed if the "MMM" is exactly three digits or two digits > 59.
1637 To be safe, just use the DDD.DDDDD form.
1639 If LOWER or UPPER are specified, then the coordinate is checked
1640 for lower and upper bounds, respectively.
1646 my ($self, $field) = (shift, shift);
1648 my $lower = shift if scalar(@_);
1649 my $upper = shift if scalar(@_);
1650 my $coord = $self->getfield($field);
1651 my $neg = $coord =~ s/^(-)//;
1653 my ($d, $m, $s) = (0, 0, 0);
1656 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
1657 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
1658 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
1660 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
1663 return "Invalid (coordinate with minutes > 59) $field: "
1664 . $self->getfield($field);
1667 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
1669 if (defined($lower) and ($coord < $lower)) {
1670 return "Invalid (coordinate < $lower) $field: "
1671 . $self->getfield($field);;
1674 if (defined($upper) and ($coord > $upper)) {
1675 return "Invalid (coordinate > $upper) $field: "
1676 . $self->getfield($field);;
1679 $self->setfield($field, $coord);
1683 return "Invalid (coordinate) $field: " . $self->getfield($field);
1687 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
1689 Same as ut_coord, except optionally null.
1695 my ($self, $field) = (shift, shift);
1697 if ($self->getfield($field) =~ /^$/) {
1700 return $self->ut_coord($field, @_);
1706 =item ut_domain COLUMN
1708 Check/untaint host and domain names.
1713 my( $self, $field ) = @_;
1714 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1715 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1716 or return "Illegal (domain) $field: ". $self->getfield($field);
1717 $self->setfield($field,$1);
1721 =item ut_name COLUMN
1723 Check/untaint proper names; allows alphanumerics, spaces and the following
1724 punctuation: , . - '
1731 my( $self, $field ) = @_;
1732 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1733 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1734 $self->setfield($field,$1);
1740 Check/untaint zip codes.
1744 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1747 my( $self, $field, $country ) = @_;
1749 if ( $country eq 'US' ) {
1751 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1752 or return gettext('illegal_zip'). " $field for country $country: ".
1753 $self->getfield($field);
1754 $self->setfield($field, $1);
1756 } elsif ( $country eq 'CA' ) {
1758 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1759 or return gettext('illegal_zip'). " $field for country $country: ".
1760 $self->getfield($field);
1761 $self->setfield($field, "$1 $2");
1765 if ( $self->getfield($field) =~ /^\s*$/
1766 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1769 $self->setfield($field,'');
1771 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1772 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1773 $self->setfield($field,$1);
1781 =item ut_country COLUMN
1783 Check/untaint country codes. Country names are changed to codes, if possible -
1784 see L<Locale::Country>.
1789 my( $self, $field ) = @_;
1790 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1791 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1792 && country2code($1) ) {
1793 $self->setfield($field,uc(country2code($1)));
1796 $self->getfield($field) =~ /^(\w\w)$/
1797 or return "Illegal (country) $field: ". $self->getfield($field);
1798 $self->setfield($field,uc($1));
1802 =item ut_anything COLUMN
1804 Untaints arbitrary data. Be careful.
1809 my( $self, $field ) = @_;
1810 $self->getfield($field) =~ /^(.*)$/s
1811 or return "Illegal $field: ". $self->getfield($field);
1812 $self->setfield($field,$1);
1816 =item ut_enum COLUMN CHOICES_ARRAYREF
1818 Check/untaint a column, supplying all possible choices, like the "enum" type.
1823 my( $self, $field, $choices ) = @_;
1824 foreach my $choice ( @$choices ) {
1825 if ( $self->getfield($field) eq $choice ) {
1826 $self->setfield($field, $choice);
1830 return "Illegal (enum) field $field: ". $self->getfield($field);
1833 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1835 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1836 on the column first.
1840 sub ut_foreign_key {
1841 my( $self, $field, $table, $foreign ) = @_;
1842 qsearchs($table, { $foreign => $self->getfield($field) })
1843 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1844 " in $table.$foreign";
1848 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1850 Like ut_foreign_key, except the null value is also allowed.
1854 sub ut_foreign_keyn {
1855 my( $self, $field, $table, $foreign ) = @_;
1856 $self->getfield($field)
1857 ? $self->ut_foreign_key($field, $table, $foreign)
1861 =item ut_agentnum_acl
1863 Checks this column as an agentnum, taking into account the current users's
1868 sub ut_agentnum_acl {
1869 my( $self, $field, $null_acl ) = @_;
1871 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1872 return "Illegal agentnum: $error" if $error;
1874 my $curuser = $FS::CurrentUser::CurrentUser;
1876 if ( $self->$field() ) {
1878 return "Access deined"
1879 unless $curuser->agentnum($self->$field());
1883 return "Access denied"
1884 unless $curuser->access_right($null_acl);
1892 =item virtual_fields [ TABLE ]
1894 Returns a list of virtual fields defined for the table. This should not
1895 be exported, and should only be called as an instance or class method.
1899 sub virtual_fields {
1902 $table = $self->table or confess "virtual_fields called on non-table";
1904 confess "Unknown table $table" unless dbdef->table($table);
1906 return () unless dbdef->table('part_virtual_field');
1908 unless ( $virtual_fields_cache{$table} ) {
1909 my $query = 'SELECT name from part_virtual_field ' .
1910 "WHERE dbtable = '$table'";
1912 my $result = $dbh->selectcol_arrayref($query);
1913 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1915 $virtual_fields_cache{$table} = $result;
1918 @{$virtual_fields_cache{$table}};
1923 =item fields [ TABLE ]
1925 This is a wrapper for real_fields and virtual_fields. Code that called
1926 fields before should probably continue to call fields.
1931 my $something = shift;
1933 if($something->isa('FS::Record')) {
1934 $table = $something->table;
1936 $table = $something;
1937 $something = "FS::$table";
1939 return (real_fields($table), $something->virtual_fields());
1942 =item pvf FIELD_NAME
1944 Returns the FS::part_virtual_field object corresponding to a field in the
1945 record (specified by FIELD_NAME).
1950 my ($self, $name) = (shift, shift);
1952 if(grep /^$name$/, $self->virtual_fields) {
1953 return qsearchs('part_virtual_field', { dbtable => $self->table,
1959 =item vfieldpart_hashref TABLE
1961 Returns a hashref of virtual field names and vfieldparts applicable to the given
1966 sub vfieldpart_hashref {
1968 my $table = $self->table;
1970 return {} unless dbdef->table('part_virtual_field');
1973 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1974 "dbtable = '$table'";
1975 my $sth = $dbh->prepare($statement);
1976 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1977 return { map { $_->{name}, $_->{vfieldpart} }
1978 @{$sth->fetchall_arrayref({})} };
1982 =item encrypt($value)
1984 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
1986 Returns the encrypted string.
1988 You should generally not have to worry about calling this, as the system handles this for you.
1993 my ($self, $value) = @_;
1996 my $conf = new FS::Conf;
1997 if ($conf->exists('encryption')) {
1998 if ($self->is_encrypted($value)) {
1999 # Return the original value if it isn't plaintext.
2000 $encrypted = $value;
2003 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2004 # RSA doesn't like the empty string so let's pack it up
2005 # The database doesn't like the RSA data so uuencode it
2006 my $length = length($value)+1;
2007 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2009 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2016 =item is_encrypted($value)
2018 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2024 my ($self, $value) = @_;
2025 # Possible Bug - Some work may be required here....
2027 if ($value =~ /^M/ && length($value) > 80) {
2034 =item decrypt($value)
2036 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2038 You should generally not have to worry about calling this, as the system handles this for you.
2043 my ($self,$value) = @_;
2044 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2045 my $conf = new FS::Conf;
2046 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2048 if (ref($rsa_decrypt) =~ /::RSA/) {
2049 my $encrypted = unpack ("u*", $value);
2050 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2051 if ($@) {warn "Decryption Failed"};
2059 #Initialize the Module
2060 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2062 my $conf = new FS::Conf;
2063 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2064 $rsa_module = $conf->config('encryptionmodule');
2068 eval ("require $rsa_module"); # No need to import the namespace
2071 # Initialize Encryption
2072 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2073 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2074 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2077 # Intitalize Decryption
2078 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2079 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2080 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2084 =item h_search ACTION
2086 Given an ACTION, either "insert", or "delete", returns the appropriate history
2087 record corresponding to this record, if any.
2092 my( $self, $action ) = @_;
2094 my $table = $self->table;
2097 my $primary_key = dbdef->table($table)->primary_key;
2100 'table' => "h_$table",
2101 'hashref' => { $primary_key => $self->$primary_key(),
2102 'history_action' => $action,
2110 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2111 appropriate history record corresponding to this record, if any.
2116 my($self, $action) = @_;
2117 my $h = $self->h_search($action);
2118 $h ? $h->history_date : '';
2127 =item real_fields [ TABLE ]
2129 Returns a list of the real columns in the specified table. Called only by
2130 fields() and other subroutines elsewhere in FS::Record.
2137 my($table_obj) = dbdef->table($table);
2138 confess "Unknown table $table" unless $table_obj;
2139 $table_obj->columns;
2142 =item _quote VALUE, TABLE, COLUMN
2144 This is an internal function used to construct SQL statements. It returns
2145 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2146 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2151 my($value, $table, $column) = @_;
2152 my $column_obj = dbdef->table($table)->column($column);
2153 my $column_type = $column_obj->type;
2154 my $nullable = $column_obj->null;
2156 warn " $table.$column: $value ($column_type".
2157 ( $nullable ? ' NULL' : ' NOT NULL' ).
2158 ")\n" if $DEBUG > 2;
2160 if ( $value eq '' && $nullable ) {
2162 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2163 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2166 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2167 ! $column_type =~ /(char|binary|text)$/i ) {
2176 This is deprecated. Don't use it.
2178 It returns a hash-type list with the fields of this record's table set true.
2183 carp "warning: hfields is deprecated";
2186 foreach (fields($table)) {
2195 "$_: ". $self->getfield($_). "|"
2196 } (fields($self->table)) );
2199 sub DESTROY { return; }
2203 # #use Carp qw(cluck);
2204 # #cluck "DESTROYING $self";
2205 # warn "DESTROYING $self";
2209 # return ! eval { join('',@_), kill 0; 1; };
2212 =item str2time_sql [ DRIVER_NAME ]
2214 Returns a function to convert to unix time based on database type, such as
2215 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2216 the str2time_sql_closing method to return a closing string rather than just
2217 using a closing parenthesis as previously suggested.
2219 You can pass an optional driver name such as "Pg", "mysql" or
2220 $dbh->{Driver}->{Name} to return a function for that database instead of
2221 the current database.
2226 my $driver = shift || driver_name;
2228 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2229 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2231 warn "warning: unknown database type $driver; guessing how to convert ".
2232 "dates to UNIX timestamps";
2233 return 'EXTRACT(EPOCH FROM ';
2237 =item str2time_sql_closing [ DRIVER_NAME ]
2239 Returns the closing suffix of a function to convert to unix time based on
2240 database type, such as ")::integer" for Pg or ")" for mysql.
2242 You can pass an optional driver name such as "Pg", "mysql" or
2243 $dbh->{Driver}->{Name} to return a function for that database instead of
2244 the current database.
2248 sub str2time_sql_closing {
2249 my $driver = shift || driver_name;
2251 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2259 This module should probably be renamed, since much of the functionality is
2260 of general use. It is not completely unlike Adapter::DBI (see below).
2262 Exported qsearch and qsearchs should be deprecated in favor of method calls
2263 (against an FS::Record object like the old search and searchs that qsearch
2264 and qsearchs were on top of.)
2266 The whole fields / hfields mess should be removed.
2268 The various WHERE clauses should be subroutined.
2270 table string should be deprecated in favor of DBIx::DBSchema::Table.
2272 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2273 true maps to the database (and WHERE clauses) would also help.
2275 The ut_ methods should ask the dbdef for a default length.
2277 ut_sqltype (like ut_varchar) should all be defined
2279 A fallback check method should be provided which uses the dbdef.
2281 The ut_money method assumes money has two decimal digits.
2283 The Pg money kludge in the new method only strips `$'.
2285 The ut_phonen method only checks US-style phone numbers.
2287 The _quote function should probably use ut_float instead of a regex.
2289 All the subroutines probably should be methods, here or elsewhere.
2291 Probably should borrow/use some dbdef methods where appropriate (like sub
2294 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2295 or allow it to be set. Working around it is ugly any way around - DBI should
2296 be fixed. (only affects RDBMS which return uppercase column names)
2298 ut_zip should take an optional country like ut_phone.
2302 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2304 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.