4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 %virtual_fields_cache $nowarn_identical );
8 use Carp qw(carp cluck croak confess);
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.25;
13 use FS::UID qw(dbh getotaker datasrc driver_name);
15 use FS::Schema qw(dbdef);
17 use FS::Msgcat qw(gettext);
20 use FS::part_virtual_field;
26 #export dbdef for now... everything else expects to find it here
27 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
32 $nowarn_identical = 0;
39 FS::UID->install_callback( sub {
41 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
47 FS::Record - Database record objects
52 use FS::Record qw(dbh fields qsearch qsearchs);
54 $record = new FS::Record 'table', \%hash;
55 $record = new FS::Record 'table', { 'column' => 'value', ... };
57 $record = qsearchs FS::Record 'table', \%hash;
58 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
59 @records = qsearch FS::Record 'table', \%hash;
60 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
62 $table = $record->table;
63 $dbdef_table = $record->dbdef_table;
65 $value = $record->get('column');
66 $value = $record->getfield('column');
67 $value = $record->column;
69 $record->set( 'column' => 'value' );
70 $record->setfield( 'column' => 'value' );
71 $record->column('value');
73 %hash = $record->hash;
75 $hashref = $record->hashref;
77 $error = $record->insert;
79 $error = $record->delete;
81 $error = $new_record->replace($old_record);
83 # external use deprecated - handled by the database (at least for Pg, mysql)
84 $value = $record->unique('column');
86 $error = $record->ut_float('column');
87 $error = $record->ut_floatn('column');
88 $error = $record->ut_number('column');
89 $error = $record->ut_numbern('column');
90 $error = $record->ut_snumber('column');
91 $error = $record->ut_snumbern('column');
92 $error = $record->ut_money('column');
93 $error = $record->ut_text('column');
94 $error = $record->ut_textn('column');
95 $error = $record->ut_alpha('column');
96 $error = $record->ut_alphan('column');
97 $error = $record->ut_phonen('column');
98 $error = $record->ut_anything('column');
99 $error = $record->ut_name('column');
101 $quoted_value = _quote($value,'table','field');
104 $fields = hfields('table');
105 if ( $fields->{Field} ) { # etc.
107 @fields = fields 'table'; #as a subroutine
108 @fields = $record->fields; #as a method call
113 (Mostly) object-oriented interface to database records. Records are currently
114 implemented on top of DBI. FS::Record is intended as a base class for
115 table-specific classes to inherit from, i.e. FS::cust_main.
121 =item new [ TABLE, ] HASHREF
123 Creates a new record. It doesn't store it in the database, though. See
124 L<"insert"> for that.
126 Note that the object stores this hash reference, not a distinct copy of the
127 hash it points to. You can ask the object for a copy with the I<hash>
130 TABLE can only be omitted when a dervived class overrides the table method.
136 my $class = ref($proto) || $proto;
138 bless ($self, $class);
140 unless ( defined ( $self->table ) ) {
141 $self->{'Table'} = shift;
142 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
145 $self->{'Hash'} = shift;
147 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
148 $self->{'Hash'}{$field}='';
151 $self->_rebless if $self->can('_rebless');
153 $self->{'modified'} = 0;
155 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
162 my $class = ref($proto) || $proto;
164 bless ($self, $class);
166 $self->{'Table'} = shift unless defined ( $self->table );
168 my $hashref = $self->{'Hash'} = shift;
170 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
171 my $obj = $cache->cache->{$hashref->{$cache->key}};
172 $obj->_cache($hashref, $cache) if $obj->can('_cache');
175 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
182 my $class = ref($proto) || $proto;
184 bless ($self, $class);
185 if ( defined $self->table ) {
186 cluck "create constructor is deprecated, use new!";
189 croak "FS::Record::create called (not from a subclass)!";
193 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
195 Searches the database for all records matching (at least) the key/value pairs
196 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
197 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
200 The preferred usage is to pass a hash reference of named parameters:
202 my @records = qsearch( {
203 'table' => 'table_name',
204 'hashref' => { 'field' => 'value'
205 'field' => { 'op' => '<',
210 #these are optional...
212 'extra_sql' => 'AND field ',
213 #'cache_obj' => '', #optional
214 'addl_from' => 'LEFT JOIN othtable USING ( field )',
218 Much code still uses old-style positional parameters, this is also probably
219 fine in the common case where there are only two parameters:
221 my @records = qsearch( 'table', { 'field' => 'value' } );
223 ###oops, argh, FS::Record::new only lets us create database fields.
224 #Normal behaviour if SELECT is not specified is `*', as in
225 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
226 #feature where you can specify SELECT - remember, the objects returned,
227 #although blessed into the appropriate `FS::TABLE' package, will only have the
228 #fields you specify. This might have unwanted results if you then go calling
229 #regular FS::TABLE methods
235 my($stable, $record, $select, $extra_sql, $cache, $addl_from );
236 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
238 $stable = $opt->{'table'} or die "table name is required";
239 $record = $opt->{'hashref'} || {};
240 $select = $opt->{'select'} || '*';
241 $extra_sql = $opt->{'extra_sql'} || '';
242 $cache = $opt->{'cache_obj'} || '';
243 $addl_from = $opt->{'addl_from'} || '';
245 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
249 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
251 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
255 my $table = $cache ? $cache->table : $stable;
256 my $dbdef_table = dbdef->table($table)
257 or die "No schema for table $table found - ".
258 "do you need to run freeside-upgrade?";
259 my $pkey = $dbdef_table->primary_key;
261 my @real_fields = grep exists($record->{$_}), real_fields($table);
263 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
264 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
266 cluck "warning: FS::$table not loaded; virtual fields not searchable";
267 @virtual_fields = ();
270 my $statement = "SELECT $select FROM $stable";
271 $statement .= " $addl_from" if $addl_from;
272 if ( @real_fields or @virtual_fields ) {
273 $statement .= ' WHERE '. join(' AND ',
278 if ( ref($record->{$_}) ) {
279 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
280 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
281 if ( uc($op) eq 'ILIKE' ) {
283 $record->{$_}{'value'} = lc($record->{$_}{'value'});
284 $column = "LOWER($_)";
286 $record->{$_} = $record->{$_}{'value'}
289 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
291 if ( driver_name eq 'Pg' ) {
292 my $type = dbdef->table($table)->column($column)->type;
293 if ( $type =~ /(int|(big)?serial)/i ) {
294 qq-( $column IS NULL )-;
296 qq-( $column IS NULL OR $column = '' )-;
299 qq-( $column IS NULL OR $column = "" )-;
301 } elsif ( $op eq '!=' ) {
302 if ( driver_name eq 'Pg' ) {
303 my $type = dbdef->table($table)->column($column)->type;
304 if ( $type =~ /(int|(big)?serial)/i ) {
305 qq-( $column IS NOT NULL )-;
307 qq-( $column IS NOT NULL AND $column != '' )-;
310 qq-( $column IS NOT NULL AND $column != "" )-;
313 if ( driver_name eq 'Pg' ) {
314 qq-( $column $op '' )-;
316 qq-( $column $op "" )-;
326 if ( ref($record->{$_}) ) {
327 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
328 if ( uc($op) eq 'ILIKE' ) {
330 $record->{$_}{'value'} = lc($record->{$_}{'value'});
331 $column = "LOWER($_)";
333 $record->{$_} = $record->{$_}{'value'};
336 # ... EXISTS ( SELECT name, value FROM part_virtual_field
338 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
339 # WHERE recnum = svc_acct.svcnum
340 # AND (name, value) = ('egad', 'brain') )
342 my $value = $record->{$_};
346 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
347 "( SELECT part_virtual_field.name, virtual_field.value ".
348 "FROM part_virtual_field JOIN virtual_field ".
349 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
350 "WHERE virtual_field.recnum = ${table}.${pkey} ".
351 "AND part_virtual_field.name = '${column}'".
353 " AND virtual_field.value ${op} '${value}'"
357 } @virtual_fields ) );
361 $statement .= " $extra_sql" if defined($extra_sql);
363 warn "[debug]$me $statement\n" if $DEBUG > 1;
364 my $sth = $dbh->prepare($statement)
365 or croak "$dbh->errstr doing $statement";
370 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
372 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
373 && dbdef->table($table)->column($field)->type =~ /(int|(big)?serial)/i
375 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
377 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
381 # $sth->execute( map $record->{$_},
382 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
383 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
385 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
387 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
388 @virtual_fields = "FS::$table"->virtual_fields;
390 cluck "warning: FS::$table not loaded; virtual fields not returned either";
391 @virtual_fields = ();
395 tie %result, "Tie::IxHash";
396 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
397 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
398 %result = map { $_->{$pkey}, $_ } @stuff;
400 @result{@stuff} = @stuff;
405 if ( keys(%result) and @virtual_fields ) {
407 "SELECT virtual_field.recnum, part_virtual_field.name, ".
408 "virtual_field.value ".
409 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
410 "WHERE part_virtual_field.dbtable = '$table' AND ".
411 "virtual_field.recnum IN (".
412 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
413 join(q!', '!, @virtual_fields) . "')";
414 warn "[debug]$me $statement\n" if $DEBUG > 1;
415 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
416 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
418 foreach (@{ $sth->fetchall_arrayref({}) }) {
419 my $recnum = $_->{recnum};
420 my $name = $_->{name};
421 my $value = $_->{value};
422 if (exists($result{$recnum})) {
423 $result{$recnum}->{$name} = $value;
428 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
429 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
430 #derivied class didn't override new method, so this optimization is safe
433 new_or_cached( "FS::$table", { %{$_} }, $cache )
437 new( "FS::$table", { %{$_} } )
441 #okay, its been tested
442 # warn "untested code (class FS::$table uses custom new method)";
444 eval 'FS::'. $table. '->new( { %{$_} } )';
448 # Check for encrypted fields and decrypt them.
449 ## only in the local copy, not the cached object
450 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
451 # the initial search for
453 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
454 foreach my $record (@return) {
455 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
456 # Set it directly... This may cause a problem in the future...
457 $record->setfield($field, $record->decrypt($record->getfield($field)));
462 cluck "warning: FS::$table not loaded; returning FS::Record objects";
464 FS::Record->new( $table, { %{$_} } );
470 =item by_key PRIMARY_KEY_VALUE
472 This is a class method that returns the record with the given primary key
473 value. This method is only useful in FS::Record subclasses. For example:
475 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
479 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
484 my ($class, $pkey_value) = @_;
486 my $table = $class->table
487 or croak "No table for $class found";
489 my $dbdef_table = dbdef->table($table)
490 or die "No schema for table $table found - ".
491 "do you need to create it or run dbdef-create?";
492 my $pkey = $dbdef_table->primary_key
493 or die "No primary key for table $table";
495 return qsearchs($table, { $pkey => $pkey_value });
498 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
500 Experimental JOINed search method. Using this method, you can execute a
501 single SELECT spanning multiple tables, and cache the results for subsequent
502 method calls. Interface will almost definately change in an incompatible
510 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
511 my $cache = FS::SearchCache->new( $ptable, $pkey );
514 grep { !$saw{$_->getfield($pkey)}++ }
515 qsearch($table, $record, $select, $extra_sql, $cache )
519 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
521 Same as qsearch, except that if more than one record matches, it B<carp>s but
522 returns the first. If this happens, you either made a logic error in asking
523 for a single item, or your data is corrupted.
527 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
529 my(@result) = qsearch(@_);
530 cluck "warning: Multiple records in scalar search ($table)"
531 if scalar(@result) > 1;
532 #should warn more vehemently if the search was on a primary key?
533 scalar(@result) ? ($result[0]) : ();
544 Returns the table name.
549 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
556 Returns the DBIx::DBSchema::Table object for the table.
562 my($table)=$self->table;
563 dbdef->table($table);
568 Returns the primary key for the table.
574 my $pkey = $self->dbdef_table->primary_key;
577 =item get, getfield COLUMN
579 Returns the value of the column/field/key COLUMN.
584 my($self,$field) = @_;
585 # to avoid "Use of unitialized value" errors
586 if ( defined ( $self->{Hash}->{$field} ) ) {
587 $self->{Hash}->{$field};
597 =item set, setfield COLUMN, VALUE
599 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
604 my($self,$field,$value) = @_;
605 $self->{'modified'} = 1;
606 $self->{'Hash'}->{$field} = $value;
613 =item AUTLOADED METHODS
615 $record->column is a synonym for $record->get('column');
617 $record->column('value') is a synonym for $record->set('column','value');
624 my($field)=$AUTOLOAD;
626 if ( defined($value) ) {
627 confess "errant AUTOLOAD $field for $self (arg $value)"
628 unless ref($self) && $self->can('setfield');
629 $self->setfield($field,$value);
631 confess "errant AUTOLOAD $field for $self (no args)"
632 unless ref($self) && $self->can('getfield');
633 $self->getfield($field);
639 # my $field = $AUTOLOAD;
641 # if ( defined($_[1]) ) {
642 # $_[0]->setfield($field, $_[1]);
644 # $_[0]->getfield($field);
650 Returns a list of the column/value pairs, usually for assigning to a new hash.
652 To make a distinct duplicate of an FS::Record object, you can do:
654 $new = new FS::Record ( $old->table, { $old->hash } );
660 confess $self. ' -> hash: Hash attribute is undefined'
661 unless defined($self->{'Hash'});
662 %{ $self->{'Hash'} };
667 Returns a reference to the column/value hash. This may be deprecated in the
668 future; if there's a reason you can't just use the autoloaded or get/set
680 Returns true if any of this object's values have been modified with set (or via
681 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
693 Inserts this record to the database. If there is an error, returns the error,
694 otherwise returns false.
702 warn "$self -> insert" if $DEBUG;
704 my $error = $self->check;
705 return $error if $error;
707 #single-field unique keys are given a value if false
708 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
709 foreach ( $self->dbdef_table->unique->singles ) {
710 $self->unique($_) unless $self->getfield($_);
713 #and also the primary key, if the database isn't going to
714 my $primary_key = $self->dbdef_table->primary_key;
716 if ( $primary_key ) {
717 my $col = $self->dbdef_table->column($primary_key);
720 uc($col->type) =~ /^(BIG)?SERIAL\d?/
721 || ( driver_name eq 'Pg'
722 && defined($col->default)
723 && $col->default =~ /^nextval\(/i
725 || ( driver_name eq 'mysql'
726 && defined($col->local)
727 && $col->local =~ /AUTO_INCREMENT/i
729 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
732 my $table = $self->table;
735 # Encrypt before the database
736 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
737 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
738 $self->{'saved'} = $self->getfield($field);
739 $self->setfield($field, $self->encrypt($self->getfield($field)));
744 #false laziness w/delete
746 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
749 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
752 my $statement = "INSERT INTO $table ";
753 if ( @real_fields ) {
756 join( ', ', @real_fields ).
758 join( ', ', @values ).
762 $statement .= 'DEFAULT VALUES';
764 warn "[debug]$me $statement\n" if $DEBUG > 1;
765 my $sth = dbh->prepare($statement) or return dbh->errstr;
767 local $SIG{HUP} = 'IGNORE';
768 local $SIG{INT} = 'IGNORE';
769 local $SIG{QUIT} = 'IGNORE';
770 local $SIG{TERM} = 'IGNORE';
771 local $SIG{TSTP} = 'IGNORE';
772 local $SIG{PIPE} = 'IGNORE';
774 $sth->execute or return $sth->errstr;
776 # get inserted id from the database, if applicable & needed
777 if ( $db_seq && ! $self->getfield($primary_key) ) {
778 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
782 if ( driver_name eq 'Pg' ) {
784 #my $oid = $sth->{'pg_oid_status'};
785 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
787 my $default = $self->dbdef_table->column($primary_key)->default;
788 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
789 dbh->rollback if $FS::UID::AutoCommit;
790 return "can't parse $table.$primary_key default value".
791 " for sequence name: $default";
795 my $i_sql = "SELECT currval('$sequence')";
796 my $i_sth = dbh->prepare($i_sql) or do {
797 dbh->rollback if $FS::UID::AutoCommit;
800 $i_sth->execute() or do { #$i_sth->execute($oid)
801 dbh->rollback if $FS::UID::AutoCommit;
802 return $i_sth->errstr;
804 $insertid = $i_sth->fetchrow_arrayref->[0];
806 } elsif ( driver_name eq 'mysql' ) {
808 $insertid = dbh->{'mysql_insertid'};
809 # work around mysql_insertid being null some of the time, ala RT :/
810 unless ( $insertid ) {
811 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
812 "using SELECT LAST_INSERT_ID();";
813 my $i_sql = "SELECT LAST_INSERT_ID()";
814 my $i_sth = dbh->prepare($i_sql) or do {
815 dbh->rollback if $FS::UID::AutoCommit;
818 $i_sth->execute or do {
819 dbh->rollback if $FS::UID::AutoCommit;
820 return $i_sth->errstr;
822 $insertid = $i_sth->fetchrow_arrayref->[0];
827 dbh->rollback if $FS::UID::AutoCommit;
828 return "don't know how to retreive inserted ids from ". driver_name.
829 ", try using counterfiles (maybe run dbdef-create?)";
833 $self->setfield($primary_key, $insertid);
838 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
839 $self->virtual_fields;
840 if (@virtual_fields) {
841 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
843 my $vfieldpart = $self->vfieldpart_hashref;
845 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
848 my $v_sth = dbh->prepare($v_statement) or do {
849 dbh->rollback if $FS::UID::AutoCommit;
853 foreach (keys(%v_values)) {
854 $v_sth->execute($self->getfield($primary_key),
858 dbh->rollback if $FS::UID::AutoCommit;
859 return $v_sth->errstr;
866 if ( defined dbdef->table('h_'. $table) ) {
867 my $h_statement = $self->_h_statement('insert');
868 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
869 $h_sth = dbh->prepare($h_statement) or do {
870 dbh->rollback if $FS::UID::AutoCommit;
876 $h_sth->execute or return $h_sth->errstr if $h_sth;
878 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
880 # Now that it has been saved, reset the encrypted fields so that $new
882 foreach my $field (keys %{$saved}) {
883 $self->setfield($field, $saved->{$field});
891 Depriciated (use insert instead).
896 cluck "warning: FS::Record::add deprecated!";
897 insert @_; #call method in this scope
902 Delete this record from the database. If there is an error, returns the error,
903 otherwise returns false.
910 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
912 $self->getfield($_) eq ''
913 #? "( $_ IS NULL OR $_ = \"\" )"
914 ? ( driver_name eq 'Pg'
916 : "( $_ IS NULL OR $_ = \"\" )"
918 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
919 } ( $self->dbdef_table->primary_key )
920 ? ( $self->dbdef_table->primary_key)
921 : real_fields($self->table)
923 warn "[debug]$me $statement\n" if $DEBUG > 1;
924 my $sth = dbh->prepare($statement) or return dbh->errstr;
927 if ( defined dbdef->table('h_'. $self->table) ) {
928 my $h_statement = $self->_h_statement('delete');
929 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
930 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
935 my $primary_key = $self->dbdef_table->primary_key;
938 my $vfp = $self->vfieldpart_hashref;
939 foreach($self->virtual_fields) {
940 next if $self->getfield($_) eq '';
941 unless(@del_vfields) {
942 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
943 $v_sth = dbh->prepare($st) or return dbh->errstr;
945 push @del_vfields, $_;
948 local $SIG{HUP} = 'IGNORE';
949 local $SIG{INT} = 'IGNORE';
950 local $SIG{QUIT} = 'IGNORE';
951 local $SIG{TERM} = 'IGNORE';
952 local $SIG{TSTP} = 'IGNORE';
953 local $SIG{PIPE} = 'IGNORE';
955 my $rc = $sth->execute or return $sth->errstr;
956 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
957 $h_sth->execute or return $h_sth->errstr if $h_sth;
958 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
959 or return $v_sth->errstr
960 foreach (@del_vfields);
962 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
964 #no need to needlessly destoy the data either (causes problems actually)
965 #undef $self; #no need to keep object!
972 Depriciated (use delete instead).
977 cluck "warning: FS::Record::del deprecated!";
978 &delete(@_); #call method in this scope
981 =item replace OLD_RECORD
983 Replace the OLD_RECORD with this one in the database. If there is an error,
984 returns the error, otherwise returns false.
989 my ($new, $old) = (shift, shift);
991 $old = $new->replace_old unless defined($old);
993 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
995 if ( $new->can('replace_check') ) {
996 my $error = $new->replace_check($old);
997 return $error if $error;
1000 return "Records not in same table!" unless $new->table eq $old->table;
1002 my $primary_key = $old->dbdef_table->primary_key;
1003 return "Can't change primary key $primary_key ".
1004 'from '. $old->getfield($primary_key).
1005 ' to ' . $new->getfield($primary_key)
1007 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1009 my $error = $new->check;
1010 return $error if $error;
1012 # Encrypt for replace
1013 my $conf = new FS::Conf;
1015 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1016 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1017 $saved->{$field} = $new->getfield($field);
1018 $new->setfield($field, $new->encrypt($new->getfield($field)));
1022 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1023 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1024 ? ($_, $new->getfield($_)) : () } $old->fields;
1026 unless ( keys(%diff) ) {
1027 carp "[warning]$me $new -> replace $old: records identical"
1028 unless $nowarn_identical;
1032 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1034 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1035 } real_fields($old->table)
1040 if ( $old->getfield($_) eq '' ) {
1042 #false laziness w/qsearch
1043 if ( driver_name eq 'Pg' ) {
1044 my $type = $old->dbdef_table->column($_)->type;
1045 if ( $type =~ /(int|(big)?serial)/i ) {
1048 qq-( $_ IS NULL OR $_ = '' )-;
1051 qq-( $_ IS NULL OR $_ = "" )-;
1055 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1058 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1061 warn "[debug]$me $statement\n" if $DEBUG > 1;
1062 my $sth = dbh->prepare($statement) or return dbh->errstr;
1065 if ( defined dbdef->table('h_'. $old->table) ) {
1066 my $h_old_statement = $old->_h_statement('replace_old');
1067 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1068 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1074 if ( defined dbdef->table('h_'. $new->table) ) {
1075 my $h_new_statement = $new->_h_statement('replace_new');
1076 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1077 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1082 # For virtual fields we have three cases with different SQL
1083 # statements: add, replace, delete
1087 my (@add_vfields, @rep_vfields, @del_vfields);
1088 my $vfp = $old->vfieldpart_hashref;
1089 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1090 if($diff{$_} eq '') {
1092 unless(@del_vfields) {
1093 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1094 "AND vfieldpart = ?";
1095 warn "[debug]$me $st\n" if $DEBUG > 2;
1096 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1098 push @del_vfields, $_;
1099 } elsif($old->getfield($_) eq '') {
1101 unless(@add_vfields) {
1102 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1104 warn "[debug]$me $st\n" if $DEBUG > 2;
1105 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1107 push @add_vfields, $_;
1110 unless(@rep_vfields) {
1111 my $st = "UPDATE virtual_field SET value = ? ".
1112 "WHERE recnum = ? AND vfieldpart = ?";
1113 warn "[debug]$me $st\n" if $DEBUG > 2;
1114 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1116 push @rep_vfields, $_;
1120 local $SIG{HUP} = 'IGNORE';
1121 local $SIG{INT} = 'IGNORE';
1122 local $SIG{QUIT} = 'IGNORE';
1123 local $SIG{TERM} = 'IGNORE';
1124 local $SIG{TSTP} = 'IGNORE';
1125 local $SIG{PIPE} = 'IGNORE';
1127 my $rc = $sth->execute or return $sth->errstr;
1128 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1129 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1130 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1132 $v_del_sth->execute($old->getfield($primary_key),
1134 or return $v_del_sth->errstr
1135 foreach(@del_vfields);
1137 $v_add_sth->execute($new->getfield($_),
1138 $old->getfield($primary_key),
1140 or return $v_add_sth->errstr
1141 foreach(@add_vfields);
1143 $v_rep_sth->execute($new->getfield($_),
1144 $old->getfield($primary_key),
1146 or return $v_rep_sth->errstr
1147 foreach(@rep_vfields);
1149 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1151 # Now that it has been saved, reset the encrypted fields so that $new
1152 # can still be used.
1153 foreach my $field (keys %{$saved}) {
1154 $new->setfield($field, $saved->{$field});
1162 my( $self ) = shift;
1163 warn "[$me] replace called with no arguments; autoloading old record\n"
1166 my $primary_key = $self->dbdef_table->primary_key;
1167 if ( $primary_key ) {
1168 $self->by_key( $self->$primary_key() ) #this is what's returned
1169 or croak "can't find ". $self->table. ".$primary_key ".
1170 $self->$primary_key();
1172 croak $self->table. " has no primary key; pass old record as argument";
1179 Depriciated (use replace instead).
1184 cluck "warning: FS::Record::rep deprecated!";
1185 replace @_; #call method in this scope
1190 Checks virtual fields (using check_blocks). Subclasses should still provide
1191 a check method to validate real fields, foreign keys, etc., and call this
1192 method via $self->SUPER::check.
1194 (FIXME: Should this method try to make sure that it I<is> being called from
1195 a subclass's check method, to keep the current semantics as far as possible?)
1200 #confess "FS::Record::check not implemented; supply one in subclass!";
1203 foreach my $field ($self->virtual_fields) {
1204 for ($self->getfield($field)) {
1205 # See notes on check_block in FS::part_virtual_field.
1206 eval $self->pvf($field)->check_block;
1208 #this is bad, probably want to follow the stack backtrace up and see
1210 my $err = "Fatal error checking $field for $self";
1212 return "$err (see log for backtrace): $@";
1215 $self->setfield($field, $_);
1222 my( $self, $action, $time ) = @_;
1227 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1228 real_fields($self->table);
1231 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1232 # You can see if it changed by the paymask...
1233 if ($conf->exists('encryption') ) {
1234 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1236 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1238 "INSERT INTO h_". $self->table. " ( ".
1239 join(', ', qw(history_date history_user history_action), @fields ).
1241 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1248 B<Warning>: External use is B<deprecated>.
1250 Replaces COLUMN in record with a unique number, using counters in the
1251 filesystem. Used by the B<insert> method on single-field unique columns
1252 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1253 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1255 Returns the new value.
1260 my($self,$field) = @_;
1261 my($table)=$self->table;
1263 croak "Unique called on field $field, but it is ",
1264 $self->getfield($field),
1266 if $self->getfield($field);
1268 #warn "table $table is tainted" if is_tainted($table);
1269 #warn "field $field is tainted" if is_tainted($field);
1271 my($counter) = new File::CounterFile "$table.$field",0;
1273 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1275 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1278 my $index = $counter->inc;
1279 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1281 $index =~ /^(\d*)$/;
1284 $self->setfield($field,$index);
1288 =item ut_float COLUMN
1290 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1291 null. If there is an error, returns the error, otherwise returns false.
1296 my($self,$field)=@_ ;
1297 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1298 $self->getfield($field) =~ /^(\d+)$/ ||
1299 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1300 $self->getfield($field) =~ /^(\d+e\d+)$/)
1301 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1302 $self->setfield($field,$1);
1305 =item ut_floatn COLUMN
1307 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1308 null. If there is an error, returns the error, otherwise returns false.
1312 #false laziness w/ut_ipn
1314 my( $self, $field ) = @_;
1315 if ( $self->getfield($field) =~ /^()$/ ) {
1316 $self->setfield($field,'');
1319 $self->ut_float($field);
1323 =item ut_snumber COLUMN
1325 Check/untaint signed numeric data (whole numbers). If there is an error,
1326 returns the error, otherwise returns false.
1331 my($self, $field) = @_;
1332 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1333 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1334 $self->setfield($field, "$1$2");
1338 =item ut_snumbern COLUMN
1340 Check/untaint signed numeric data (whole numbers). If there is an error,
1341 returns the error, otherwise returns false.
1346 my($self, $field) = @_;
1347 $self->getfield($field) =~ /^(-?)\s*(\d*)$/
1348 or return "Illegal (numeric) $field: ". $self->getfield($field);
1350 return "Illegal (numeric) $field: ". $self->getfield($field)
1353 $self->setfield($field, "$1$2");
1357 =item ut_number COLUMN
1359 Check/untaint simple numeric data (whole numbers). May not be null. If there
1360 is an error, returns the error, otherwise returns false.
1365 my($self,$field)=@_;
1366 $self->getfield($field) =~ /^(\d+)$/
1367 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1368 $self->setfield($field,$1);
1372 =item ut_numbern COLUMN
1374 Check/untaint simple numeric data (whole numbers). May be null. If there is
1375 an error, returns the error, otherwise returns false.
1380 my($self,$field)=@_;
1381 $self->getfield($field) =~ /^(\d*)$/
1382 or return "Illegal (numeric) $field: ". $self->getfield($field);
1383 $self->setfield($field,$1);
1387 =item ut_money COLUMN
1389 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1390 is an error, returns the error, otherwise returns false.
1395 my($self,$field)=@_;
1396 $self->setfield($field, 0) if $self->getfield($field) eq '';
1397 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1398 or return "Illegal (money) $field: ". $self->getfield($field);
1399 #$self->setfield($field, "$1$2$3" || 0);
1400 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1404 =item ut_text COLUMN
1406 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1407 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1408 May not be null. If there is an error, returns the error, otherwise returns
1414 my($self,$field)=@_;
1415 #warn "msgcat ". \&msgcat. "\n";
1416 #warn "notexist ". \¬exist. "\n";
1417 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1418 $self->getfield($field)
1419 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1420 or return gettext('illegal_or_empty_text'). " $field: ".
1421 $self->getfield($field);
1422 $self->setfield($field,$1);
1426 =item ut_textn COLUMN
1428 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1429 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1430 May be null. If there is an error, returns the error, otherwise returns false.
1435 my($self,$field)=@_;
1436 $self->getfield($field)
1437 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1438 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1439 $self->setfield($field,$1);
1443 =item ut_alpha COLUMN
1445 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1446 an error, returns the error, otherwise returns false.
1451 my($self,$field)=@_;
1452 $self->getfield($field) =~ /^(\w+)$/
1453 or return "Illegal or empty (alphanumeric) $field: ".
1454 $self->getfield($field);
1455 $self->setfield($field,$1);
1459 =item ut_alpha COLUMN
1461 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1462 error, returns the error, otherwise returns false.
1467 my($self,$field)=@_;
1468 $self->getfield($field) =~ /^(\w*)$/
1469 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1470 $self->setfield($field,$1);
1474 =item ut_phonen COLUMN [ COUNTRY ]
1476 Check/untaint phone numbers. May be null. If there is an error, returns
1477 the error, otherwise returns false.
1479 Takes an optional two-letter ISO country code; without it or with unsupported
1480 countries, ut_phonen simply calls ut_alphan.
1485 my( $self, $field, $country ) = @_;
1486 return $self->ut_alphan($field) unless defined $country;
1487 my $phonen = $self->getfield($field);
1488 if ( $phonen eq '' ) {
1489 $self->setfield($field,'');
1490 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1492 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1493 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1494 $phonen = "$1-$2-$3";
1495 $phonen .= " x$4" if $4;
1496 $self->setfield($field,$phonen);
1498 warn "warning: don't know how to check phone numbers for country $country";
1499 return $self->ut_textn($field);
1506 Check/untaint hexadecimal values.
1511 my($self, $field) = @_;
1512 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1513 or return "Illegal (hex) $field: ". $self->getfield($field);
1514 $self->setfield($field, uc($1));
1518 =item ut_hexn COLUMN
1520 Check/untaint hexadecimal values. May be null.
1525 my($self, $field) = @_;
1526 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1527 or return "Illegal (hex) $field: ". $self->getfield($field);
1528 $self->setfield($field, uc($1));
1533 Check/untaint ip addresses. IPv4 only for now.
1538 my( $self, $field ) = @_;
1539 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1540 or return "Illegal (IP address) $field: ". $self->getfield($field);
1541 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1542 $self->setfield($field, "$1.$2.$3.$4");
1548 Check/untaint ip addresses. IPv4 only for now. May be null.
1553 my( $self, $field ) = @_;
1554 if ( $self->getfield($field) =~ /^()$/ ) {
1555 $self->setfield($field,'');
1558 $self->ut_ip($field);
1562 =item ut_domain COLUMN
1564 Check/untaint host and domain names.
1569 my( $self, $field ) = @_;
1570 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1571 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1572 or return "Illegal (domain) $field: ". $self->getfield($field);
1573 $self->setfield($field,$1);
1577 =item ut_name COLUMN
1579 Check/untaint proper names; allows alphanumerics, spaces and the following
1580 punctuation: , . - '
1587 my( $self, $field ) = @_;
1588 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1589 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1590 $self->setfield($field,$1);
1596 Check/untaint zip codes.
1600 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1603 my( $self, $field, $country ) = @_;
1605 if ( $country eq 'US' ) {
1607 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1608 or return gettext('illegal_zip'). " $field for country $country: ".
1609 $self->getfield($field);
1610 $self->setfield($field, $1);
1612 } elsif ( $country eq 'CA' ) {
1614 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1615 or return gettext('illegal_zip'). " $field for country $country: ".
1616 $self->getfield($field);
1617 $self->setfield($field, "$1 $2");
1621 if ( $self->getfield($field) =~ /^\s*$/
1622 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1625 $self->setfield($field,'');
1627 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1628 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1629 $self->setfield($field,$1);
1637 =item ut_country COLUMN
1639 Check/untaint country codes. Country names are changed to codes, if possible -
1640 see L<Locale::Country>.
1645 my( $self, $field ) = @_;
1646 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1647 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1648 && country2code($1) ) {
1649 $self->setfield($field,uc(country2code($1)));
1652 $self->getfield($field) =~ /^(\w\w)$/
1653 or return "Illegal (country) $field: ". $self->getfield($field);
1654 $self->setfield($field,uc($1));
1658 =item ut_anything COLUMN
1660 Untaints arbitrary data. Be careful.
1665 my( $self, $field ) = @_;
1666 $self->getfield($field) =~ /^(.*)$/s
1667 or return "Illegal $field: ". $self->getfield($field);
1668 $self->setfield($field,$1);
1672 =item ut_enum COLUMN CHOICES_ARRAYREF
1674 Check/untaint a column, supplying all possible choices, like the "enum" type.
1679 my( $self, $field, $choices ) = @_;
1680 foreach my $choice ( @$choices ) {
1681 if ( $self->getfield($field) eq $choice ) {
1682 $self->setfield($choice);
1686 return "Illegal (enum) field $field: ". $self->getfield($field);
1689 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1691 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1692 on the column first.
1696 sub ut_foreign_key {
1697 my( $self, $field, $table, $foreign ) = @_;
1698 qsearchs($table, { $foreign => $self->getfield($field) })
1699 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1700 " in $table.$foreign";
1704 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1706 Like ut_foreign_key, except the null value is also allowed.
1710 sub ut_foreign_keyn {
1711 my( $self, $field, $table, $foreign ) = @_;
1712 $self->getfield($field)
1713 ? $self->ut_foreign_key($field, $table, $foreign)
1717 =item ut_agentnum_acl
1719 Checks this column as an agentnum, taking into account the current users's
1724 sub ut_agentnum_acl {
1725 my( $self, $field, $null_acl ) = @_;
1727 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1728 return "Illegal agentnum: $error" if $error;
1730 my $curuser = $FS::CurrentUser::CurrentUser;
1732 if ( $self->$field() ) {
1734 return "Access deined"
1735 unless $curuser->agentnum($self->$field());
1739 return "Access denied"
1740 unless $curuser->access_right($null_acl);
1748 =item virtual_fields [ TABLE ]
1750 Returns a list of virtual fields defined for the table. This should not
1751 be exported, and should only be called as an instance or class method.
1755 sub virtual_fields {
1758 $table = $self->table or confess "virtual_fields called on non-table";
1760 confess "Unknown table $table" unless dbdef->table($table);
1762 return () unless dbdef->table('part_virtual_field');
1764 unless ( $virtual_fields_cache{$table} ) {
1765 my $query = 'SELECT name from part_virtual_field ' .
1766 "WHERE dbtable = '$table'";
1768 my $result = $dbh->selectcol_arrayref($query);
1769 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1771 $virtual_fields_cache{$table} = $result;
1774 @{$virtual_fields_cache{$table}};
1779 =item fields [ TABLE ]
1781 This is a wrapper for real_fields and virtual_fields. Code that called
1782 fields before should probably continue to call fields.
1787 my $something = shift;
1789 if($something->isa('FS::Record')) {
1790 $table = $something->table;
1792 $table = $something;
1793 $something = "FS::$table";
1795 return (real_fields($table), $something->virtual_fields());
1800 =item pvf FIELD_NAME
1802 Returns the FS::part_virtual_field object corresponding to a field in the
1803 record (specified by FIELD_NAME).
1808 my ($self, $name) = (shift, shift);
1810 if(grep /^$name$/, $self->virtual_fields) {
1811 return qsearchs('part_virtual_field', { dbtable => $self->table,
1821 =item real_fields [ TABLE ]
1823 Returns a list of the real columns in the specified table. Called only by
1824 fields() and other subroutines elsewhere in FS::Record.
1831 my($table_obj) = dbdef->table($table);
1832 confess "Unknown table $table" unless $table_obj;
1833 $table_obj->columns;
1836 =item _quote VALUE, TABLE, COLUMN
1838 This is an internal function used to construct SQL statements. It returns
1839 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1840 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1845 my($value, $table, $column) = @_;
1846 my $column_obj = dbdef->table($table)->column($column);
1847 my $column_type = $column_obj->type;
1848 my $nullable = $column_obj->null;
1850 warn " $table.$column: $value ($column_type".
1851 ( $nullable ? ' NULL' : ' NOT NULL' ).
1852 ")\n" if $DEBUG > 2;
1854 if ( $value eq '' && $nullable ) {
1856 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
1857 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1860 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1861 ! $column_type =~ /(char|binary|text)$/i ) {
1868 =item vfieldpart_hashref TABLE
1870 Returns a hashref of virtual field names and vfieldparts applicable to the given
1875 sub vfieldpart_hashref {
1877 my $table = $self->table;
1879 return {} unless dbdef->table('part_virtual_field');
1882 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1883 "dbtable = '$table'";
1884 my $sth = $dbh->prepare($statement);
1885 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1886 return { map { $_->{name}, $_->{vfieldpart} }
1887 @{$sth->fetchall_arrayref({})} };
1894 This is deprecated. Don't use it.
1896 It returns a hash-type list with the fields of this record's table set true.
1901 carp "warning: hfields is deprecated";
1904 foreach (fields($table)) {
1913 "$_: ". $self->getfield($_). "|"
1914 } (fields($self->table)) );
1917 =item encrypt($value)
1919 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
1921 Returns the encrypted string.
1923 You should generally not have to worry about calling this, as the system handles this for you.
1929 my ($self, $value) = @_;
1932 my $conf = new FS::Conf;
1933 if ($conf->exists('encryption')) {
1934 if ($self->is_encrypted($value)) {
1935 # Return the original value if it isn't plaintext.
1936 $encrypted = $value;
1939 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1940 # RSA doesn't like the empty string so let's pack it up
1941 # The database doesn't like the RSA data so uuencode it
1942 my $length = length($value)+1;
1943 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1945 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1952 =item is_encrypted($value)
1954 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
1960 my ($self, $value) = @_;
1961 # Possible Bug - Some work may be required here....
1963 if ($value =~ /^M/ && length($value) > 80) {
1970 =item decrypt($value)
1972 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
1974 You should generally not have to worry about calling this, as the system handles this for you.
1979 my ($self,$value) = @_;
1980 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1981 my $conf = new FS::Conf;
1982 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1984 if (ref($rsa_decrypt) =~ /::RSA/) {
1985 my $encrypted = unpack ("u*", $value);
1986 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
1987 if ($@) {warn "Decryption Failed"};
1995 #Initialize the Module
1996 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1998 my $conf = new FS::Conf;
1999 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2000 $rsa_module = $conf->config('encryptionmodule');
2004 eval ("require $rsa_module"); # No need to import the namespace
2007 # Initialize Encryption
2008 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2009 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2010 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2013 # Intitalize Decryption
2014 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2015 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2016 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2020 sub DESTROY { return; }
2024 # #use Carp qw(cluck);
2025 # #cluck "DESTROYING $self";
2026 # warn "DESTROYING $self";
2030 # return ! eval { join('',@_), kill 0; 1; };
2037 This module should probably be renamed, since much of the functionality is
2038 of general use. It is not completely unlike Adapter::DBI (see below).
2040 Exported qsearch and qsearchs should be deprecated in favor of method calls
2041 (against an FS::Record object like the old search and searchs that qsearch
2042 and qsearchs were on top of.)
2044 The whole fields / hfields mess should be removed.
2046 The various WHERE clauses should be subroutined.
2048 table string should be deprecated in favor of DBIx::DBSchema::Table.
2050 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2051 true maps to the database (and WHERE clauses) would also help.
2053 The ut_ methods should ask the dbdef for a default length.
2055 ut_sqltype (like ut_varchar) should all be defined
2057 A fallback check method should be provided which uses the dbdef.
2059 The ut_money method assumes money has two decimal digits.
2061 The Pg money kludge in the new method only strips `$'.
2063 The ut_phonen method only checks US-style phone numbers.
2065 The _quote function should probably use ut_float instead of a regex.
2067 All the subroutines probably should be methods, here or elsewhere.
2069 Probably should borrow/use some dbdef methods where appropriate (like sub
2072 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2073 or allow it to be set. Working around it is ugly any way around - DBI should
2074 be fixed. (only affects RDBMS which return uppercase column names)
2076 ut_zip should take an optional country like ut_phone.
2080 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2082 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.