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_snumber('column');
87 $error = $record->ut_snumbern('column');
88 $error = $record->ut_money('column');
89 $error = $record->ut_text('column');
90 $error = $record->ut_textn('column');
91 $error = $record->ut_alpha('column');
92 $error = $record->ut_alphan('column');
93 $error = $record->ut_phonen('column');
94 $error = $record->ut_anything('column');
95 $error = $record->ut_name('column');
97 $quoted_value = _quote($value,'table','field');
100 $fields = hfields('table');
101 if ( $fields->{Field} ) { # etc.
103 @fields = fields 'table'; #as a subroutine
104 @fields = $record->fields; #as a method call
109 (Mostly) object-oriented interface to database records. Records are currently
110 implemented on top of DBI. FS::Record is intended as a base class for
111 table-specific classes to inherit from, i.e. FS::cust_main.
117 =item new [ TABLE, ] HASHREF
119 Creates a new record. It doesn't store it in the database, though. See
120 L<"insert"> for that.
122 Note that the object stores this hash reference, not a distinct copy of the
123 hash it points to. You can ask the object for a copy with the I<hash>
126 TABLE can only be omitted when a dervived class overrides the table method.
132 my $class = ref($proto) || $proto;
134 bless ($self, $class);
136 unless ( defined ( $self->table ) ) {
137 $self->{'Table'} = shift;
138 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
141 $self->{'Hash'} = shift;
143 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
144 $self->{'Hash'}{$field}='';
147 $self->_rebless if $self->can('_rebless');
149 $self->{'modified'} = 0;
151 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
158 my $class = ref($proto) || $proto;
160 bless ($self, $class);
162 $self->{'Table'} = shift unless defined ( $self->table );
164 my $hashref = $self->{'Hash'} = shift;
166 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
167 my $obj = $cache->cache->{$hashref->{$cache->key}};
168 $obj->_cache($hashref, $cache) if $obj->can('_cache');
171 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
178 my $class = ref($proto) || $proto;
180 bless ($self, $class);
181 if ( defined $self->table ) {
182 cluck "create constructor is deprecated, use new!";
185 croak "FS::Record::create called (not from a subclass)!";
189 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
191 Searches the database for all records matching (at least) the key/value pairs
192 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
193 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
196 The preferred usage is to pass a hash reference of named parameters:
198 my @records = qsearch( {
199 'table' => 'table_name',
200 'hashref' => { 'field' => 'value'
201 'field' => { 'op' => '<',
206 #these are optional...
208 'extra_sql' => 'AND field ',
209 #'cache_obj' => '', #optional
210 'addl_from' => 'LEFT JOIN othtable USING ( field )',
214 Much code still uses old-style positional parameters, this is also probably
215 fine in the common case where there are only two parameters:
217 my @records = qsearch( 'table', { 'field' => 'value' } );
219 ###oops, argh, FS::Record::new only lets us create database fields.
220 #Normal behaviour if SELECT is not specified is `*', as in
221 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
222 #feature where you can specify SELECT - remember, the objects returned,
223 #although blessed into the appropriate `FS::TABLE' package, will only have the
224 #fields you specify. This might have unwanted results if you then go calling
225 #regular FS::TABLE methods
231 my($stable, $record, $select, $extra_sql, $cache, $addl_from );
232 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
234 $stable = $opt->{'table'} or die "table name is required";
235 $record = $opt->{'hashref'} || {};
236 $select = $opt->{'select'} || '*';
237 $extra_sql = $opt->{'extra_sql'} || '';
238 $cache = $opt->{'cache_obj'} || '';
239 $addl_from = $opt->{'addl_from'} || '';
241 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
245 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
247 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
251 my $table = $cache ? $cache->table : $stable;
252 my $dbdef_table = dbdef->table($table)
253 or die "No schema for table $table found - ".
254 "do you need to run freeside-upgrade?";
255 my $pkey = $dbdef_table->primary_key;
257 my @real_fields = grep exists($record->{$_}), real_fields($table);
259 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
260 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
262 cluck "warning: FS::$table not loaded; virtual fields not searchable";
263 @virtual_fields = ();
266 my $statement = "SELECT $select FROM $stable";
267 $statement .= " $addl_from" if $addl_from;
268 if ( @real_fields or @virtual_fields ) {
269 $statement .= ' WHERE '. join(' AND ',
274 if ( ref($record->{$_}) ) {
275 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
276 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
277 if ( uc($op) eq 'ILIKE' ) {
279 $record->{$_}{'value'} = lc($record->{$_}{'value'});
280 $column = "LOWER($_)";
282 $record->{$_} = $record->{$_}{'value'}
285 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
287 if ( driver_name eq 'Pg' ) {
288 my $type = dbdef->table($table)->column($column)->type;
289 if ( $type =~ /(int|(big)?serial)/i ) {
290 qq-( $column IS NULL )-;
292 qq-( $column IS NULL OR $column = '' )-;
295 qq-( $column IS NULL OR $column = "" )-;
297 } elsif ( $op eq '!=' ) {
298 if ( driver_name eq 'Pg' ) {
299 my $type = dbdef->table($table)->column($column)->type;
300 if ( $type =~ /(int|(big)?serial)/i ) {
301 qq-( $column IS NOT NULL )-;
303 qq-( $column IS NOT NULL AND $column != '' )-;
306 qq-( $column IS NOT NULL AND $column != "" )-;
309 if ( driver_name eq 'Pg' ) {
310 qq-( $column $op '' )-;
312 qq-( $column $op "" )-;
322 if ( ref($record->{$_}) ) {
323 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
324 if ( uc($op) eq 'ILIKE' ) {
326 $record->{$_}{'value'} = lc($record->{$_}{'value'});
327 $column = "LOWER($_)";
329 $record->{$_} = $record->{$_}{'value'};
332 # ... EXISTS ( SELECT name, value FROM part_virtual_field
334 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
335 # WHERE recnum = svc_acct.svcnum
336 # AND (name, value) = ('egad', 'brain') )
338 my $value = $record->{$_};
342 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
343 "( SELECT part_virtual_field.name, virtual_field.value ".
344 "FROM part_virtual_field JOIN virtual_field ".
345 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
346 "WHERE virtual_field.recnum = ${table}.${pkey} ".
347 "AND part_virtual_field.name = '${column}'".
349 " AND virtual_field.value ${op} '${value}'"
353 } @virtual_fields ) );
357 $statement .= " $extra_sql" if defined($extra_sql);
359 warn "[debug]$me $statement\n" if $DEBUG > 1;
360 my $sth = $dbh->prepare($statement)
361 or croak "$dbh->errstr doing $statement";
366 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
368 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
369 && dbdef->table($table)->column($field)->type =~ /(int|(big)?serial)/i
371 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
373 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
377 # $sth->execute( map $record->{$_},
378 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
379 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
381 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
383 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
384 @virtual_fields = "FS::$table"->virtual_fields;
386 cluck "warning: FS::$table not loaded; virtual fields not returned either";
387 @virtual_fields = ();
391 tie %result, "Tie::IxHash";
392 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
393 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
394 %result = map { $_->{$pkey}, $_ } @stuff;
396 @result{@stuff} = @stuff;
401 if ( keys(%result) and @virtual_fields ) {
403 "SELECT virtual_field.recnum, part_virtual_field.name, ".
404 "virtual_field.value ".
405 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
406 "WHERE part_virtual_field.dbtable = '$table' AND ".
407 "virtual_field.recnum IN (".
408 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
409 join(q!', '!, @virtual_fields) . "')";
410 warn "[debug]$me $statement\n" if $DEBUG > 1;
411 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
412 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
414 foreach (@{ $sth->fetchall_arrayref({}) }) {
415 my $recnum = $_->{recnum};
416 my $name = $_->{name};
417 my $value = $_->{value};
418 if (exists($result{$recnum})) {
419 $result{$recnum}->{$name} = $value;
424 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
425 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
426 #derivied class didn't override new method, so this optimization is safe
429 new_or_cached( "FS::$table", { %{$_} }, $cache )
433 new( "FS::$table", { %{$_} } )
437 #okay, its been tested
438 # warn "untested code (class FS::$table uses custom new method)";
440 eval 'FS::'. $table. '->new( { %{$_} } )';
444 # Check for encrypted fields and decrypt them.
445 my $conf = new FS::Conf;
446 if ($conf->exists('encryption') && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
447 foreach my $record (@return) {
448 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
449 # Set it directly... This may cause a problem in the future...
450 $record->setfield($field, $record->decrypt($record->getfield($field)));
455 cluck "warning: FS::$table not loaded; returning FS::Record objects";
457 FS::Record->new( $table, { %{$_} } );
463 =item by_key PRIMARY_KEY_VALUE
465 This is a class method that returns the record with the given primary key
466 value. This method is only useful in FS::Record subclasses. For example:
468 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
472 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
477 my ($class, $pkey_value) = @_;
479 my $table = $class->table
480 or croak "No table for $class found";
482 my $dbdef_table = dbdef->table($table)
483 or die "No schema for table $table found - ".
484 "do you need to create it or run dbdef-create?";
485 my $pkey = $dbdef_table->primary_key
486 or die "No primary key for table $table";
488 return qsearchs($table, { $pkey => $pkey_value });
491 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
493 Experimental JOINed search method. Using this method, you can execute a
494 single SELECT spanning multiple tables, and cache the results for subsequent
495 method calls. Interface will almost definately change in an incompatible
503 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
504 my $cache = FS::SearchCache->new( $ptable, $pkey );
507 grep { !$saw{$_->getfield($pkey)}++ }
508 qsearch($table, $record, $select, $extra_sql, $cache )
512 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
514 Same as qsearch, except that if more than one record matches, it B<carp>s but
515 returns the first. If this happens, you either made a logic error in asking
516 for a single item, or your data is corrupted.
520 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
522 my(@result) = qsearch(@_);
523 cluck "warning: Multiple records in scalar search ($table)"
524 if scalar(@result) > 1;
525 #should warn more vehemently if the search was on a primary key?
526 scalar(@result) ? ($result[0]) : ();
537 Returns the table name.
542 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
549 Returns the DBIx::DBSchema::Table object for the table.
555 my($table)=$self->table;
556 dbdef->table($table);
559 =item get, getfield COLUMN
561 Returns the value of the column/field/key COLUMN.
566 my($self,$field) = @_;
567 # to avoid "Use of unitialized value" errors
568 if ( defined ( $self->{Hash}->{$field} ) ) {
569 $self->{Hash}->{$field};
579 =item set, setfield COLUMN, VALUE
581 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
586 my($self,$field,$value) = @_;
587 $self->{'modified'} = 1;
588 $self->{'Hash'}->{$field} = $value;
595 =item AUTLOADED METHODS
597 $record->column is a synonym for $record->get('column');
599 $record->column('value') is a synonym for $record->set('column','value');
606 my($field)=$AUTOLOAD;
608 if ( defined($value) ) {
609 confess "errant AUTOLOAD $field for $self (arg $value)"
610 unless ref($self) && $self->can('setfield');
611 $self->setfield($field,$value);
613 confess "errant AUTOLOAD $field for $self (no args)"
614 unless ref($self) && $self->can('getfield');
615 $self->getfield($field);
621 # my $field = $AUTOLOAD;
623 # if ( defined($_[1]) ) {
624 # $_[0]->setfield($field, $_[1]);
626 # $_[0]->getfield($field);
632 Returns a list of the column/value pairs, usually for assigning to a new hash.
634 To make a distinct duplicate of an FS::Record object, you can do:
636 $new = new FS::Record ( $old->table, { $old->hash } );
642 confess $self. ' -> hash: Hash attribute is undefined'
643 unless defined($self->{'Hash'});
644 %{ $self->{'Hash'} };
649 Returns a reference to the column/value hash. This may be deprecated in the
650 future; if there's a reason you can't just use the autoloaded or get/set
662 Returns true if any of this object's values have been modified with set (or via
663 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
675 Inserts this record to the database. If there is an error, returns the error,
676 otherwise returns false.
684 my $error = $self->check;
685 return $error if $error;
687 #single-field unique keys are given a value if false
688 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
689 foreach ( $self->dbdef_table->unique->singles ) {
690 $self->unique($_) unless $self->getfield($_);
693 #and also the primary key, if the database isn't going to
694 my $primary_key = $self->dbdef_table->primary_key;
696 if ( $primary_key ) {
697 my $col = $self->dbdef_table->column($primary_key);
700 uc($col->type) =~ /^(BIG)?SERIAL\d?/
701 || ( driver_name eq 'Pg'
702 && defined($col->default)
703 && $col->default =~ /^nextval\(/i
705 || ( driver_name eq 'mysql'
706 && defined($col->local)
707 && $col->local =~ /AUTO_INCREMENT/i
709 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
712 my $table = $self->table;
715 # Encrypt before the database
716 my $conf = new FS::Conf;
717 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
718 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
719 $self->{'saved'} = $self->getfield($field);
720 $self->setfield($field, $self->enrypt($self->getfield($field)));
725 #false laziness w/delete
727 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
730 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
733 my $statement = "INSERT INTO $table ";
734 if ( @real_fields ) {
737 join( ', ', @real_fields ).
739 join( ', ', @values ).
743 $statement .= 'DEFAULT VALUES';
745 warn "[debug]$me $statement\n" if $DEBUG > 1;
746 my $sth = dbh->prepare($statement) or return dbh->errstr;
748 local $SIG{HUP} = 'IGNORE';
749 local $SIG{INT} = 'IGNORE';
750 local $SIG{QUIT} = 'IGNORE';
751 local $SIG{TERM} = 'IGNORE';
752 local $SIG{TSTP} = 'IGNORE';
753 local $SIG{PIPE} = 'IGNORE';
755 $sth->execute or return $sth->errstr;
757 # get inserted id from the database, if applicable & needed
758 if ( $db_seq && ! $self->getfield($primary_key) ) {
759 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
763 if ( driver_name eq 'Pg' ) {
765 #my $oid = $sth->{'pg_oid_status'};
766 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
768 my $default = $self->dbdef_table->column($primary_key)->default;
769 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
770 dbh->rollback if $FS::UID::AutoCommit;
771 return "can't parse $table.$primary_key default value".
772 " for sequence name: $default";
776 my $i_sql = "SELECT currval('$sequence')";
777 my $i_sth = dbh->prepare($i_sql) or do {
778 dbh->rollback if $FS::UID::AutoCommit;
781 #$i_sth->execute($oid) or do {
782 $i_sth->execute() or do {
783 dbh->rollback if $FS::UID::AutoCommit;
784 return $i_sth->errstr;
786 $insertid = $i_sth->fetchrow_arrayref->[0];
788 } elsif ( driver_name eq 'mysql' ) {
790 $insertid = dbh->{'mysql_insertid'};
791 # work around mysql_insertid being null some of the time, ala RT :/
792 unless ( $insertid ) {
793 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
794 "using SELECT LAST_INSERT_ID();";
795 my $i_sql = "SELECT LAST_INSERT_ID()";
796 my $i_sth = dbh->prepare($i_sql) or do {
797 dbh->rollback if $FS::UID::AutoCommit;
800 $i_sth->execute or do {
801 dbh->rollback if $FS::UID::AutoCommit;
802 return $i_sth->errstr;
804 $insertid = $i_sth->fetchrow_arrayref->[0];
809 dbh->rollback if $FS::UID::AutoCommit;
810 return "don't know how to retreive inserted ids from ". driver_name.
811 ", try using counterfiles (maybe run dbdef-create?)";
815 $self->setfield($primary_key, $insertid);
820 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
821 $self->virtual_fields;
822 if (@virtual_fields) {
823 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
825 my $vfieldpart = $self->vfieldpart_hashref;
827 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
830 my $v_sth = dbh->prepare($v_statement) or do {
831 dbh->rollback if $FS::UID::AutoCommit;
835 foreach (keys(%v_values)) {
836 $v_sth->execute($self->getfield($primary_key),
840 dbh->rollback if $FS::UID::AutoCommit;
841 return $v_sth->errstr;
848 if ( defined dbdef->table('h_'. $table) ) {
849 my $h_statement = $self->_h_statement('insert');
850 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
851 $h_sth = dbh->prepare($h_statement) or do {
852 dbh->rollback if $FS::UID::AutoCommit;
858 $h_sth->execute or return $h_sth->errstr if $h_sth;
860 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
862 # Now that it has been saved, reset the encrypted fields so that $new
864 foreach my $field (keys %{$saved}) {
865 $self->setfield($field, $saved->{$field});
873 Depriciated (use insert instead).
878 cluck "warning: FS::Record::add deprecated!";
879 insert @_; #call method in this scope
884 Delete this record from the database. If there is an error, returns the error,
885 otherwise returns false.
892 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
894 $self->getfield($_) eq ''
895 #? "( $_ IS NULL OR $_ = \"\" )"
896 ? ( driver_name eq 'Pg'
898 : "( $_ IS NULL OR $_ = \"\" )"
900 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
901 } ( $self->dbdef_table->primary_key )
902 ? ( $self->dbdef_table->primary_key)
903 : real_fields($self->table)
905 warn "[debug]$me $statement\n" if $DEBUG > 1;
906 my $sth = dbh->prepare($statement) or return dbh->errstr;
909 if ( defined dbdef->table('h_'. $self->table) ) {
910 my $h_statement = $self->_h_statement('delete');
911 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
912 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
917 my $primary_key = $self->dbdef_table->primary_key;
920 my $vfp = $self->vfieldpart_hashref;
921 foreach($self->virtual_fields) {
922 next if $self->getfield($_) eq '';
923 unless(@del_vfields) {
924 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
925 $v_sth = dbh->prepare($st) or return dbh->errstr;
927 push @del_vfields, $_;
930 local $SIG{HUP} = 'IGNORE';
931 local $SIG{INT} = 'IGNORE';
932 local $SIG{QUIT} = 'IGNORE';
933 local $SIG{TERM} = 'IGNORE';
934 local $SIG{TSTP} = 'IGNORE';
935 local $SIG{PIPE} = 'IGNORE';
937 my $rc = $sth->execute or return $sth->errstr;
938 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
939 $h_sth->execute or return $h_sth->errstr if $h_sth;
940 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
941 or return $v_sth->errstr
942 foreach (@del_vfields);
944 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
946 #no need to needlessly destoy the data either (causes problems actually)
947 #undef $self; #no need to keep object!
954 Depriciated (use delete instead).
959 cluck "warning: FS::Record::del deprecated!";
960 &delete(@_); #call method in this scope
963 =item replace OLD_RECORD
965 Replace the OLD_RECORD with this one in the database. If there is an error,
966 returns the error, otherwise returns false.
974 if (!defined($old)) {
975 warn "[debug]$me replace called with no arguments; autoloading old record\n"
977 my $primary_key = $new->dbdef_table->primary_key;
978 if ( $primary_key ) {
979 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
980 or croak "can't find ". $new->table. ".$primary_key ".
981 $new->$primary_key();
983 croak $new->table. " has no primary key; pass old record as argument";
987 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
989 if ( $new->can('replace_check') ) {
990 my $error = $new->replace_check($old);
991 return $error if $error;
994 return "Records not in same table!" unless $new->table eq $old->table;
996 my $primary_key = $old->dbdef_table->primary_key;
997 return "Can't change primary key $primary_key ".
998 'from '. $old->getfield($primary_key).
999 ' to ' . $new->getfield($primary_key)
1001 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1003 my $error = $new->check;
1004 return $error if $error;
1006 # Encrypt for replace
1007 my $conf = new FS::Conf;
1009 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
1010 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1011 $saved->{$field} = $new->getfield($field);
1012 $new->setfield($field, $new->encrypt($new->getfield($field)));
1016 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1017 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1018 ? ($_, $new->getfield($_)) : () } $old->fields;
1020 unless ( keys(%diff) ) {
1021 carp "[warning]$me $new -> replace $old: records identical"
1022 unless $nowarn_identical;
1026 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1028 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1029 } real_fields($old->table)
1034 if ( $old->getfield($_) eq '' ) {
1036 #false laziness w/qsearch
1037 if ( driver_name eq 'Pg' ) {
1038 my $type = $old->dbdef_table->column($_)->type;
1039 if ( $type =~ /(int|(big)?serial)/i ) {
1042 qq-( $_ IS NULL OR $_ = '' )-;
1045 qq-( $_ IS NULL OR $_ = "" )-;
1049 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1052 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1055 warn "[debug]$me $statement\n" if $DEBUG > 1;
1056 my $sth = dbh->prepare($statement) or return dbh->errstr;
1059 if ( defined dbdef->table('h_'. $old->table) ) {
1060 my $h_old_statement = $old->_h_statement('replace_old');
1061 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1062 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1068 if ( defined dbdef->table('h_'. $new->table) ) {
1069 my $h_new_statement = $new->_h_statement('replace_new');
1070 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1071 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1076 # For virtual fields we have three cases with different SQL
1077 # statements: add, replace, delete
1081 my (@add_vfields, @rep_vfields, @del_vfields);
1082 my $vfp = $old->vfieldpart_hashref;
1083 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1084 if($diff{$_} eq '') {
1086 unless(@del_vfields) {
1087 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1088 "AND vfieldpart = ?";
1089 warn "[debug]$me $st\n" if $DEBUG > 2;
1090 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1092 push @del_vfields, $_;
1093 } elsif($old->getfield($_) eq '') {
1095 unless(@add_vfields) {
1096 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1098 warn "[debug]$me $st\n" if $DEBUG > 2;
1099 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1101 push @add_vfields, $_;
1104 unless(@rep_vfields) {
1105 my $st = "UPDATE virtual_field SET value = ? ".
1106 "WHERE recnum = ? AND vfieldpart = ?";
1107 warn "[debug]$me $st\n" if $DEBUG > 2;
1108 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1110 push @rep_vfields, $_;
1114 local $SIG{HUP} = 'IGNORE';
1115 local $SIG{INT} = 'IGNORE';
1116 local $SIG{QUIT} = 'IGNORE';
1117 local $SIG{TERM} = 'IGNORE';
1118 local $SIG{TSTP} = 'IGNORE';
1119 local $SIG{PIPE} = 'IGNORE';
1121 my $rc = $sth->execute or return $sth->errstr;
1122 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1123 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1124 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1126 $v_del_sth->execute($old->getfield($primary_key),
1128 or return $v_del_sth->errstr
1129 foreach(@del_vfields);
1131 $v_add_sth->execute($new->getfield($_),
1132 $old->getfield($primary_key),
1134 or return $v_add_sth->errstr
1135 foreach(@add_vfields);
1137 $v_rep_sth->execute($new->getfield($_),
1138 $old->getfield($primary_key),
1140 or return $v_rep_sth->errstr
1141 foreach(@rep_vfields);
1143 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1145 # Now that it has been saved, reset the encrypted fields so that $new
1146 # can still be used.
1147 foreach my $field (keys %{$saved}) {
1148 $new->setfield($field, $saved->{$field});
1157 Depriciated (use replace instead).
1162 cluck "warning: FS::Record::rep deprecated!";
1163 replace @_; #call method in this scope
1168 Checks virtual fields (using check_blocks). Subclasses should still provide
1169 a check method to validate real fields, foreign keys, etc., and call this
1170 method via $self->SUPER::check.
1172 (FIXME: Should this method try to make sure that it I<is> being called from
1173 a subclass's check method, to keep the current semantics as far as possible?)
1178 #confess "FS::Record::check not implemented; supply one in subclass!";
1181 foreach my $field ($self->virtual_fields) {
1182 for ($self->getfield($field)) {
1183 # See notes on check_block in FS::part_virtual_field.
1184 eval $self->pvf($field)->check_block;
1186 #this is bad, probably want to follow the stack backtrace up and see
1188 my $err = "Fatal error checking $field for $self";
1190 return "$err (see log for backtrace): $@";
1193 $self->setfield($field, $_);
1200 my( $self, $action, $time ) = @_;
1205 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1206 real_fields($self->table);
1208 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1210 "INSERT INTO h_". $self->table. " ( ".
1211 join(', ', qw(history_date history_user history_action), @fields ).
1213 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1220 B<Warning>: External use is B<deprecated>.
1222 Replaces COLUMN in record with a unique number, using counters in the
1223 filesystem. Used by the B<insert> method on single-field unique columns
1224 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1225 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1227 Returns the new value.
1232 my($self,$field) = @_;
1233 my($table)=$self->table;
1235 croak "Unique called on field $field, but it is ",
1236 $self->getfield($field),
1238 if $self->getfield($field);
1240 #warn "table $table is tainted" if is_tainted($table);
1241 #warn "field $field is tainted" if is_tainted($field);
1243 my($counter) = new File::CounterFile "$table.$field",0;
1245 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1247 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1250 my $index = $counter->inc;
1251 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1253 $index =~ /^(\d*)$/;
1256 $self->setfield($field,$index);
1260 =item ut_float COLUMN
1262 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1263 null. If there is an error, returns the error, otherwise returns false.
1268 my($self,$field)=@_ ;
1269 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1270 $self->getfield($field) =~ /^(\d+)$/ ||
1271 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1272 $self->getfield($field) =~ /^(\d+e\d+)$/)
1273 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1274 $self->setfield($field,$1);
1278 =item ut_snumber COLUMN
1280 Check/untaint signed numeric data (whole numbers). May not be null. If there
1281 is an error, returns the error, otherwise returns false.
1286 my($self, $field) = @_;
1287 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1288 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1289 $self->setfield($field, "$1$2");
1293 =item ut_snumbern COLUMN
1295 Check/untaint signed numeric data (whole numbers). If there is an error,
1296 returns the error, otherwise returns false.
1301 my($self, $field) = @_;
1302 $self->getfield($field) =~ /^(-?)\s*(\d*)$/
1303 or return "Illegal (numeric) $field: ". $self->getfield($field);
1305 return "Illegal (numeric) $field: ". $self->getfield($field)
1308 $self->setfield($field, "$1$2");
1312 =item ut_number COLUMN
1314 Check/untaint simple numeric data (whole numbers). May not be null. If there
1315 is an error, returns the error, otherwise returns false.
1320 my($self,$field)=@_;
1321 $self->getfield($field) =~ /^(\d+)$/
1322 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1323 $self->setfield($field,$1);
1327 =item ut_numbern COLUMN
1329 Check/untaint simple numeric data (whole numbers). May be null. If there is
1330 an error, returns the error, otherwise returns false.
1335 my($self,$field)=@_;
1336 $self->getfield($field) =~ /^(\d*)$/
1337 or return "Illegal (numeric) $field: ". $self->getfield($field);
1338 $self->setfield($field,$1);
1342 =item ut_money COLUMN
1344 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1345 is an error, returns the error, otherwise returns false.
1350 my($self,$field)=@_;
1351 $self->setfield($field, 0) if $self->getfield($field) eq '';
1352 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1353 or return "Illegal (money) $field: ". $self->getfield($field);
1354 #$self->setfield($field, "$1$2$3" || 0);
1355 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1359 =item ut_text COLUMN
1361 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1362 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1363 May not be null. If there is an error, returns the error, otherwise returns
1369 my($self,$field)=@_;
1370 #warn "msgcat ". \&msgcat. "\n";
1371 #warn "notexist ". \¬exist. "\n";
1372 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1373 $self->getfield($field)
1374 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1375 or return gettext('illegal_or_empty_text'). " $field: ".
1376 $self->getfield($field);
1377 $self->setfield($field,$1);
1381 =item ut_textn COLUMN
1383 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1384 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1385 May be null. If there is an error, returns the error, otherwise returns false.
1390 my($self,$field)=@_;
1391 $self->getfield($field)
1392 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1393 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1394 $self->setfield($field,$1);
1398 =item ut_alpha COLUMN
1400 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1401 an error, returns the error, otherwise returns false.
1406 my($self,$field)=@_;
1407 $self->getfield($field) =~ /^(\w+)$/
1408 or return "Illegal or empty (alphanumeric) $field: ".
1409 $self->getfield($field);
1410 $self->setfield($field,$1);
1414 =item ut_alpha COLUMN
1416 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1417 error, returns the error, otherwise returns false.
1422 my($self,$field)=@_;
1423 $self->getfield($field) =~ /^(\w*)$/
1424 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1425 $self->setfield($field,$1);
1429 =item ut_phonen COLUMN [ COUNTRY ]
1431 Check/untaint phone numbers. May be null. If there is an error, returns
1432 the error, otherwise returns false.
1434 Takes an optional two-letter ISO country code; without it or with unsupported
1435 countries, ut_phonen simply calls ut_alphan.
1440 my( $self, $field, $country ) = @_;
1441 return $self->ut_alphan($field) unless defined $country;
1442 my $phonen = $self->getfield($field);
1443 if ( $phonen eq '' ) {
1444 $self->setfield($field,'');
1445 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1447 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1448 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1449 $phonen = "$1-$2-$3";
1450 $phonen .= " x$4" if $4;
1451 $self->setfield($field,$phonen);
1453 warn "warning: don't know how to check phone numbers for country $country";
1454 return $self->ut_textn($field);
1461 Check/untaint ip addresses. IPv4 only for now.
1466 my( $self, $field ) = @_;
1467 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1468 or return "Illegal (IP address) $field: ". $self->getfield($field);
1469 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1470 $self->setfield($field, "$1.$2.$3.$4");
1476 Check/untaint ip addresses. IPv4 only for now. May be null.
1481 my( $self, $field ) = @_;
1482 if ( $self->getfield($field) =~ /^()$/ ) {
1483 $self->setfield($field,'');
1486 $self->ut_ip($field);
1490 =item ut_domain COLUMN
1492 Check/untaint host and domain names.
1497 my( $self, $field ) = @_;
1498 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1499 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1500 or return "Illegal (domain) $field: ". $self->getfield($field);
1501 $self->setfield($field,$1);
1505 =item ut_name COLUMN
1507 Check/untaint proper names; allows alphanumerics, spaces and the following
1508 punctuation: , . - '
1515 my( $self, $field ) = @_;
1516 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1517 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1518 $self->setfield($field,$1);
1524 Check/untaint zip codes.
1528 my @zip_reqd_countries = qw( CA ); #US implicit...
1531 my( $self, $field, $country ) = @_;
1533 if ( $country eq 'US' ) {
1535 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1536 or return gettext('illegal_zip'). " $field for country $country: ".
1537 $self->getfield($field);
1538 $self->setfield($field, $1);
1540 } elsif ( $country eq 'CA' ) {
1542 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1543 or return gettext('illegal_zip'). " $field for country $country: ".
1544 $self->getfield($field);
1545 $self->setfield($field, "$1 $2");
1549 if ( $self->getfield($field) =~ /^\s*$/
1550 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1553 $self->setfield($field,'');
1555 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1556 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1557 $self->setfield($field,$1);
1565 =item ut_country COLUMN
1567 Check/untaint country codes. Country names are changed to codes, if possible -
1568 see L<Locale::Country>.
1573 my( $self, $field ) = @_;
1574 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1575 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1576 && country2code($1) ) {
1577 $self->setfield($field,uc(country2code($1)));
1580 $self->getfield($field) =~ /^(\w\w)$/
1581 or return "Illegal (country) $field: ". $self->getfield($field);
1582 $self->setfield($field,uc($1));
1586 =item ut_anything COLUMN
1588 Untaints arbitrary data. Be careful.
1593 my( $self, $field ) = @_;
1594 $self->getfield($field) =~ /^(.*)$/s
1595 or return "Illegal $field: ". $self->getfield($field);
1596 $self->setfield($field,$1);
1600 =item ut_enum COLUMN CHOICES_ARRAYREF
1602 Check/untaint a column, supplying all possible choices, like the "enum" type.
1607 my( $self, $field, $choices ) = @_;
1608 foreach my $choice ( @$choices ) {
1609 if ( $self->getfield($field) eq $choice ) {
1610 $self->setfield($choice);
1614 return "Illegal (enum) field $field: ". $self->getfield($field);
1617 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1619 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1620 on the column first.
1624 sub ut_foreign_key {
1625 my( $self, $field, $table, $foreign ) = @_;
1626 qsearchs($table, { $foreign => $self->getfield($field) })
1627 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1628 " in $table.$foreign";
1632 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1634 Like ut_foreign_key, except the null value is also allowed.
1638 sub ut_foreign_keyn {
1639 my( $self, $field, $table, $foreign ) = @_;
1640 $self->getfield($field)
1641 ? $self->ut_foreign_key($field, $table, $foreign)
1645 =item ut_agentnum_acl
1647 Checks this column as an agentnum, taking into account the current users's
1652 sub ut_agentnum_acl {
1653 my( $self, $field, $null_acl ) = @_;
1655 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1656 return "Illegal agentnum: $error" if $error;
1658 my $curuser = $FS::CurrentUser::CurrentUser;
1660 if ( $self->$field() ) {
1662 return "Access deined"
1663 unless $curuser->agentnum($self->$field());
1667 return "Access denied"
1668 unless $curuser->access_right($null_acl);
1676 =item virtual_fields [ TABLE ]
1678 Returns a list of virtual fields defined for the table. This should not
1679 be exported, and should only be called as an instance or class method.
1683 sub virtual_fields {
1686 $table = $self->table or confess "virtual_fields called on non-table";
1688 confess "Unknown table $table" unless dbdef->table($table);
1690 return () unless dbdef->table('part_virtual_field');
1692 unless ( $virtual_fields_cache{$table} ) {
1693 my $query = 'SELECT name from part_virtual_field ' .
1694 "WHERE dbtable = '$table'";
1696 my $result = $dbh->selectcol_arrayref($query);
1697 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1699 $virtual_fields_cache{$table} = $result;
1702 @{$virtual_fields_cache{$table}};
1707 =item fields [ TABLE ]
1709 This is a wrapper for real_fields and virtual_fields. Code that called
1710 fields before should probably continue to call fields.
1715 my $something = shift;
1717 if($something->isa('FS::Record')) {
1718 $table = $something->table;
1720 $table = $something;
1721 $something = "FS::$table";
1723 return (real_fields($table), $something->virtual_fields());
1728 =item pvf FIELD_NAME
1730 Returns the FS::part_virtual_field object corresponding to a field in the
1731 record (specified by FIELD_NAME).
1736 my ($self, $name) = (shift, shift);
1738 if(grep /^$name$/, $self->virtual_fields) {
1739 return qsearchs('part_virtual_field', { dbtable => $self->table,
1749 =item real_fields [ TABLE ]
1751 Returns a list of the real columns in the specified table. Called only by
1752 fields() and other subroutines elsewhere in FS::Record.
1759 my($table_obj) = dbdef->table($table);
1760 confess "Unknown table $table" unless $table_obj;
1761 $table_obj->columns;
1764 =item _quote VALUE, TABLE, COLUMN
1766 This is an internal function used to construct SQL statements. It returns
1767 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1768 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1773 my($value, $table, $column) = @_;
1774 my $column_obj = dbdef->table($table)->column($column);
1775 my $column_type = $column_obj->type;
1776 my $nullable = $column_obj->null;
1778 warn " $table.$column: $value ($column_type".
1779 ( $nullable ? ' NULL' : ' NOT NULL' ).
1780 ")\n" if $DEBUG > 2;
1782 if ( $value eq '' && $nullable ) {
1784 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
1785 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1788 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1789 ! $column_type =~ /(char|binary|text)$/i ) {
1796 =item vfieldpart_hashref TABLE
1798 Returns a hashref of virtual field names and vfieldparts applicable to the given
1803 sub vfieldpart_hashref {
1805 my $table = $self->table;
1807 return {} unless dbdef->table('part_virtual_field');
1810 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1811 "dbtable = '$table'";
1812 my $sth = $dbh->prepare($statement);
1813 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1814 return { map { $_->{name}, $_->{vfieldpart} }
1815 @{$sth->fetchall_arrayref({})} };
1822 This is deprecated. Don't use it.
1824 It returns a hash-type list with the fields of this record's table set true.
1829 carp "warning: hfields is deprecated";
1832 foreach (fields($table)) {
1841 "$_: ". $self->getfield($_). "|"
1842 } (fields($self->table)) );
1846 my ($self, $value) = @_;
1849 my $conf = new FS::Conf;
1850 if ($conf->exists('encryption')) {
1851 if ($self->is_encrypted($value)) {
1852 # Return the original value if it isn't plaintext.
1853 $encrypted = $value;
1856 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1857 # RSA doesn't like the empty string so let's pack it up
1858 # The database doesn't like the RSA data so uuencode it
1859 my $length = length($value)+1;
1860 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1862 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1870 my ($self, $value) = @_;
1871 # Possible Bug - Some work may be required here....
1873 if (length($value) > 80) {
1881 my ($self,$value) = @_;
1882 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1883 my $conf = new FS::Conf;
1884 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1886 if (ref($rsa_decrypt) =~ /::RSA/) {
1887 my $encrypted = unpack ("u*", $value);
1888 $decrypted = unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1896 #Initialize the Module
1897 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1899 my $conf = new FS::Conf;
1900 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1901 $rsa_module = $conf->config('encryptionmodule');
1905 eval ("require $rsa_module"); # No need to import the namespace
1908 # Initialize Encryption
1909 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1910 my $public_key = join("\n",$conf->config('encryptionpublickey'));
1911 $rsa_encrypt = $rsa_module->new_public_key($public_key);
1914 # Intitalize Decryption
1915 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1916 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1917 $rsa_decrypt = $rsa_module->new_private_key($private_key);
1921 sub DESTROY { return; }
1925 # #use Carp qw(cluck);
1926 # #cluck "DESTROYING $self";
1927 # warn "DESTROYING $self";
1931 # return ! eval { join('',@_), kill 0; 1; };
1938 This module should probably be renamed, since much of the functionality is
1939 of general use. It is not completely unlike Adapter::DBI (see below).
1941 Exported qsearch and qsearchs should be deprecated in favor of method calls
1942 (against an FS::Record object like the old search and searchs that qsearch
1943 and qsearchs were on top of.)
1945 The whole fields / hfields mess should be removed.
1947 The various WHERE clauses should be subroutined.
1949 table string should be deprecated in favor of DBIx::DBSchema::Table.
1951 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1952 true maps to the database (and WHERE clauses) would also help.
1954 The ut_ methods should ask the dbdef for a default length.
1956 ut_sqltype (like ut_varchar) should all be defined
1958 A fallback check method should be provided which uses the dbdef.
1960 The ut_money method assumes money has two decimal digits.
1962 The Pg money kludge in the new method only strips `$'.
1964 The ut_phonen method only checks US-style phone numbers.
1966 The _quote function should probably use ut_float instead of a regex.
1968 All the subroutines probably should be methods, here or elsewhere.
1970 Probably should borrow/use some dbdef methods where appropriate (like sub
1973 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1974 or allow it to be set. Working around it is ugly any way around - DBI should
1975 be fixed. (only affects RDBMS which return uppercase column names)
1977 ut_zip should take an optional country like ut_phone.
1981 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1983 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.