4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $me %virtual_fields_cache $nowarn_identical );
7 use Carp qw(carp cluck croak confess);
10 use DBI qw(:sql_types);
11 use DBIx::DBSchema 0.25;
12 use FS::UID qw(dbh getotaker datasrc driver_name);
14 use FS::Schema qw(dbdef);
16 use FS::Msgcat qw(gettext);
19 use FS::part_virtual_field;
25 #export dbdef for now... everything else expects to find it here
26 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
31 $nowarn_identical = 0;
38 FS::UID->install_callback( sub {
39 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
44 FS::Record - Database record objects
49 use FS::Record qw(dbh fields qsearch qsearchs);
51 $record = new FS::Record 'table', \%hash;
52 $record = new FS::Record 'table', { 'column' => 'value', ... };
54 $record = qsearchs FS::Record 'table', \%hash;
55 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
56 @records = qsearch FS::Record 'table', \%hash;
57 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
59 $table = $record->table;
60 $dbdef_table = $record->dbdef_table;
62 $value = $record->get('column');
63 $value = $record->getfield('column');
64 $value = $record->column;
66 $record->set( 'column' => 'value' );
67 $record->setfield( 'column' => 'value' );
68 $record->column('value');
70 %hash = $record->hash;
72 $hashref = $record->hashref;
74 $error = $record->insert;
76 $error = $record->delete;
78 $error = $new_record->replace($old_record);
80 # external use deprecated - handled by the database (at least for Pg, mysql)
81 $value = $record->unique('column');
83 $error = $record->ut_float('column');
84 $error = $record->ut_number('column');
85 $error = $record->ut_numbern('column');
86 $error = $record->ut_money('column');
87 $error = $record->ut_text('column');
88 $error = $record->ut_textn('column');
89 $error = $record->ut_alpha('column');
90 $error = $record->ut_alphan('column');
91 $error = $record->ut_phonen('column');
92 $error = $record->ut_anything('column');
93 $error = $record->ut_name('column');
95 $quoted_value = _quote($value,'table','field');
98 $fields = hfields('table');
99 if ( $fields->{Field} ) { # etc.
101 @fields = fields 'table'; #as a subroutine
102 @fields = $record->fields; #as a method call
107 (Mostly) object-oriented interface to database records. Records are currently
108 implemented on top of DBI. FS::Record is intended as a base class for
109 table-specific classes to inherit from, i.e. FS::cust_main.
115 =item new [ TABLE, ] HASHREF
117 Creates a new record. It doesn't store it in the database, though. See
118 L<"insert"> for that.
120 Note that the object stores this hash reference, not a distinct copy of the
121 hash it points to. You can ask the object for a copy with the I<hash>
124 TABLE can only be omitted when a dervived class overrides the table method.
130 my $class = ref($proto) || $proto;
132 bless ($self, $class);
134 unless ( defined ( $self->table ) ) {
135 $self->{'Table'} = shift;
136 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
139 $self->{'Hash'} = shift;
141 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
142 $self->{'Hash'}{$field}='';
145 $self->_rebless if $self->can('_rebless');
147 $self->{'modified'} = 0;
149 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
156 my $class = ref($proto) || $proto;
158 bless ($self, $class);
160 $self->{'Table'} = shift unless defined ( $self->table );
162 my $hashref = $self->{'Hash'} = shift;
164 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
165 my $obj = $cache->cache->{$hashref->{$cache->key}};
166 $obj->_cache($hashref, $cache) if $obj->can('_cache');
169 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
176 my $class = ref($proto) || $proto;
178 bless ($self, $class);
179 if ( defined $self->table ) {
180 cluck "create constructor is deprecated, use new!";
183 croak "FS::Record::create called (not from a subclass)!";
187 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
189 Searches the database for all records matching (at least) the key/value pairs
190 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
191 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
194 The preferred usage is to pass a hash reference of named parameters:
196 my @records = qsearch( {
197 'table' => 'table_name',
198 'hashref' => { 'field' => 'value'
199 'field' => { 'op' => '<',
204 #these are optional...
206 'extra_sql' => 'AND field ',
207 #'cache_obj' => '', #optional
208 'addl_from' => 'LEFT JOIN othtable USING ( field )',
212 Much code still uses old-style positional parameters, this is also probably
213 fine in the common case where there are only two parameters:
215 my @records = qsearch( 'table', { 'field' => 'value' } );
217 ###oops, argh, FS::Record::new only lets us create database fields.
218 #Normal behaviour if SELECT is not specified is `*', as in
219 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
220 #feature where you can specify SELECT - remember, the objects returned,
221 #although blessed into the appropriate `FS::TABLE' package, will only have the
222 #fields you specify. This might have unwanted results if you then go calling
223 #regular FS::TABLE methods
229 my($stable, $record, $select, $extra_sql, $cache, $addl_from );
230 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
232 $stable = $opt->{'table'} or die "table name is required";
233 $record = $opt->{'hashref'} || {};
234 $select = $opt->{'select'} || '*';
235 $extra_sql = $opt->{'extra_sql'} || '';
236 $cache = $opt->{'cache_obj'} || '';
237 $addl_from = $opt->{'addl_from'} || '';
239 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
243 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
245 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
249 my $table = $cache ? $cache->table : $stable;
250 my $dbdef_table = dbdef->table($table)
251 or die "No schema for table $table found - ".
252 "do you need to run freeside-upgrade?";
253 my $pkey = $dbdef_table->primary_key;
255 my @real_fields = grep exists($record->{$_}), real_fields($table);
257 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
258 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
260 cluck "warning: FS::$table not loaded; virtual fields not searchable";
261 @virtual_fields = ();
264 my $statement = "SELECT $select FROM $stable";
265 $statement .= " $addl_from" if $addl_from;
266 if ( @real_fields or @virtual_fields ) {
267 $statement .= ' WHERE '. join(' AND ',
272 if ( ref($record->{$_}) ) {
273 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
274 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
275 if ( uc($op) eq 'ILIKE' ) {
277 $record->{$_}{'value'} = lc($record->{$_}{'value'});
278 $column = "LOWER($_)";
280 $record->{$_} = $record->{$_}{'value'}
283 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
285 if ( driver_name eq 'Pg' ) {
286 my $type = dbdef->table($table)->column($column)->type;
287 if ( $type =~ /(int|(big)?serial)/i ) {
288 qq-( $column IS NULL )-;
290 qq-( $column IS NULL OR $column = '' )-;
293 qq-( $column IS NULL OR $column = "" )-;
295 } elsif ( $op eq '!=' ) {
296 if ( driver_name eq 'Pg' ) {
297 my $type = dbdef->table($table)->column($column)->type;
298 if ( $type =~ /(int|(big)?serial)/i ) {
299 qq-( $column IS NOT NULL )-;
301 qq-( $column IS NOT NULL AND $column != '' )-;
304 qq-( $column IS NOT NULL AND $column != "" )-;
307 if ( driver_name eq 'Pg' ) {
308 qq-( $column $op '' )-;
310 qq-( $column $op "" )-;
320 if ( ref($record->{$_}) ) {
321 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
322 if ( uc($op) eq 'ILIKE' ) {
324 $record->{$_}{'value'} = lc($record->{$_}{'value'});
325 $column = "LOWER($_)";
327 $record->{$_} = $record->{$_}{'value'};
330 # ... EXISTS ( SELECT name, value FROM part_virtual_field
332 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
333 # WHERE recnum = svc_acct.svcnum
334 # AND (name, value) = ('egad', 'brain') )
336 my $value = $record->{$_};
340 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
341 "( SELECT part_virtual_field.name, virtual_field.value ".
342 "FROM part_virtual_field JOIN virtual_field ".
343 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
344 "WHERE virtual_field.recnum = ${table}.${pkey} ".
345 "AND part_virtual_field.name = '${column}'".
347 " AND virtual_field.value ${op} '${value}'"
351 } @virtual_fields ) );
355 $statement .= " $extra_sql" if defined($extra_sql);
357 warn "[debug]$me $statement\n" if $DEBUG > 1;
358 my $sth = $dbh->prepare($statement)
359 or croak "$dbh->errstr doing $statement";
364 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
366 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
367 && dbdef->table($table)->column($field)->type =~ /(int|(big)?serial)/i
369 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
371 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
375 # $sth->execute( map $record->{$_},
376 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
377 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
379 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
381 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
382 @virtual_fields = "FS::$table"->virtual_fields;
384 cluck "warning: FS::$table not loaded; virtual fields not returned either";
385 @virtual_fields = ();
389 tie %result, "Tie::IxHash";
390 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
391 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
392 %result = map { $_->{$pkey}, $_ } @stuff;
394 @result{@stuff} = @stuff;
399 if ( keys(%result) and @virtual_fields ) {
401 "SELECT virtual_field.recnum, part_virtual_field.name, ".
402 "virtual_field.value ".
403 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
404 "WHERE part_virtual_field.dbtable = '$table' AND ".
405 "virtual_field.recnum IN (".
406 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
407 join(q!', '!, @virtual_fields) . "')";
408 warn "[debug]$me $statement\n" if $DEBUG > 1;
409 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
410 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
412 foreach (@{ $sth->fetchall_arrayref({}) }) {
413 my $recnum = $_->{recnum};
414 my $name = $_->{name};
415 my $value = $_->{value};
416 if (exists($result{$recnum})) {
417 $result{$recnum}->{$name} = $value;
422 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
423 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
424 #derivied class didn't override new method, so this optimization is safe
427 new_or_cached( "FS::$table", { %{$_} }, $cache )
431 new( "FS::$table", { %{$_} } )
435 #okay, its been tested
436 # warn "untested code (class FS::$table uses custom new method)";
438 eval 'FS::'. $table. '->new( { %{$_} } )';
442 # Check for encrypted fields and decrypt them.
443 my $conf = new FS::Conf;
444 if ($conf->exists('encryption') && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
445 foreach my $record (@return) {
446 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
447 # Set it directly... This may cause a problem in the future...
448 $record->setfield($field, $record->decrypt($record->getfield($field)));
453 cluck "warning: FS::$table not loaded; returning FS::Record objects";
455 FS::Record->new( $table, { %{$_} } );
461 =item by_key PRIMARY_KEY_VALUE
463 This is a class method that returns the record with the given primary key
464 value. This method is only useful in FS::Record subclasses. For example:
466 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
470 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
475 my ($class, $pkey_value) = @_;
477 my $table = $class->table
478 or croak "No table for $class found";
480 my $dbdef_table = dbdef->table($table)
481 or die "No schema for table $table found - ".
482 "do you need to create it or run dbdef-create?";
483 my $pkey = $dbdef_table->primary_key
484 or die "No primary key for table $table";
486 return qsearchs($table, { $pkey => $pkey_value });
489 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
491 Experimental JOINed search method. Using this method, you can execute a
492 single SELECT spanning multiple tables, and cache the results for subsequent
493 method calls. Interface will almost definately change in an incompatible
501 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
502 my $cache = FS::SearchCache->new( $ptable, $pkey );
505 grep { !$saw{$_->getfield($pkey)}++ }
506 qsearch($table, $record, $select, $extra_sql, $cache )
510 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
512 Same as qsearch, except that if more than one record matches, it B<carp>s but
513 returns the first. If this happens, you either made a logic error in asking
514 for a single item, or your data is corrupted.
518 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
520 my(@result) = qsearch(@_);
521 cluck "warning: Multiple records in scalar search ($table)"
522 if scalar(@result) > 1;
523 #should warn more vehemently if the search was on a primary key?
524 scalar(@result) ? ($result[0]) : ();
535 Returns the table name.
540 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
547 Returns the DBIx::DBSchema::Table object for the table.
553 my($table)=$self->table;
554 dbdef->table($table);
557 =item get, getfield COLUMN
559 Returns the value of the column/field/key COLUMN.
564 my($self,$field) = @_;
565 # to avoid "Use of unitialized value" errors
566 if ( defined ( $self->{Hash}->{$field} ) ) {
567 $self->{Hash}->{$field};
577 =item set, setfield COLUMN, VALUE
579 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
584 my($self,$field,$value) = @_;
585 $self->{'modified'} = 1;
586 $self->{'Hash'}->{$field} = $value;
593 =item AUTLOADED METHODS
595 $record->column is a synonym for $record->get('column');
597 $record->column('value') is a synonym for $record->set('column','value');
604 my($field)=$AUTOLOAD;
606 if ( defined($value) ) {
607 confess "errant AUTOLOAD $field for $self (arg $value)"
608 unless ref($self) && $self->can('setfield');
609 $self->setfield($field,$value);
611 confess "errant AUTOLOAD $field for $self (no args)"
612 unless ref($self) && $self->can('getfield');
613 $self->getfield($field);
619 # my $field = $AUTOLOAD;
621 # if ( defined($_[1]) ) {
622 # $_[0]->setfield($field, $_[1]);
624 # $_[0]->getfield($field);
630 Returns a list of the column/value pairs, usually for assigning to a new hash.
632 To make a distinct duplicate of an FS::Record object, you can do:
634 $new = new FS::Record ( $old->table, { $old->hash } );
640 confess $self. ' -> hash: Hash attribute is undefined'
641 unless defined($self->{'Hash'});
642 %{ $self->{'Hash'} };
647 Returns a reference to the column/value hash. This may be deprecated in the
648 future; if there's a reason you can't just use the autoloaded or get/set
660 Returns true if any of this object's values have been modified with set (or via
661 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
673 Inserts this record to the database. If there is an error, returns the error,
674 otherwise returns false.
682 my $error = $self->check;
683 return $error if $error;
685 #single-field unique keys are given a value if false
686 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
687 foreach ( $self->dbdef_table->unique->singles ) {
688 $self->unique($_) unless $self->getfield($_);
691 #and also the primary key, if the database isn't going to
692 my $primary_key = $self->dbdef_table->primary_key;
694 if ( $primary_key ) {
695 my $col = $self->dbdef_table->column($primary_key);
698 uc($col->type) =~ /^(BIG)?SERIAL\d?/
699 || ( driver_name eq 'Pg'
700 && defined($col->default)
701 && $col->default =~ /^nextval\(/i
703 || ( driver_name eq 'mysql'
704 && defined($col->local)
705 && $col->local =~ /AUTO_INCREMENT/i
707 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
710 my $table = $self->table;
713 # Encrypt before the database
714 my $conf = new FS::Conf;
715 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
716 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
717 $self->{'saved'} = $self->getfield($field);
718 $self->setfield($field, $self->enrypt($self->getfield($field)));
723 #false laziness w/delete
725 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
728 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
731 my $statement = "INSERT INTO $table ";
732 if ( @real_fields ) {
735 join( ', ', @real_fields ).
737 join( ', ', @values ).
741 $statement .= 'DEFAULT VALUES';
743 warn "[debug]$me $statement\n" if $DEBUG > 1;
744 my $sth = dbh->prepare($statement) or return dbh->errstr;
746 local $SIG{HUP} = 'IGNORE';
747 local $SIG{INT} = 'IGNORE';
748 local $SIG{QUIT} = 'IGNORE';
749 local $SIG{TERM} = 'IGNORE';
750 local $SIG{TSTP} = 'IGNORE';
751 local $SIG{PIPE} = 'IGNORE';
753 $sth->execute or return $sth->errstr;
755 # get inserted id from the database, if applicable & needed
756 if ( $db_seq && ! $self->getfield($primary_key) ) {
757 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
761 if ( driver_name eq 'Pg' ) {
763 #my $oid = $sth->{'pg_oid_status'};
764 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
766 my $default = $self->dbdef_table->column($primary_key)->default;
767 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
768 dbh->rollback if $FS::UID::AutoCommit;
769 return "can't parse $table.$primary_key default value".
770 " for sequence name: $default";
774 my $i_sql = "SELECT currval('$sequence')";
775 my $i_sth = dbh->prepare($i_sql) or do {
776 dbh->rollback if $FS::UID::AutoCommit;
779 #$i_sth->execute($oid) or do {
780 $i_sth->execute() or do {
781 dbh->rollback if $FS::UID::AutoCommit;
782 return $i_sth->errstr;
784 $insertid = $i_sth->fetchrow_arrayref->[0];
786 } elsif ( driver_name eq 'mysql' ) {
788 $insertid = dbh->{'mysql_insertid'};
789 # work around mysql_insertid being null some of the time, ala RT :/
790 unless ( $insertid ) {
791 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
792 "using SELECT LAST_INSERT_ID();";
793 my $i_sql = "SELECT LAST_INSERT_ID()";
794 my $i_sth = dbh->prepare($i_sql) or do {
795 dbh->rollback if $FS::UID::AutoCommit;
798 $i_sth->execute or do {
799 dbh->rollback if $FS::UID::AutoCommit;
800 return $i_sth->errstr;
802 $insertid = $i_sth->fetchrow_arrayref->[0];
807 dbh->rollback if $FS::UID::AutoCommit;
808 return "don't know how to retreive inserted ids from ". driver_name.
809 ", try using counterfiles (maybe run dbdef-create?)";
813 $self->setfield($primary_key, $insertid);
818 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
819 $self->virtual_fields;
820 if (@virtual_fields) {
821 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
823 my $vfieldpart = $self->vfieldpart_hashref;
825 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
828 my $v_sth = dbh->prepare($v_statement) or do {
829 dbh->rollback if $FS::UID::AutoCommit;
833 foreach (keys(%v_values)) {
834 $v_sth->execute($self->getfield($primary_key),
838 dbh->rollback if $FS::UID::AutoCommit;
839 return $v_sth->errstr;
846 if ( defined dbdef->table('h_'. $table) ) {
847 my $h_statement = $self->_h_statement('insert');
848 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
849 $h_sth = dbh->prepare($h_statement) or do {
850 dbh->rollback if $FS::UID::AutoCommit;
856 $h_sth->execute or return $h_sth->errstr if $h_sth;
858 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
860 # Now that it has been saved, reset the encrypted fields so that $new
862 foreach my $field (keys %{$saved}) {
863 $self->setfield($field, $saved->{$field});
871 Depriciated (use insert instead).
876 cluck "warning: FS::Record::add deprecated!";
877 insert @_; #call method in this scope
882 Delete this record from the database. If there is an error, returns the error,
883 otherwise returns false.
890 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
892 $self->getfield($_) eq ''
893 #? "( $_ IS NULL OR $_ = \"\" )"
894 ? ( driver_name eq 'Pg'
896 : "( $_ IS NULL OR $_ = \"\" )"
898 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
899 } ( $self->dbdef_table->primary_key )
900 ? ( $self->dbdef_table->primary_key)
901 : real_fields($self->table)
903 warn "[debug]$me $statement\n" if $DEBUG > 1;
904 my $sth = dbh->prepare($statement) or return dbh->errstr;
907 if ( defined dbdef->table('h_'. $self->table) ) {
908 my $h_statement = $self->_h_statement('delete');
909 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
910 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
915 my $primary_key = $self->dbdef_table->primary_key;
918 my $vfp = $self->vfieldpart_hashref;
919 foreach($self->virtual_fields) {
920 next if $self->getfield($_) eq '';
921 unless(@del_vfields) {
922 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
923 $v_sth = dbh->prepare($st) or return dbh->errstr;
925 push @del_vfields, $_;
928 local $SIG{HUP} = 'IGNORE';
929 local $SIG{INT} = 'IGNORE';
930 local $SIG{QUIT} = 'IGNORE';
931 local $SIG{TERM} = 'IGNORE';
932 local $SIG{TSTP} = 'IGNORE';
933 local $SIG{PIPE} = 'IGNORE';
935 my $rc = $sth->execute or return $sth->errstr;
936 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
937 $h_sth->execute or return $h_sth->errstr if $h_sth;
938 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
939 or return $v_sth->errstr
940 foreach (@del_vfields);
942 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
944 #no need to needlessly destoy the data either (causes problems actually)
945 #undef $self; #no need to keep object!
952 Depriciated (use delete instead).
957 cluck "warning: FS::Record::del deprecated!";
958 &delete(@_); #call method in this scope
961 =item replace OLD_RECORD
963 Replace the OLD_RECORD with this one in the database. If there is an error,
964 returns the error, otherwise returns false.
972 if (!defined($old)) {
973 warn "[debug]$me replace called with no arguments; autoloading old record\n"
975 my $primary_key = $new->dbdef_table->primary_key;
976 if ( $primary_key ) {
977 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
978 or croak "can't find ". $new->table. ".$primary_key ".
979 $new->$primary_key();
981 croak $new->table. " has no primary key; pass old record as argument";
985 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
987 if ( $new->can('replace_check') ) {
988 my $error = $new->replace_check($old);
989 return $error if $error;
992 return "Records not in same table!" unless $new->table eq $old->table;
994 my $primary_key = $old->dbdef_table->primary_key;
995 return "Can't change primary key $primary_key ".
996 'from '. $old->getfield($primary_key).
997 ' to ' . $new->getfield($primary_key)
999 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1001 my $error = $new->check;
1002 return $error if $error;
1004 # Encrypt for replace
1005 my $conf = new FS::Conf;
1007 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
1008 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1009 $saved->{$field} = $new->getfield($field);
1010 $new->setfield($field, $new->encrypt($new->getfield($field)));
1014 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1015 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1016 ? ($_, $new->getfield($_)) : () } $old->fields;
1018 unless ( keys(%diff) ) {
1019 carp "[warning]$me $new -> replace $old: records identical"
1020 unless $nowarn_identical;
1024 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1026 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1027 } real_fields($old->table)
1032 if ( $old->getfield($_) eq '' ) {
1034 #false laziness w/qsearch
1035 if ( driver_name eq 'Pg' ) {
1036 my $type = $old->dbdef_table->column($_)->type;
1037 if ( $type =~ /(int|(big)?serial)/i ) {
1040 qq-( $_ IS NULL OR $_ = '' )-;
1043 qq-( $_ IS NULL OR $_ = "" )-;
1047 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1050 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1053 warn "[debug]$me $statement\n" if $DEBUG > 1;
1054 my $sth = dbh->prepare($statement) or return dbh->errstr;
1057 if ( defined dbdef->table('h_'. $old->table) ) {
1058 my $h_old_statement = $old->_h_statement('replace_old');
1059 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1060 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1066 if ( defined dbdef->table('h_'. $new->table) ) {
1067 my $h_new_statement = $new->_h_statement('replace_new');
1068 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1069 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1074 # For virtual fields we have three cases with different SQL
1075 # statements: add, replace, delete
1079 my (@add_vfields, @rep_vfields, @del_vfields);
1080 my $vfp = $old->vfieldpart_hashref;
1081 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1082 if($diff{$_} eq '') {
1084 unless(@del_vfields) {
1085 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1086 "AND vfieldpart = ?";
1087 warn "[debug]$me $st\n" if $DEBUG > 2;
1088 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1090 push @del_vfields, $_;
1091 } elsif($old->getfield($_) eq '') {
1093 unless(@add_vfields) {
1094 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1096 warn "[debug]$me $st\n" if $DEBUG > 2;
1097 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1099 push @add_vfields, $_;
1102 unless(@rep_vfields) {
1103 my $st = "UPDATE virtual_field SET value = ? ".
1104 "WHERE recnum = ? AND vfieldpart = ?";
1105 warn "[debug]$me $st\n" if $DEBUG > 2;
1106 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1108 push @rep_vfields, $_;
1112 local $SIG{HUP} = 'IGNORE';
1113 local $SIG{INT} = 'IGNORE';
1114 local $SIG{QUIT} = 'IGNORE';
1115 local $SIG{TERM} = 'IGNORE';
1116 local $SIG{TSTP} = 'IGNORE';
1117 local $SIG{PIPE} = 'IGNORE';
1119 my $rc = $sth->execute or return $sth->errstr;
1120 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1121 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1122 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1124 $v_del_sth->execute($old->getfield($primary_key),
1126 or return $v_del_sth->errstr
1127 foreach(@del_vfields);
1129 $v_add_sth->execute($new->getfield($_),
1130 $old->getfield($primary_key),
1132 or return $v_add_sth->errstr
1133 foreach(@add_vfields);
1135 $v_rep_sth->execute($new->getfield($_),
1136 $old->getfield($primary_key),
1138 or return $v_rep_sth->errstr
1139 foreach(@rep_vfields);
1141 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1143 # Now that it has been saved, reset the encrypted fields so that $new
1144 # can still be used.
1145 foreach my $field (keys %{$saved}) {
1146 $new->setfield($field, $saved->{$field});
1155 Depriciated (use replace instead).
1160 cluck "warning: FS::Record::rep deprecated!";
1161 replace @_; #call method in this scope
1166 Checks virtual fields (using check_blocks). Subclasses should still provide
1167 a check method to validate real fields, foreign keys, etc., and call this
1168 method via $self->SUPER::check.
1170 (FIXME: Should this method try to make sure that it I<is> being called from
1171 a subclass's check method, to keep the current semantics as far as possible?)
1176 #confess "FS::Record::check not implemented; supply one in subclass!";
1179 foreach my $field ($self->virtual_fields) {
1180 for ($self->getfield($field)) {
1181 # See notes on check_block in FS::part_virtual_field.
1182 eval $self->pvf($field)->check_block;
1184 #this is bad, probably want to follow the stack backtrace up and see
1186 my $err = "Fatal error checking $field for $self";
1188 return "$err (see log for backtrace): $@";
1191 $self->setfield($field, $_);
1198 my( $self, $action, $time ) = @_;
1203 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1204 real_fields($self->table);
1206 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1208 "INSERT INTO h_". $self->table. " ( ".
1209 join(', ', qw(history_date history_user history_action), @fields ).
1211 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1218 B<Warning>: External use is B<deprecated>.
1220 Replaces COLUMN in record with a unique number, using counters in the
1221 filesystem. Used by the B<insert> method on single-field unique columns
1222 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1223 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1225 Returns the new value.
1230 my($self,$field) = @_;
1231 my($table)=$self->table;
1233 croak "Unique called on field $field, but it is ",
1234 $self->getfield($field),
1236 if $self->getfield($field);
1238 #warn "table $table is tainted" if is_tainted($table);
1239 #warn "field $field is tainted" if is_tainted($field);
1241 my($counter) = new File::CounterFile "$table.$field",0;
1243 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1245 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1248 my $index = $counter->inc;
1249 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1251 $index =~ /^(\d*)$/;
1254 $self->setfield($field,$index);
1258 =item ut_float COLUMN
1260 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1261 null. If there is an error, returns the error, otherwise returns false.
1266 my($self,$field)=@_ ;
1267 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1268 $self->getfield($field) =~ /^(\d+)$/ ||
1269 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1270 $self->getfield($field) =~ /^(\d+e\d+)$/)
1271 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1272 $self->setfield($field,$1);
1276 =item ut_snumber COLUMN
1278 Check/untaint signed numeric data (whole numbers). May not be null. If there
1279 is an error, returns the error, otherwise returns false.
1284 my($self, $field) = @_;
1285 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1286 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1287 $self->setfield($field, "$1$2");
1291 =item ut_number COLUMN
1293 Check/untaint simple numeric data (whole numbers). May not be null. If there
1294 is an error, returns the error, otherwise returns false.
1299 my($self,$field)=@_;
1300 $self->getfield($field) =~ /^(\d+)$/
1301 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1302 $self->setfield($field,$1);
1306 =item ut_numbern COLUMN
1308 Check/untaint simple numeric data (whole numbers). May be null. If there is
1309 an error, returns the error, otherwise returns false.
1314 my($self,$field)=@_;
1315 $self->getfield($field) =~ /^(\d*)$/
1316 or return "Illegal (numeric) $field: ". $self->getfield($field);
1317 $self->setfield($field,$1);
1321 =item ut_money COLUMN
1323 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1324 is an error, returns the error, otherwise returns false.
1329 my($self,$field)=@_;
1330 $self->setfield($field, 0) if $self->getfield($field) eq '';
1331 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1332 or return "Illegal (money) $field: ". $self->getfield($field);
1333 #$self->setfield($field, "$1$2$3" || 0);
1334 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1338 =item ut_text COLUMN
1340 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1341 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1342 May not be null. If there is an error, returns the error, otherwise returns
1348 my($self,$field)=@_;
1349 #warn "msgcat ". \&msgcat. "\n";
1350 #warn "notexist ". \¬exist. "\n";
1351 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1352 $self->getfield($field)
1353 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1354 or return gettext('illegal_or_empty_text'). " $field: ".
1355 $self->getfield($field);
1356 $self->setfield($field,$1);
1360 =item ut_textn COLUMN
1362 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1363 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1364 May be null. If there is an error, returns the error, otherwise returns false.
1369 my($self,$field)=@_;
1370 $self->getfield($field)
1371 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1372 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1373 $self->setfield($field,$1);
1377 =item ut_alpha COLUMN
1379 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1380 an error, returns the error, otherwise returns false.
1385 my($self,$field)=@_;
1386 $self->getfield($field) =~ /^(\w+)$/
1387 or return "Illegal or empty (alphanumeric) $field: ".
1388 $self->getfield($field);
1389 $self->setfield($field,$1);
1393 =item ut_alpha COLUMN
1395 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1396 error, returns the error, otherwise returns false.
1401 my($self,$field)=@_;
1402 $self->getfield($field) =~ /^(\w*)$/
1403 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1404 $self->setfield($field,$1);
1408 =item ut_phonen COLUMN [ COUNTRY ]
1410 Check/untaint phone numbers. May be null. If there is an error, returns
1411 the error, otherwise returns false.
1413 Takes an optional two-letter ISO country code; without it or with unsupported
1414 countries, ut_phonen simply calls ut_alphan.
1419 my( $self, $field, $country ) = @_;
1420 return $self->ut_alphan($field) unless defined $country;
1421 my $phonen = $self->getfield($field);
1422 if ( $phonen eq '' ) {
1423 $self->setfield($field,'');
1424 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1426 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1427 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1428 $phonen = "$1-$2-$3";
1429 $phonen .= " x$4" if $4;
1430 $self->setfield($field,$phonen);
1432 warn "warning: don't know how to check phone numbers for country $country";
1433 return $self->ut_textn($field);
1440 Check/untaint ip addresses. IPv4 only for now.
1445 my( $self, $field ) = @_;
1446 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1447 or return "Illegal (IP address) $field: ". $self->getfield($field);
1448 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1449 $self->setfield($field, "$1.$2.$3.$4");
1455 Check/untaint ip addresses. IPv4 only for now. May be null.
1460 my( $self, $field ) = @_;
1461 if ( $self->getfield($field) =~ /^()$/ ) {
1462 $self->setfield($field,'');
1465 $self->ut_ip($field);
1469 =item ut_domain COLUMN
1471 Check/untaint host and domain names.
1476 my( $self, $field ) = @_;
1477 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1478 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1479 or return "Illegal (domain) $field: ". $self->getfield($field);
1480 $self->setfield($field,$1);
1484 =item ut_name COLUMN
1486 Check/untaint proper names; allows alphanumerics, spaces and the following
1487 punctuation: , . - '
1494 my( $self, $field ) = @_;
1495 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1496 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1497 $self->setfield($field,$1);
1503 Check/untaint zip codes.
1507 my @zip_reqd_countries = qw( CA ); #US implicit...
1510 my( $self, $field, $country ) = @_;
1512 if ( $country eq 'US' ) {
1514 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1515 or return gettext('illegal_zip'). " $field for country $country: ".
1516 $self->getfield($field);
1517 $self->setfield($field, $1);
1519 } elsif ( $country eq 'CA' ) {
1521 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1522 or return gettext('illegal_zip'). " $field for country $country: ".
1523 $self->getfield($field);
1524 $self->setfield($field, "$1 $2");
1528 if ( $self->getfield($field) =~ /^\s*$/
1529 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1532 $self->setfield($field,'');
1534 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1535 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1536 $self->setfield($field,$1);
1544 =item ut_country COLUMN
1546 Check/untaint country codes. Country names are changed to codes, if possible -
1547 see L<Locale::Country>.
1552 my( $self, $field ) = @_;
1553 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1554 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1555 && country2code($1) ) {
1556 $self->setfield($field,uc(country2code($1)));
1559 $self->getfield($field) =~ /^(\w\w)$/
1560 or return "Illegal (country) $field: ". $self->getfield($field);
1561 $self->setfield($field,uc($1));
1565 =item ut_anything COLUMN
1567 Untaints arbitrary data. Be careful.
1572 my( $self, $field ) = @_;
1573 $self->getfield($field) =~ /^(.*)$/s
1574 or return "Illegal $field: ". $self->getfield($field);
1575 $self->setfield($field,$1);
1579 =item ut_enum COLUMN CHOICES_ARRAYREF
1581 Check/untaint a column, supplying all possible choices, like the "enum" type.
1586 my( $self, $field, $choices ) = @_;
1587 foreach my $choice ( @$choices ) {
1588 if ( $self->getfield($field) eq $choice ) {
1589 $self->setfield($choice);
1593 return "Illegal (enum) field $field: ". $self->getfield($field);
1596 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1598 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1599 on the column first.
1603 sub ut_foreign_key {
1604 my( $self, $field, $table, $foreign ) = @_;
1605 qsearchs($table, { $foreign => $self->getfield($field) })
1606 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1607 " in $table.$foreign";
1611 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1613 Like ut_foreign_key, except the null value is also allowed.
1617 sub ut_foreign_keyn {
1618 my( $self, $field, $table, $foreign ) = @_;
1619 $self->getfield($field)
1620 ? $self->ut_foreign_key($field, $table, $foreign)
1624 =item ut_agentnum_acl
1626 Checks this column as an agentnum, taking into account the current users's
1631 sub ut_agentnum_acl {
1632 my( $self, $field, $null_acl ) = @_;
1634 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1635 return "Illegal agentnum: $error" if $error;
1637 my $curuser = $FS::CurrentUser::CurrentUser;
1639 if ( $self->$field() ) {
1641 return "Access deined"
1642 unless $curuser->agentnum($self->$field());
1646 return "Access denied"
1647 unless $curuser->access_right($null_acl);
1655 =item virtual_fields [ TABLE ]
1657 Returns a list of virtual fields defined for the table. This should not
1658 be exported, and should only be called as an instance or class method.
1662 sub virtual_fields {
1665 $table = $self->table or confess "virtual_fields called on non-table";
1667 confess "Unknown table $table" unless dbdef->table($table);
1669 return () unless dbdef->table('part_virtual_field');
1671 unless ( $virtual_fields_cache{$table} ) {
1672 my $query = 'SELECT name from part_virtual_field ' .
1673 "WHERE dbtable = '$table'";
1675 my $result = $dbh->selectcol_arrayref($query);
1676 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1678 $virtual_fields_cache{$table} = $result;
1681 @{$virtual_fields_cache{$table}};
1686 =item fields [ TABLE ]
1688 This is a wrapper for real_fields and virtual_fields. Code that called
1689 fields before should probably continue to call fields.
1694 my $something = shift;
1696 if($something->isa('FS::Record')) {
1697 $table = $something->table;
1699 $table = $something;
1700 $something = "FS::$table";
1702 return (real_fields($table), $something->virtual_fields());
1707 =item pvf FIELD_NAME
1709 Returns the FS::part_virtual_field object corresponding to a field in the
1710 record (specified by FIELD_NAME).
1715 my ($self, $name) = (shift, shift);
1717 if(grep /^$name$/, $self->virtual_fields) {
1718 return qsearchs('part_virtual_field', { dbtable => $self->table,
1728 =item real_fields [ TABLE ]
1730 Returns a list of the real columns in the specified table. Called only by
1731 fields() and other subroutines elsewhere in FS::Record.
1738 my($table_obj) = dbdef->table($table);
1739 confess "Unknown table $table" unless $table_obj;
1740 $table_obj->columns;
1743 =item _quote VALUE, TABLE, COLUMN
1745 This is an internal function used to construct SQL statements. It returns
1746 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1747 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1752 my($value, $table, $column) = @_;
1753 my $column_obj = dbdef->table($table)->column($column);
1754 my $column_type = $column_obj->type;
1755 my $nullable = $column_obj->null;
1757 warn " $table.$column: $value ($column_type".
1758 ( $nullable ? ' NULL' : ' NOT NULL' ).
1759 ")\n" if $DEBUG > 2;
1761 if ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
1765 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1769 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1770 ! $column_type =~ /(char|binary|text)$/i ) {
1777 =item vfieldpart_hashref TABLE
1779 Returns a hashref of virtual field names and vfieldparts applicable to the given
1784 sub vfieldpart_hashref {
1786 my $table = $self->table;
1788 return {} unless dbdef->table('part_virtual_field');
1791 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1792 "dbtable = '$table'";
1793 my $sth = $dbh->prepare($statement);
1794 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1795 return { map { $_->{name}, $_->{vfieldpart} }
1796 @{$sth->fetchall_arrayref({})} };
1803 This is deprecated. Don't use it.
1805 It returns a hash-type list with the fields of this record's table set true.
1810 carp "warning: hfields is deprecated";
1813 foreach (fields($table)) {
1822 "$_: ". $self->getfield($_). "|"
1823 } (fields($self->table)) );
1827 my ($self, $value) = @_;
1830 my $conf = new FS::Conf;
1831 if ($conf->exists('encryption')) {
1832 if ($self->is_encrypted($value)) {
1833 # Return the original value if it isn't plaintext.
1834 $encrypted = $value;
1837 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1838 # RSA doesn't like the empty string so let's pack it up
1839 # The database doesn't like the RSA data so uuencode it
1840 my $length = length($value)+1;
1841 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1843 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1851 my ($self, $value) = @_;
1852 # Possible Bug - Some work may be required here....
1854 if (length($value) > 80) {
1862 my ($self,$value) = @_;
1863 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1864 my $conf = new FS::Conf;
1865 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1867 if (ref($rsa_decrypt) =~ /::RSA/) {
1868 my $encrypted = unpack ("u*", $value);
1869 $decrypted = unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1877 #Initialize the Module
1878 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1880 my $conf = new FS::Conf;
1881 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1882 $rsa_module = $conf->config('encryptionmodule');
1886 eval ("require $rsa_module"); # No need to import the namespace
1889 # Initialize Encryption
1890 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1891 my $public_key = join("\n",$conf->config('encryptionpublickey'));
1892 $rsa_encrypt = $rsa_module->new_public_key($public_key);
1895 # Intitalize Decryption
1896 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1897 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1898 $rsa_decrypt = $rsa_module->new_private_key($private_key);
1902 sub DESTROY { return; }
1906 # #use Carp qw(cluck);
1907 # #cluck "DESTROYING $self";
1908 # warn "DESTROYING $self";
1912 # return ! eval { join('',@_), kill 0; 1; };
1919 This module should probably be renamed, since much of the functionality is
1920 of general use. It is not completely unlike Adapter::DBI (see below).
1922 Exported qsearch and qsearchs should be deprecated in favor of method calls
1923 (against an FS::Record object like the old search and searchs that qsearch
1924 and qsearchs were on top of.)
1926 The whole fields / hfields mess should be removed.
1928 The various WHERE clauses should be subroutined.
1930 table string should be deprecated in favor of DBIx::DBSchema::Table.
1932 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1933 true maps to the database (and WHERE clauses) would also help.
1935 The ut_ methods should ask the dbdef for a default length.
1937 ut_sqltype (like ut_varchar) should all be defined
1939 A fallback check method should be provided which uses the dbdef.
1941 The ut_money method assumes money has two decimal digits.
1943 The Pg money kludge in the new method only strips `$'.
1945 The ut_phonen method only checks US-style phone numbers.
1947 The _quote function should probably use ut_float instead of a regex.
1949 All the subroutines probably should be methods, here or elsewhere.
1951 Probably should borrow/use some dbdef methods where appropriate (like sub
1954 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1955 or allow it to be set. Working around it is ugly any way around - DBI should
1956 be fixed. (only affects RDBMS which return uppercase column names)
1958 ut_zip should take an optional country like ut_phone.
1962 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1964 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.