4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 %virtual_fields_cache $nowarn_identical $no_update_diff );
8 use Carp qw(carp cluck croak confess);
9 use Scalar::Util qw( blessed );
10 use File::CounterFile;
12 use DBI qw(:sql_types);
13 use DBIx::DBSchema 0.33;
14 use FS::UID qw(dbh getotaker datasrc driver_name);
16 use FS::Schema qw(dbdef);
18 use FS::Msgcat qw(gettext);
19 #use FS::Conf; #dependency loop bs, in install_callback below instead
21 use FS::part_virtual_field;
27 #export dbdef for now... everything else expects to find it here
28 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
29 str2time_sql str2time_sql_closing );
34 $nowarn_identical = 0;
42 FS::UID->install_callback( sub {
46 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
52 FS::Record - Database record objects
57 use FS::Record qw(dbh fields qsearch qsearchs);
59 $record = new FS::Record 'table', \%hash;
60 $record = new FS::Record 'table', { 'column' => 'value', ... };
62 $record = qsearchs FS::Record 'table', \%hash;
63 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
64 @records = qsearch FS::Record 'table', \%hash;
65 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
67 $table = $record->table;
68 $dbdef_table = $record->dbdef_table;
70 $value = $record->get('column');
71 $value = $record->getfield('column');
72 $value = $record->column;
74 $record->set( 'column' => 'value' );
75 $record->setfield( 'column' => 'value' );
76 $record->column('value');
78 %hash = $record->hash;
80 $hashref = $record->hashref;
82 $error = $record->insert;
84 $error = $record->delete;
86 $error = $new_record->replace($old_record);
88 # external use deprecated - handled by the database (at least for Pg, mysql)
89 $value = $record->unique('column');
91 $error = $record->ut_float('column');
92 $error = $record->ut_floatn('column');
93 $error = $record->ut_number('column');
94 $error = $record->ut_numbern('column');
95 $error = $record->ut_snumber('column');
96 $error = $record->ut_snumbern('column');
97 $error = $record->ut_money('column');
98 $error = $record->ut_text('column');
99 $error = $record->ut_textn('column');
100 $error = $record->ut_alpha('column');
101 $error = $record->ut_alphan('column');
102 $error = $record->ut_phonen('column');
103 $error = $record->ut_anything('column');
104 $error = $record->ut_name('column');
106 $quoted_value = _quote($value,'table','field');
109 $fields = hfields('table');
110 if ( $fields->{Field} ) { # etc.
112 @fields = fields 'table'; #as a subroutine
113 @fields = $record->fields; #as a method call
118 (Mostly) object-oriented interface to database records. Records are currently
119 implemented on top of DBI. FS::Record is intended as a base class for
120 table-specific classes to inherit from, i.e. FS::cust_main.
126 =item new [ TABLE, ] HASHREF
128 Creates a new record. It doesn't store it in the database, though. See
129 L<"insert"> for that.
131 Note that the object stores this hash reference, not a distinct copy of the
132 hash it points to. You can ask the object for a copy with the I<hash>
135 TABLE can only be omitted when a dervived class overrides the table method.
141 my $class = ref($proto) || $proto;
143 bless ($self, $class);
145 unless ( defined ( $self->table ) ) {
146 $self->{'Table'} = shift;
147 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
150 $self->{'Hash'} = shift;
152 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
153 $self->{'Hash'}{$field}='';
156 $self->_rebless if $self->can('_rebless');
158 $self->{'modified'} = 0;
160 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
167 my $class = ref($proto) || $proto;
169 bless ($self, $class);
171 $self->{'Table'} = shift unless defined ( $self->table );
173 my $hashref = $self->{'Hash'} = shift;
175 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
176 my $obj = $cache->cache->{$hashref->{$cache->key}};
177 $obj->_cache($hashref, $cache) if $obj->can('_cache');
180 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
187 my $class = ref($proto) || $proto;
189 bless ($self, $class);
190 if ( defined $self->table ) {
191 cluck "create constructor is deprecated, use new!";
194 croak "FS::Record::create called (not from a subclass)!";
198 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
200 Searches the database for all records matching (at least) the key/value pairs
201 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
202 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
205 The preferred usage is to pass a hash reference of named parameters:
207 my @records = qsearch( {
208 'table' => 'table_name',
209 'hashref' => { 'field' => 'value'
210 'field' => { 'op' => '<',
215 #these are optional...
217 'extra_sql' => 'AND field ',
218 'order_by' => 'ORDER BY something',
219 #'cache_obj' => '', #optional
220 'addl_from' => 'LEFT JOIN othtable USING ( field )',
225 Much code still uses old-style positional parameters, this is also probably
226 fine in the common case where there are only two parameters:
228 my @records = qsearch( 'table', { 'field' => 'value' } );
230 ###oops, argh, FS::Record::new only lets us create database fields.
231 #Normal behaviour if SELECT is not specified is `*', as in
232 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
233 #feature where you can specify SELECT - remember, the objects returned,
234 #although blessed into the appropriate `FS::TABLE' package, will only have the
235 #fields you specify. This might have unwanted results if you then go calling
236 #regular FS::TABLE methods
242 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
244 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
246 $stable = $opt->{'table'} or die "table name is required";
247 $record = $opt->{'hashref'} || {};
248 $select = $opt->{'select'} || '*';
249 $extra_sql = $opt->{'extra_sql'} || '';
250 $order_by = $opt->{'order_by'} || '';
251 $cache = $opt->{'cache_obj'} || '';
252 $addl_from = $opt->{'addl_from'} || '';
253 $debug = $opt->{'debug'} || '';
255 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
259 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
261 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
265 my $table = $cache ? $cache->table : $stable;
266 my $dbdef_table = dbdef->table($table)
267 or die "No schema for table $table found - ".
268 "do you need to run freeside-upgrade?";
269 my $pkey = $dbdef_table->primary_key;
271 my @real_fields = grep exists($record->{$_}), real_fields($table);
273 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
274 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
276 cluck "warning: FS::$table not loaded; virtual fields not searchable";
277 @virtual_fields = ();
280 my $statement = "SELECT $select FROM $stable";
281 $statement .= " $addl_from" if $addl_from;
282 if ( @real_fields or @virtual_fields ) {
283 $statement .= ' WHERE '. join(' AND ',
284 get_real_fields($table, $record, \@real_fields) ,
285 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
289 $statement .= " $extra_sql" if defined($extra_sql);
290 $statement .= " $order_by" if defined($order_by);
292 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
293 my $sth = $dbh->prepare($statement)
294 or croak "$dbh->errstr doing $statement";
299 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
301 my $value = $record->{$field};
302 $value = $value->{'value'} if ref($value);
303 my $type = dbdef->table($table)->column($field)->type;
304 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
305 $sth->bind_param($bind++, $value, { TYPE => SQL_INTEGER } );
306 } elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
307 || ( $type =~ /(real|float4)/i
308 && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
311 $sth->bind_param($bind++, $value, { TYPE => SQL_FLOAT } );
313 $sth->bind_param($bind++, $value, { TYPE => SQL_VARCHAR } );
317 # $sth->execute( map $record->{$_},
318 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
319 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
321 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
323 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
324 @virtual_fields = "FS::$table"->virtual_fields;
326 cluck "warning: FS::$table not loaded; virtual fields not returned either";
327 @virtual_fields = ();
331 tie %result, "Tie::IxHash";
332 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
333 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
334 %result = map { $_->{$pkey}, $_ } @stuff;
336 @result{@stuff} = @stuff;
341 if ( keys(%result) and @virtual_fields ) {
343 "SELECT virtual_field.recnum, part_virtual_field.name, ".
344 "virtual_field.value ".
345 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
346 "WHERE part_virtual_field.dbtable = '$table' AND ".
347 "virtual_field.recnum IN (".
348 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
349 join(q!', '!, @virtual_fields) . "')";
350 warn "[debug]$me $statement\n" if $DEBUG > 1;
351 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
352 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
354 foreach (@{ $sth->fetchall_arrayref({}) }) {
355 my $recnum = $_->{recnum};
356 my $name = $_->{name};
357 my $value = $_->{value};
358 if (exists($result{$recnum})) {
359 $result{$recnum}->{$name} = $value;
364 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
365 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
366 #derivied class didn't override new method, so this optimization is safe
369 new_or_cached( "FS::$table", { %{$_} }, $cache )
373 new( "FS::$table", { %{$_} } )
377 #okay, its been tested
378 # warn "untested code (class FS::$table uses custom new method)";
380 eval 'FS::'. $table. '->new( { %{$_} } )';
384 # Check for encrypted fields and decrypt them.
385 ## only in the local copy, not the cached object
386 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
387 # the initial search for
389 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
390 foreach my $record (@return) {
391 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
392 # Set it directly... This may cause a problem in the future...
393 $record->setfield($field, $record->decrypt($record->getfield($field)));
398 cluck "warning: FS::$table not loaded; returning FS::Record objects";
400 FS::Record->new( $table, { %{$_} } );
406 ## makes this easier to read
408 sub get_virtual_fields {
412 my $virtual_fields = shift;
418 if ( ref($record->{$_}) ) {
419 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
420 if ( uc($op) eq 'ILIKE' ) {
422 $record->{$_}{'value'} = lc($record->{$_}{'value'});
423 $column = "LOWER($_)";
425 $record->{$_} = $record->{$_}{'value'};
428 # ... EXISTS ( SELECT name, value FROM part_virtual_field
430 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
431 # WHERE recnum = svc_acct.svcnum
432 # AND (name, value) = ('egad', 'brain') )
434 my $value = $record->{$_};
438 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
439 "( SELECT part_virtual_field.name, virtual_field.value ".
440 "FROM part_virtual_field JOIN virtual_field ".
441 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
442 "WHERE virtual_field.recnum = ${table}.${pkey} ".
443 "AND part_virtual_field.name = '${column}'".
445 " AND virtual_field.value ${op} '${value}'"
449 } @{ $virtual_fields } ) ;
452 sub get_real_fields {
455 my $real_fields = shift;
457 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
463 if ( ref($record->{$_}) ) {
464 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
465 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
466 if ( uc($op) eq 'ILIKE' ) {
468 $record->{$_}{'value'} = lc($record->{$_}{'value'});
469 $column = "LOWER($_)";
471 $record->{$_} = $record->{$_}{'value'}
474 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
476 if ( driver_name eq 'Pg' ) {
477 my $type = dbdef->table($table)->column($column)->type;
478 if ( $type =~ /(int|(big)?serial)/i ) {
479 qq-( $column IS NULL )-;
481 qq-( $column IS NULL OR $column = '' )-;
484 qq-( $column IS NULL OR $column = "" )-;
486 } elsif ( $op eq '!=' ) {
487 if ( driver_name eq 'Pg' ) {
488 my $type = dbdef->table($table)->column($column)->type;
489 if ( $type =~ /(int|(big)?serial)/i ) {
490 qq-( $column IS NOT NULL )-;
492 qq-( $column IS NOT NULL AND $column != '' )-;
495 qq-( $column IS NOT NULL AND $column != "" )-;
498 if ( driver_name eq 'Pg' ) {
499 qq-( $column $op '' )-;
501 qq-( $column $op "" )-;
507 } @{ $real_fields } );
510 =item by_key PRIMARY_KEY_VALUE
512 This is a class method that returns the record with the given primary key
513 value. This method is only useful in FS::Record subclasses. For example:
515 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
519 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
524 my ($class, $pkey_value) = @_;
526 my $table = $class->table
527 or croak "No table for $class found";
529 my $dbdef_table = dbdef->table($table)
530 or die "No schema for table $table found - ".
531 "do you need to create it or run dbdef-create?";
532 my $pkey = $dbdef_table->primary_key
533 or die "No primary key for table $table";
535 return qsearchs($table, { $pkey => $pkey_value });
538 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
540 Experimental JOINed search method. Using this method, you can execute a
541 single SELECT spanning multiple tables, and cache the results for subsequent
542 method calls. Interface will almost definately change in an incompatible
550 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
551 my $cache = FS::SearchCache->new( $ptable, $pkey );
554 grep { !$saw{$_->getfield($pkey)}++ }
555 qsearch($table, $record, $select, $extra_sql, $cache )
559 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
561 Same as qsearch, except that if more than one record matches, it B<carp>s but
562 returns the first. If this happens, you either made a logic error in asking
563 for a single item, or your data is corrupted.
567 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
569 my(@result) = qsearch(@_);
570 cluck "warning: Multiple records in scalar search ($table)"
571 if scalar(@result) > 1;
572 #should warn more vehemently if the search was on a primary key?
573 scalar(@result) ? ($result[0]) : ();
584 Returns the table name.
589 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
596 Returns the DBIx::DBSchema::Table object for the table.
602 my($table)=$self->table;
603 dbdef->table($table);
608 Returns the primary key for the table.
614 my $pkey = $self->dbdef_table->primary_key;
617 =item get, getfield COLUMN
619 Returns the value of the column/field/key COLUMN.
624 my($self,$field) = @_;
625 # to avoid "Use of unitialized value" errors
626 if ( defined ( $self->{Hash}->{$field} ) ) {
627 $self->{Hash}->{$field};
637 =item set, setfield COLUMN, VALUE
639 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
644 my($self,$field,$value) = @_;
645 $self->{'modified'} = 1;
646 $self->{'Hash'}->{$field} = $value;
653 =item AUTLOADED METHODS
655 $record->column is a synonym for $record->get('column');
657 $record->column('value') is a synonym for $record->set('column','value');
664 my($field)=$AUTOLOAD;
666 if ( defined($value) ) {
667 confess "errant AUTOLOAD $field for $self (arg $value)"
668 unless blessed($self) && $self->can('setfield');
669 $self->setfield($field,$value);
671 confess "errant AUTOLOAD $field for $self (no args)"
672 unless blessed($self) && $self->can('getfield');
673 $self->getfield($field);
679 # my $field = $AUTOLOAD;
681 # if ( defined($_[1]) ) {
682 # $_[0]->setfield($field, $_[1]);
684 # $_[0]->getfield($field);
690 Returns a list of the column/value pairs, usually for assigning to a new hash.
692 To make a distinct duplicate of an FS::Record object, you can do:
694 $new = new FS::Record ( $old->table, { $old->hash } );
700 confess $self. ' -> hash: Hash attribute is undefined'
701 unless defined($self->{'Hash'});
702 %{ $self->{'Hash'} };
707 Returns a reference to the column/value hash. This may be deprecated in the
708 future; if there's a reason you can't just use the autoloaded or get/set
720 Returns true if any of this object's values have been modified with set (or via
721 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
731 =item select_for_update
733 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
738 sub select_for_update {
740 my $primary_key = $self->primary_key;
743 'table' => $self->table,
744 'hashref' => { $primary_key => $self->$primary_key() },
745 'extra_sql' => 'FOR UPDATE',
751 Inserts this record to the database. If there is an error, returns the error,
752 otherwise returns false.
760 warn "$self -> insert" if $DEBUG;
762 my $error = $self->check;
763 return $error if $error;
765 #single-field unique keys are given a value if false
766 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
767 foreach ( $self->dbdef_table->unique_singles) {
768 $self->unique($_) unless $self->getfield($_);
771 #and also the primary key, if the database isn't going to
772 my $primary_key = $self->dbdef_table->primary_key;
774 if ( $primary_key ) {
775 my $col = $self->dbdef_table->column($primary_key);
778 uc($col->type) =~ /^(BIG)?SERIAL\d?/
779 || ( driver_name eq 'Pg'
780 && defined($col->default)
781 && $col->default =~ /^nextval\(/i
783 || ( driver_name eq 'mysql'
784 && defined($col->local)
785 && $col->local =~ /AUTO_INCREMENT/i
787 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
790 my $table = $self->table;
793 # Encrypt before the database
794 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
795 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
796 $self->{'saved'} = $self->getfield($field);
797 $self->setfield($field, $self->encrypt($self->getfield($field)));
802 #false laziness w/delete
804 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
807 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
810 my $statement = "INSERT INTO $table ";
811 if ( @real_fields ) {
814 join( ', ', @real_fields ).
816 join( ', ', @values ).
820 $statement .= 'DEFAULT VALUES';
822 warn "[debug]$me $statement\n" if $DEBUG > 1;
823 my $sth = dbh->prepare($statement) or return dbh->errstr;
825 local $SIG{HUP} = 'IGNORE';
826 local $SIG{INT} = 'IGNORE';
827 local $SIG{QUIT} = 'IGNORE';
828 local $SIG{TERM} = 'IGNORE';
829 local $SIG{TSTP} = 'IGNORE';
830 local $SIG{PIPE} = 'IGNORE';
832 $sth->execute or return $sth->errstr;
834 # get inserted id from the database, if applicable & needed
835 if ( $db_seq && ! $self->getfield($primary_key) ) {
836 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
840 if ( driver_name eq 'Pg' ) {
842 #my $oid = $sth->{'pg_oid_status'};
843 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
845 my $default = $self->dbdef_table->column($primary_key)->default;
846 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
847 dbh->rollback if $FS::UID::AutoCommit;
848 return "can't parse $table.$primary_key default value".
849 " for sequence name: $default";
853 my $i_sql = "SELECT currval('$sequence')";
854 my $i_sth = dbh->prepare($i_sql) or do {
855 dbh->rollback if $FS::UID::AutoCommit;
858 $i_sth->execute() or do { #$i_sth->execute($oid)
859 dbh->rollback if $FS::UID::AutoCommit;
860 return $i_sth->errstr;
862 $insertid = $i_sth->fetchrow_arrayref->[0];
864 } elsif ( driver_name eq 'mysql' ) {
866 $insertid = dbh->{'mysql_insertid'};
867 # work around mysql_insertid being null some of the time, ala RT :/
868 unless ( $insertid ) {
869 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
870 "using SELECT LAST_INSERT_ID();";
871 my $i_sql = "SELECT LAST_INSERT_ID()";
872 my $i_sth = dbh->prepare($i_sql) or do {
873 dbh->rollback if $FS::UID::AutoCommit;
876 $i_sth->execute or do {
877 dbh->rollback if $FS::UID::AutoCommit;
878 return $i_sth->errstr;
880 $insertid = $i_sth->fetchrow_arrayref->[0];
885 dbh->rollback if $FS::UID::AutoCommit;
886 return "don't know how to retreive inserted ids from ". driver_name.
887 ", try using counterfiles (maybe run dbdef-create?)";
891 $self->setfield($primary_key, $insertid);
896 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
897 $self->virtual_fields;
898 if (@virtual_fields) {
899 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
901 my $vfieldpart = $self->vfieldpart_hashref;
903 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
906 my $v_sth = dbh->prepare($v_statement) or do {
907 dbh->rollback if $FS::UID::AutoCommit;
911 foreach (keys(%v_values)) {
912 $v_sth->execute($self->getfield($primary_key),
916 dbh->rollback if $FS::UID::AutoCommit;
917 return $v_sth->errstr;
924 if ( defined dbdef->table('h_'. $table) ) {
925 my $h_statement = $self->_h_statement('insert');
926 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
927 $h_sth = dbh->prepare($h_statement) or do {
928 dbh->rollback if $FS::UID::AutoCommit;
934 $h_sth->execute or return $h_sth->errstr if $h_sth;
936 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
938 # Now that it has been saved, reset the encrypted fields so that $new
940 foreach my $field (keys %{$saved}) {
941 $self->setfield($field, $saved->{$field});
949 Depriciated (use insert instead).
954 cluck "warning: FS::Record::add deprecated!";
955 insert @_; #call method in this scope
960 Delete this record from the database. If there is an error, returns the error,
961 otherwise returns false.
968 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
970 $self->getfield($_) eq ''
971 #? "( $_ IS NULL OR $_ = \"\" )"
972 ? ( driver_name eq 'Pg'
974 : "( $_ IS NULL OR $_ = \"\" )"
976 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
977 } ( $self->dbdef_table->primary_key )
978 ? ( $self->dbdef_table->primary_key)
979 : real_fields($self->table)
981 warn "[debug]$me $statement\n" if $DEBUG > 1;
982 my $sth = dbh->prepare($statement) or return dbh->errstr;
985 if ( defined dbdef->table('h_'. $self->table) ) {
986 my $h_statement = $self->_h_statement('delete');
987 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
988 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
993 my $primary_key = $self->dbdef_table->primary_key;
996 my $vfp = $self->vfieldpart_hashref;
997 foreach($self->virtual_fields) {
998 next if $self->getfield($_) eq '';
999 unless(@del_vfields) {
1000 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1001 $v_sth = dbh->prepare($st) or return dbh->errstr;
1003 push @del_vfields, $_;
1006 local $SIG{HUP} = 'IGNORE';
1007 local $SIG{INT} = 'IGNORE';
1008 local $SIG{QUIT} = 'IGNORE';
1009 local $SIG{TERM} = 'IGNORE';
1010 local $SIG{TSTP} = 'IGNORE';
1011 local $SIG{PIPE} = 'IGNORE';
1013 my $rc = $sth->execute or return $sth->errstr;
1014 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1015 $h_sth->execute or return $h_sth->errstr if $h_sth;
1016 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1017 or return $v_sth->errstr
1018 foreach (@del_vfields);
1020 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1022 #no need to needlessly destoy the data either (causes problems actually)
1023 #undef $self; #no need to keep object!
1030 Depriciated (use delete instead).
1035 cluck "warning: FS::Record::del deprecated!";
1036 &delete(@_); #call method in this scope
1039 =item replace OLD_RECORD
1041 Replace the OLD_RECORD with this one in the database. If there is an error,
1042 returns the error, otherwise returns false.
1047 my ($new, $old) = (shift, shift);
1049 $old = $new->replace_old unless defined($old);
1051 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1053 if ( $new->can('replace_check') ) {
1054 my $error = $new->replace_check($old);
1055 return $error if $error;
1058 return "Records not in same table!" unless $new->table eq $old->table;
1060 my $primary_key = $old->dbdef_table->primary_key;
1061 return "Can't change primary key $primary_key ".
1062 'from '. $old->getfield($primary_key).
1063 ' to ' . $new->getfield($primary_key)
1065 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1067 my $error = $new->check;
1068 return $error if $error;
1070 # Encrypt for replace
1072 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1073 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1074 $saved->{$field} = $new->getfield($field);
1075 $new->setfield($field, $new->encrypt($new->getfield($field)));
1079 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1080 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1081 ? ($_, $new->getfield($_)) : () } $old->fields;
1083 unless (keys(%diff) || $no_update_diff ) {
1084 carp "[warning]$me $new -> replace $old: records identical"
1085 unless $nowarn_identical;
1089 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1091 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1092 } real_fields($old->table)
1097 if ( $old->getfield($_) eq '' ) {
1099 #false laziness w/qsearch
1100 if ( driver_name eq 'Pg' ) {
1101 my $type = $old->dbdef_table->column($_)->type;
1102 if ( $type =~ /(int|(big)?serial)/i ) {
1105 qq-( $_ IS NULL OR $_ = '' )-;
1108 qq-( $_ IS NULL OR $_ = "" )-;
1112 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1115 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1118 warn "[debug]$me $statement\n" if $DEBUG > 1;
1119 my $sth = dbh->prepare($statement) or return dbh->errstr;
1122 if ( defined dbdef->table('h_'. $old->table) ) {
1123 my $h_old_statement = $old->_h_statement('replace_old');
1124 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1125 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1131 if ( defined dbdef->table('h_'. $new->table) ) {
1132 my $h_new_statement = $new->_h_statement('replace_new');
1133 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1134 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1139 # For virtual fields we have three cases with different SQL
1140 # statements: add, replace, delete
1144 my (@add_vfields, @rep_vfields, @del_vfields);
1145 my $vfp = $old->vfieldpart_hashref;
1146 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1147 if($diff{$_} eq '') {
1149 unless(@del_vfields) {
1150 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1151 "AND vfieldpart = ?";
1152 warn "[debug]$me $st\n" if $DEBUG > 2;
1153 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1155 push @del_vfields, $_;
1156 } elsif($old->getfield($_) eq '') {
1158 unless(@add_vfields) {
1159 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1161 warn "[debug]$me $st\n" if $DEBUG > 2;
1162 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1164 push @add_vfields, $_;
1167 unless(@rep_vfields) {
1168 my $st = "UPDATE virtual_field SET value = ? ".
1169 "WHERE recnum = ? AND vfieldpart = ?";
1170 warn "[debug]$me $st\n" if $DEBUG > 2;
1171 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1173 push @rep_vfields, $_;
1177 local $SIG{HUP} = 'IGNORE';
1178 local $SIG{INT} = 'IGNORE';
1179 local $SIG{QUIT} = 'IGNORE';
1180 local $SIG{TERM} = 'IGNORE';
1181 local $SIG{TSTP} = 'IGNORE';
1182 local $SIG{PIPE} = 'IGNORE';
1184 my $rc = $sth->execute or return $sth->errstr;
1185 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1186 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1187 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1189 $v_del_sth->execute($old->getfield($primary_key),
1191 or return $v_del_sth->errstr
1192 foreach(@del_vfields);
1194 $v_add_sth->execute($new->getfield($_),
1195 $old->getfield($primary_key),
1197 or return $v_add_sth->errstr
1198 foreach(@add_vfields);
1200 $v_rep_sth->execute($new->getfield($_),
1201 $old->getfield($primary_key),
1203 or return $v_rep_sth->errstr
1204 foreach(@rep_vfields);
1206 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1208 # Now that it has been saved, reset the encrypted fields so that $new
1209 # can still be used.
1210 foreach my $field (keys %{$saved}) {
1211 $new->setfield($field, $saved->{$field});
1219 my( $self ) = shift;
1220 warn "[$me] replace called with no arguments; autoloading old record\n"
1223 my $primary_key = $self->dbdef_table->primary_key;
1224 if ( $primary_key ) {
1225 $self->by_key( $self->$primary_key() ) #this is what's returned
1226 or croak "can't find ". $self->table. ".$primary_key ".
1227 $self->$primary_key();
1229 croak $self->table. " has no primary key; pass old record as argument";
1236 Depriciated (use replace instead).
1241 cluck "warning: FS::Record::rep deprecated!";
1242 replace @_; #call method in this scope
1247 Checks virtual fields (using check_blocks). Subclasses should still provide
1248 a check method to validate real fields, foreign keys, etc., and call this
1249 method via $self->SUPER::check.
1251 (FIXME: Should this method try to make sure that it I<is> being called from
1252 a subclass's check method, to keep the current semantics as far as possible?)
1257 #confess "FS::Record::check not implemented; supply one in subclass!";
1260 foreach my $field ($self->virtual_fields) {
1261 for ($self->getfield($field)) {
1262 # See notes on check_block in FS::part_virtual_field.
1263 eval $self->pvf($field)->check_block;
1265 #this is bad, probably want to follow the stack backtrace up and see
1267 my $err = "Fatal error checking $field for $self";
1269 return "$err (see log for backtrace): $@";
1272 $self->setfield($field, $_);
1279 my( $self, $action, $time ) = @_;
1284 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1285 real_fields($self->table);
1288 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1289 # You can see if it changed by the paymask...
1290 if ($conf->exists('encryption') ) {
1291 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1293 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1295 "INSERT INTO h_". $self->table. " ( ".
1296 join(', ', qw(history_date history_user history_action), @fields ).
1298 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1305 B<Warning>: External use is B<deprecated>.
1307 Replaces COLUMN in record with a unique number, using counters in the
1308 filesystem. Used by the B<insert> method on single-field unique columns
1309 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1310 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1312 Returns the new value.
1317 my($self,$field) = @_;
1318 my($table)=$self->table;
1320 croak "Unique called on field $field, but it is ",
1321 $self->getfield($field),
1323 if $self->getfield($field);
1325 #warn "table $table is tainted" if is_tainted($table);
1326 #warn "field $field is tainted" if is_tainted($field);
1328 my($counter) = new File::CounterFile "$table.$field",0;
1330 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1332 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1335 my $index = $counter->inc;
1336 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1338 $index =~ /^(\d*)$/;
1341 $self->setfield($field,$index);
1345 =item ut_float COLUMN
1347 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1348 null. If there is an error, returns the error, otherwise returns false.
1353 my($self,$field)=@_ ;
1354 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1355 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1356 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1357 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1358 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1359 $self->setfield($field,$1);
1362 =item ut_floatn COLUMN
1364 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1365 null. If there is an error, returns the error, otherwise returns false.
1369 #false laziness w/ut_ipn
1371 my( $self, $field ) = @_;
1372 if ( $self->getfield($field) =~ /^()$/ ) {
1373 $self->setfield($field,'');
1376 $self->ut_float($field);
1380 =item ut_sfloat COLUMN
1382 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1383 May not be null. If there is an error, returns the error, otherwise returns
1389 my($self,$field)=@_ ;
1390 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1391 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1392 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1393 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1394 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1395 $self->setfield($field,$1);
1398 =item ut_sfloatn COLUMN
1400 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1401 null. If there is an error, returns the error, otherwise returns false.
1406 my( $self, $field ) = @_;
1407 if ( $self->getfield($field) =~ /^()$/ ) {
1408 $self->setfield($field,'');
1411 $self->ut_sfloat($field);
1415 =item ut_snumber COLUMN
1417 Check/untaint signed numeric data (whole numbers). If there is an error,
1418 returns the error, otherwise returns false.
1423 my($self, $field) = @_;
1424 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1425 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1426 $self->setfield($field, "$1$2");
1430 =item ut_snumbern COLUMN
1432 Check/untaint signed numeric data (whole numbers). If there is an error,
1433 returns the error, otherwise returns false.
1438 my($self, $field) = @_;
1439 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1440 or return "Illegal (numeric) $field: ". $self->getfield($field);
1442 return "Illegal (numeric) $field: ". $self->getfield($field)
1445 $self->setfield($field, "$1$2");
1449 =item ut_number COLUMN
1451 Check/untaint simple numeric data (whole numbers). May not be null. If there
1452 is an error, returns the error, otherwise returns false.
1457 my($self,$field)=@_;
1458 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1459 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1460 $self->setfield($field,$1);
1464 =item ut_numbern COLUMN
1466 Check/untaint simple numeric data (whole numbers). May be null. If there is
1467 an error, returns the error, otherwise returns false.
1472 my($self,$field)=@_;
1473 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1474 or return "Illegal (numeric) $field: ". $self->getfield($field);
1475 $self->setfield($field,$1);
1479 =item ut_money COLUMN
1481 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1482 is an error, returns the error, otherwise returns false.
1487 my($self,$field)=@_;
1488 $self->setfield($field, 0) if $self->getfield($field) eq '';
1489 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1490 or return "Illegal (money) $field: ". $self->getfield($field);
1491 #$self->setfield($field, "$1$2$3" || 0);
1492 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1496 =item ut_text COLUMN
1498 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1499 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1500 May not be null. If there is an error, returns the error, otherwise returns
1506 my($self,$field)=@_;
1507 #warn "msgcat ". \&msgcat. "\n";
1508 #warn "notexist ". \¬exist. "\n";
1509 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1510 $self->getfield($field)
1511 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1512 or return gettext('illegal_or_empty_text'). " $field: ".
1513 $self->getfield($field);
1514 $self->setfield($field,$1);
1518 =item ut_textn COLUMN
1520 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1521 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1522 May be null. If there is an error, returns the error, otherwise returns false.
1527 my($self,$field)=@_;
1528 $self->getfield($field)
1529 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1530 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1531 $self->setfield($field,$1);
1535 =item ut_alpha COLUMN
1537 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1538 an error, returns the error, otherwise returns false.
1543 my($self,$field)=@_;
1544 $self->getfield($field) =~ /^(\w+)$/
1545 or return "Illegal or empty (alphanumeric) $field: ".
1546 $self->getfield($field);
1547 $self->setfield($field,$1);
1551 =item ut_alpha COLUMN
1553 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1554 error, returns the error, otherwise returns false.
1559 my($self,$field)=@_;
1560 $self->getfield($field) =~ /^(\w*)$/
1561 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1562 $self->setfield($field,$1);
1566 =item ut_alpha_lower COLUMN
1568 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1569 there is an error, returns the error, otherwise returns false.
1573 sub ut_alpha_lower {
1574 my($self,$field)=@_;
1575 $self->getfield($field) =~ /[[:upper:]]/
1576 and return "Uppercase characters are not permitted in $field";
1577 $self->ut_alpha($field);
1580 =item ut_phonen COLUMN [ COUNTRY ]
1582 Check/untaint phone numbers. May be null. If there is an error, returns
1583 the error, otherwise returns false.
1585 Takes an optional two-letter ISO country code; without it or with unsupported
1586 countries, ut_phonen simply calls ut_alphan.
1591 my( $self, $field, $country ) = @_;
1592 return $self->ut_alphan($field) unless defined $country;
1593 my $phonen = $self->getfield($field);
1594 if ( $phonen eq '' ) {
1595 $self->setfield($field,'');
1596 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1598 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1599 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1600 $phonen = "$1-$2-$3";
1601 $phonen .= " x$4" if $4;
1602 $self->setfield($field,$phonen);
1604 warn "warning: don't know how to check phone numbers for country $country";
1605 return $self->ut_textn($field);
1612 Check/untaint hexadecimal values.
1617 my($self, $field) = @_;
1618 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1619 or return "Illegal (hex) $field: ". $self->getfield($field);
1620 $self->setfield($field, uc($1));
1624 =item ut_hexn COLUMN
1626 Check/untaint hexadecimal values. May be null.
1631 my($self, $field) = @_;
1632 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1633 or return "Illegal (hex) $field: ". $self->getfield($field);
1634 $self->setfield($field, uc($1));
1639 Check/untaint ip addresses. IPv4 only for now.
1644 my( $self, $field ) = @_;
1645 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1646 or return "Illegal (IP address) $field: ". $self->getfield($field);
1647 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1648 $self->setfield($field, "$1.$2.$3.$4");
1654 Check/untaint ip addresses. IPv4 only for now. May be null.
1659 my( $self, $field ) = @_;
1660 if ( $self->getfield($field) =~ /^()$/ ) {
1661 $self->setfield($field,'');
1664 $self->ut_ip($field);
1668 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
1670 Check/untaint coordinates.
1671 Accepts the following forms:
1681 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
1682 The latter form (that is, the MMM are thousands of minutes) is
1683 assumed if the "MMM" is exactly three digits or two digits > 59.
1685 To be safe, just use the DDD.DDDDD form.
1687 If LOWER or UPPER are specified, then the coordinate is checked
1688 for lower and upper bounds, respectively.
1694 my ($self, $field) = (shift, shift);
1696 my $lower = shift if scalar(@_);
1697 my $upper = shift if scalar(@_);
1698 my $coord = $self->getfield($field);
1699 my $neg = $coord =~ s/^(-)//;
1701 my ($d, $m, $s) = (0, 0, 0);
1704 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
1705 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
1706 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
1708 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
1711 return "Invalid (coordinate with minutes > 59) $field: "
1712 . $self->getfield($field);
1715 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
1717 if (defined($lower) and ($coord < $lower)) {
1718 return "Invalid (coordinate < $lower) $field: "
1719 . $self->getfield($field);;
1722 if (defined($upper) and ($coord > $upper)) {
1723 return "Invalid (coordinate > $upper) $field: "
1724 . $self->getfield($field);;
1727 $self->setfield($field, $coord);
1731 return "Invalid (coordinate) $field: " . $self->getfield($field);
1735 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
1737 Same as ut_coord, except optionally null.
1743 my ($self, $field) = (shift, shift);
1745 if ($self->getfield($field) =~ /^$/) {
1748 return $self->ut_coord($field, @_);
1754 =item ut_domain COLUMN
1756 Check/untaint host and domain names.
1761 my( $self, $field ) = @_;
1762 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1763 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1764 or return "Illegal (domain) $field: ". $self->getfield($field);
1765 $self->setfield($field,$1);
1769 =item ut_name COLUMN
1771 Check/untaint proper names; allows alphanumerics, spaces and the following
1772 punctuation: , . - '
1779 my( $self, $field ) = @_;
1780 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1781 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1782 $self->setfield($field,$1);
1788 Check/untaint zip codes.
1792 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1795 my( $self, $field, $country ) = @_;
1797 if ( $country eq 'US' ) {
1799 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1800 or return gettext('illegal_zip'). " $field for country $country: ".
1801 $self->getfield($field);
1802 $self->setfield($field, $1);
1804 } elsif ( $country eq 'CA' ) {
1806 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1807 or return gettext('illegal_zip'). " $field for country $country: ".
1808 $self->getfield($field);
1809 $self->setfield($field, "$1 $2");
1813 if ( $self->getfield($field) =~ /^\s*$/
1814 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1817 $self->setfield($field,'');
1819 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1820 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1821 $self->setfield($field,$1);
1829 =item ut_country COLUMN
1831 Check/untaint country codes. Country names are changed to codes, if possible -
1832 see L<Locale::Country>.
1837 my( $self, $field ) = @_;
1838 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1839 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1840 && country2code($1) ) {
1841 $self->setfield($field,uc(country2code($1)));
1844 $self->getfield($field) =~ /^(\w\w)$/
1845 or return "Illegal (country) $field: ". $self->getfield($field);
1846 $self->setfield($field,uc($1));
1850 =item ut_anything COLUMN
1852 Untaints arbitrary data. Be careful.
1857 my( $self, $field ) = @_;
1858 $self->getfield($field) =~ /^(.*)$/s
1859 or return "Illegal $field: ". $self->getfield($field);
1860 $self->setfield($field,$1);
1864 =item ut_enum COLUMN CHOICES_ARRAYREF
1866 Check/untaint a column, supplying all possible choices, like the "enum" type.
1871 my( $self, $field, $choices ) = @_;
1872 foreach my $choice ( @$choices ) {
1873 if ( $self->getfield($field) eq $choice ) {
1874 $self->setfield($choice);
1878 return "Illegal (enum) field $field: ". $self->getfield($field);
1881 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1883 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1884 on the column first.
1888 sub ut_foreign_key {
1889 my( $self, $field, $table, $foreign ) = @_;
1890 qsearchs($table, { $foreign => $self->getfield($field) })
1891 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1892 " in $table.$foreign";
1896 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1898 Like ut_foreign_key, except the null value is also allowed.
1902 sub ut_foreign_keyn {
1903 my( $self, $field, $table, $foreign ) = @_;
1904 $self->getfield($field)
1905 ? $self->ut_foreign_key($field, $table, $foreign)
1909 =item ut_agentnum_acl
1911 Checks this column as an agentnum, taking into account the current users's
1916 sub ut_agentnum_acl {
1917 my( $self, $field, $null_acl ) = @_;
1919 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1920 return "Illegal agentnum: $error" if $error;
1922 my $curuser = $FS::CurrentUser::CurrentUser;
1924 if ( $self->$field() ) {
1926 return "Access denied"
1927 unless $curuser->agentnum($self->$field());
1931 return "Access denied"
1932 unless $curuser->access_right($null_acl);
1940 =item virtual_fields [ TABLE ]
1942 Returns a list of virtual fields defined for the table. This should not
1943 be exported, and should only be called as an instance or class method.
1947 sub virtual_fields {
1950 $table = $self->table or confess "virtual_fields called on non-table";
1952 confess "Unknown table $table" unless dbdef->table($table);
1954 return () unless dbdef->table('part_virtual_field');
1956 unless ( $virtual_fields_cache{$table} ) {
1957 my $query = 'SELECT name from part_virtual_field ' .
1958 "WHERE dbtable = '$table'";
1960 my $result = $dbh->selectcol_arrayref($query);
1961 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1963 $virtual_fields_cache{$table} = $result;
1966 @{$virtual_fields_cache{$table}};
1971 =item fields [ TABLE ]
1973 This is a wrapper for real_fields and virtual_fields. Code that called
1974 fields before should probably continue to call fields.
1979 my $something = shift;
1981 if($something->isa('FS::Record')) {
1982 $table = $something->table;
1984 $table = $something;
1985 $something = "FS::$table";
1987 return (real_fields($table), $something->virtual_fields());
1990 =item pvf FIELD_NAME
1992 Returns the FS::part_virtual_field object corresponding to a field in the
1993 record (specified by FIELD_NAME).
1998 my ($self, $name) = (shift, shift);
2000 if(grep /^$name$/, $self->virtual_fields) {
2001 return qsearchs('part_virtual_field', { dbtable => $self->table,
2007 =item vfieldpart_hashref TABLE
2009 Returns a hashref of virtual field names and vfieldparts applicable to the given
2014 sub vfieldpart_hashref {
2016 my $table = $self->table;
2018 return {} unless dbdef->table('part_virtual_field');
2021 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2022 "dbtable = '$table'";
2023 my $sth = $dbh->prepare($statement);
2024 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2025 return { map { $_->{name}, $_->{vfieldpart} }
2026 @{$sth->fetchall_arrayref({})} };
2030 =item encrypt($value)
2032 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2034 Returns the encrypted string.
2036 You should generally not have to worry about calling this, as the system handles this for you.
2041 my ($self, $value) = @_;
2044 if ($conf->exists('encryption')) {
2045 if ($self->is_encrypted($value)) {
2046 # Return the original value if it isn't plaintext.
2047 $encrypted = $value;
2050 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2051 # RSA doesn't like the empty string so let's pack it up
2052 # The database doesn't like the RSA data so uuencode it
2053 my $length = length($value)+1;
2054 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2056 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2063 =item is_encrypted($value)
2065 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2071 my ($self, $value) = @_;
2072 # Possible Bug - Some work may be required here....
2074 if ($value =~ /^M/ && length($value) > 80) {
2081 =item decrypt($value)
2083 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2085 You should generally not have to worry about calling this, as the system handles this for you.
2090 my ($self,$value) = @_;
2091 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2092 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2094 if (ref($rsa_decrypt) =~ /::RSA/) {
2095 my $encrypted = unpack ("u*", $value);
2096 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2097 if ($@) {warn "Decryption Failed"};
2105 #Initialize the Module
2106 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2108 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2109 $rsa_module = $conf->config('encryptionmodule');
2113 eval ("require $rsa_module"); # No need to import the namespace
2116 # Initialize Encryption
2117 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2118 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2119 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2122 # Intitalize Decryption
2123 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2124 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2125 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2129 =item h_search ACTION
2131 Given an ACTION, either "insert", or "delete", returns the appropriate history
2132 record corresponding to this record, if any.
2137 my( $self, $action ) = @_;
2139 my $table = $self->table;
2142 my $primary_key = dbdef->table($table)->primary_key;
2145 'table' => "h_$table",
2146 'hashref' => { $primary_key => $self->$primary_key(),
2147 'history_action' => $action,
2155 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2156 appropriate history record corresponding to this record, if any.
2161 my($self, $action) = @_;
2162 my $h = $self->h_search($action);
2163 $h ? $h->history_date : '';
2172 =item real_fields [ TABLE ]
2174 Returns a list of the real columns in the specified table. Called only by
2175 fields() and other subroutines elsewhere in FS::Record.
2182 my($table_obj) = dbdef->table($table);
2183 confess "Unknown table $table" unless $table_obj;
2184 $table_obj->columns;
2187 =item _quote VALUE, TABLE, COLUMN
2189 This is an internal function used to construct SQL statements. It returns
2190 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2191 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2196 my($value, $table, $column) = @_;
2197 my $column_obj = dbdef->table($table)->column($column);
2198 my $column_type = $column_obj->type;
2199 my $nullable = $column_obj->null;
2201 warn " $table.$column: $value ($column_type".
2202 ( $nullable ? ' NULL' : ' NOT NULL' ).
2203 ")\n" if $DEBUG > 2;
2205 if ( $value eq '' && $nullable ) {
2207 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2208 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2211 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2212 ! $column_type =~ /(char|binary|text)$/i ) {
2221 This is deprecated. Don't use it.
2223 It returns a hash-type list with the fields of this record's table set true.
2228 carp "warning: hfields is deprecated";
2231 foreach (fields($table)) {
2240 "$_: ". $self->getfield($_). "|"
2241 } (fields($self->table)) );
2244 sub DESTROY { return; }
2248 # #use Carp qw(cluck);
2249 # #cluck "DESTROYING $self";
2250 # warn "DESTROYING $self";
2254 # return ! eval { join('',@_), kill 0; 1; };
2257 =item str2time_sql [ DRIVER_NAME ]
2259 Returns a function to convert to unix time based on database type, such as
2260 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2261 the str2time_sql_closing method to return a closing string rather than just
2262 using a closing parenthesis as previously suggested.
2264 You can pass an optional driver name such as "Pg", "mysql" or
2265 $dbh->{Driver}->{Name} to return a function for that database instead of
2266 the current database.
2271 my $driver = shift || driver_name;
2273 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2274 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2276 warn "warning: unknown database type $driver; guessing how to convert ".
2277 "dates to UNIX timestamps";
2278 return 'EXTRACT(EPOCH FROM ';
2282 =item str2time_sql_closing [ DRIVER_NAME ]
2284 Returns the closing suffix of a function to convert to unix time based on
2285 database type, such as ")::integer" for Pg or ")" for mysql.
2287 You can pass an optional driver name such as "Pg", "mysql" or
2288 $dbh->{Driver}->{Name} to return a function for that database instead of
2289 the current database.
2293 sub str2time_sql_closing {
2294 my $driver = shift || driver_name;
2296 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2304 This module should probably be renamed, since much of the functionality is
2305 of general use. It is not completely unlike Adapter::DBI (see below).
2307 Exported qsearch and qsearchs should be deprecated in favor of method calls
2308 (against an FS::Record object like the old search and searchs that qsearch
2309 and qsearchs were on top of.)
2311 The whole fields / hfields mess should be removed.
2313 The various WHERE clauses should be subroutined.
2315 table string should be deprecated in favor of DBIx::DBSchema::Table.
2317 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2318 true maps to the database (and WHERE clauses) would also help.
2320 The ut_ methods should ask the dbdef for a default length.
2322 ut_sqltype (like ut_varchar) should all be defined
2324 A fallback check method should be provided which uses the dbdef.
2326 The ut_money method assumes money has two decimal digits.
2328 The Pg money kludge in the new method only strips `$'.
2330 The ut_phonen method only checks US-style phone numbers.
2332 The _quote function should probably use ut_float instead of a regex.
2334 All the subroutines probably should be methods, here or elsewhere.
2336 Probably should borrow/use some dbdef methods where appropriate (like sub
2339 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2340 or allow it to be set. Working around it is ugly any way around - DBI should
2341 be fixed. (only affects RDBMS which return uppercase column names)
2343 ut_zip should take an optional country like ut_phone.
2347 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2349 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.