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 {
45 $conf = FS::Conf->new;
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
241 my %TYPE = (); #for debugging
244 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
246 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
248 $stable = $opt->{'table'} or die "table name is required";
249 $record = $opt->{'hashref'} || {};
250 $select = $opt->{'select'} || '*';
251 $extra_sql = $opt->{'extra_sql'} || '';
252 $order_by = $opt->{'order_by'} || '';
253 $cache = $opt->{'cache_obj'} || '';
254 $addl_from = $opt->{'addl_from'} || '';
255 $debug = $opt->{'debug'} || '';
257 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
261 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
263 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
267 my $table = $cache ? $cache->table : $stable;
268 my $dbdef_table = dbdef->table($table)
269 or die "No schema for table $table found - ".
270 "do you need to run freeside-upgrade?";
271 my $pkey = $dbdef_table->primary_key;
273 my @real_fields = grep exists($record->{$_}), real_fields($table);
275 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
276 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
278 cluck "warning: FS::$table not loaded; virtual fields not searchable";
279 @virtual_fields = ();
282 my $statement = "SELECT $select FROM $stable";
283 $statement .= " $addl_from" if $addl_from;
284 if ( @real_fields or @virtual_fields ) {
285 $statement .= ' WHERE '. join(' AND ',
286 get_real_fields($table, $record, \@real_fields) ,
287 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
291 $statement .= " $extra_sql" if defined($extra_sql);
292 $statement .= " $order_by" if defined($order_by);
294 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
295 my $sth = $dbh->prepare($statement)
296 or croak "$dbh->errstr doing $statement";
301 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
304 my $value = $record->{$field};
305 $value = $value->{'value'} if ref($value);
306 my $type = dbdef->table($table)->column($field)->type;
308 my $TYPE = SQL_VARCHAR;
309 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
312 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6
313 #} elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
314 # || ( $type =~ /(real|float4)/i
315 # && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
323 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
325 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
328 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
332 # $sth->execute( map $record->{$_},
333 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
334 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
336 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
338 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
339 @virtual_fields = "FS::$table"->virtual_fields;
341 cluck "warning: FS::$table not loaded; virtual fields not returned either";
342 @virtual_fields = ();
346 tie %result, "Tie::IxHash";
347 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
348 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
349 %result = map { $_->{$pkey}, $_ } @stuff;
351 @result{@stuff} = @stuff;
356 if ( keys(%result) and @virtual_fields ) {
358 "SELECT virtual_field.recnum, part_virtual_field.name, ".
359 "virtual_field.value ".
360 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
361 "WHERE part_virtual_field.dbtable = '$table' AND ".
362 "virtual_field.recnum IN (".
363 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
364 join(q!', '!, @virtual_fields) . "')";
365 warn "[debug]$me $statement\n" if $DEBUG > 1;
366 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
367 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
369 foreach (@{ $sth->fetchall_arrayref({}) }) {
370 my $recnum = $_->{recnum};
371 my $name = $_->{name};
372 my $value = $_->{value};
373 if (exists($result{$recnum})) {
374 $result{$recnum}->{$name} = $value;
379 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
380 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
381 #derivied class didn't override new method, so this optimization is safe
384 new_or_cached( "FS::$table", { %{$_} }, $cache )
388 new( "FS::$table", { %{$_} } )
392 #okay, its been tested
393 # warn "untested code (class FS::$table uses custom new method)";
395 eval 'FS::'. $table. '->new( { %{$_} } )';
399 # Check for encrypted fields and decrypt them.
400 ## only in the local copy, not the cached object
401 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
402 # the initial search for
404 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
405 foreach my $record (@return) {
406 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
407 # Set it directly... This may cause a problem in the future...
408 $record->setfield($field, $record->decrypt($record->getfield($field)));
413 cluck "warning: FS::$table not loaded; returning FS::Record objects";
415 FS::Record->new( $table, { %{$_} } );
421 ## makes this easier to read
423 sub get_virtual_fields {
427 my $virtual_fields = shift;
433 if ( ref($record->{$_}) ) {
434 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
435 if ( uc($op) eq 'ILIKE' ) {
437 $record->{$_}{'value'} = lc($record->{$_}{'value'});
438 $column = "LOWER($_)";
440 $record->{$_} = $record->{$_}{'value'};
443 # ... EXISTS ( SELECT name, value FROM part_virtual_field
445 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
446 # WHERE recnum = svc_acct.svcnum
447 # AND (name, value) = ('egad', 'brain') )
449 my $value = $record->{$_};
453 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
454 "( SELECT part_virtual_field.name, virtual_field.value ".
455 "FROM part_virtual_field JOIN virtual_field ".
456 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
457 "WHERE virtual_field.recnum = ${table}.${pkey} ".
458 "AND part_virtual_field.name = '${column}'".
460 " AND virtual_field.value ${op} '${value}'"
464 } @{ $virtual_fields } ) ;
467 sub get_real_fields {
470 my $real_fields = shift;
472 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
478 if ( ref($record->{$_}) ) {
479 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
480 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
481 if ( uc($op) eq 'ILIKE' ) {
483 $record->{$_}{'value'} = lc($record->{$_}{'value'});
484 $column = "LOWER($_)";
486 $record->{$_} = $record->{$_}{'value'}
489 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
491 if ( driver_name eq 'Pg' ) {
492 my $type = dbdef->table($table)->column($column)->type;
493 if ( $type =~ /(int|(big)?serial)/i ) {
494 qq-( $column IS NULL )-;
496 qq-( $column IS NULL OR $column = '' )-;
499 qq-( $column IS NULL OR $column = "" )-;
501 } elsif ( $op eq '!=' ) {
502 if ( driver_name eq 'Pg' ) {
503 my $type = dbdef->table($table)->column($column)->type;
504 if ( $type =~ /(int|(big)?serial)/i ) {
505 qq-( $column IS NOT NULL )-;
507 qq-( $column IS NOT NULL AND $column != '' )-;
510 qq-( $column IS NOT NULL AND $column != "" )-;
513 if ( driver_name eq 'Pg' ) {
514 qq-( $column $op '' )-;
516 qq-( $column $op "" )-;
522 } @{ $real_fields } );
525 =item by_key PRIMARY_KEY_VALUE
527 This is a class method that returns the record with the given primary key
528 value. This method is only useful in FS::Record subclasses. For example:
530 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
534 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
539 my ($class, $pkey_value) = @_;
541 my $table = $class->table
542 or croak "No table for $class found";
544 my $dbdef_table = dbdef->table($table)
545 or die "No schema for table $table found - ".
546 "do you need to create it or run dbdef-create?";
547 my $pkey = $dbdef_table->primary_key
548 or die "No primary key for table $table";
550 return qsearchs($table, { $pkey => $pkey_value });
553 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
555 Experimental JOINed search method. Using this method, you can execute a
556 single SELECT spanning multiple tables, and cache the results for subsequent
557 method calls. Interface will almost definately change in an incompatible
565 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
566 my $cache = FS::SearchCache->new( $ptable, $pkey );
569 grep { !$saw{$_->getfield($pkey)}++ }
570 qsearch($table, $record, $select, $extra_sql, $cache )
574 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
576 Same as qsearch, except that if more than one record matches, it B<carp>s but
577 returns the first. If this happens, you either made a logic error in asking
578 for a single item, or your data is corrupted.
582 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
584 my(@result) = qsearch(@_);
585 cluck "warning: Multiple records in scalar search ($table)"
586 if scalar(@result) > 1;
587 #should warn more vehemently if the search was on a primary key?
588 scalar(@result) ? ($result[0]) : ();
599 Returns the table name.
604 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
611 Returns the DBIx::DBSchema::Table object for the table.
617 my($table)=$self->table;
618 dbdef->table($table);
623 Returns the primary key for the table.
629 my $pkey = $self->dbdef_table->primary_key;
632 =item get, getfield COLUMN
634 Returns the value of the column/field/key COLUMN.
639 my($self,$field) = @_;
640 # to avoid "Use of unitialized value" errors
641 if ( defined ( $self->{Hash}->{$field} ) ) {
642 $self->{Hash}->{$field};
652 =item set, setfield COLUMN, VALUE
654 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
659 my($self,$field,$value) = @_;
660 $self->{'modified'} = 1;
661 $self->{'Hash'}->{$field} = $value;
668 =item AUTLOADED METHODS
670 $record->column is a synonym for $record->get('column');
672 $record->column('value') is a synonym for $record->set('column','value');
679 my($field)=$AUTOLOAD;
681 if ( defined($value) ) {
682 confess "errant AUTOLOAD $field for $self (arg $value)"
683 unless blessed($self) && $self->can('setfield');
684 $self->setfield($field,$value);
686 confess "errant AUTOLOAD $field for $self (no args)"
687 unless blessed($self) && $self->can('getfield');
688 $self->getfield($field);
694 # my $field = $AUTOLOAD;
696 # if ( defined($_[1]) ) {
697 # $_[0]->setfield($field, $_[1]);
699 # $_[0]->getfield($field);
705 Returns a list of the column/value pairs, usually for assigning to a new hash.
707 To make a distinct duplicate of an FS::Record object, you can do:
709 $new = new FS::Record ( $old->table, { $old->hash } );
715 confess $self. ' -> hash: Hash attribute is undefined'
716 unless defined($self->{'Hash'});
717 %{ $self->{'Hash'} };
722 Returns a reference to the column/value hash. This may be deprecated in the
723 future; if there's a reason you can't just use the autoloaded or get/set
735 Returns true if any of this object's values have been modified with set (or via
736 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
746 =item select_for_update
748 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
753 sub select_for_update {
755 my $primary_key = $self->primary_key;
758 'table' => $self->table,
759 'hashref' => { $primary_key => $self->$primary_key() },
760 'extra_sql' => 'FOR UPDATE',
766 Inserts this record to the database. If there is an error, returns the error,
767 otherwise returns false.
775 warn "$self -> insert" if $DEBUG;
777 my $error = $self->check;
778 return $error if $error;
780 #single-field unique keys are given a value if false
781 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
782 foreach ( $self->dbdef_table->unique_singles) {
783 $self->unique($_) unless $self->getfield($_);
786 #and also the primary key, if the database isn't going to
787 my $primary_key = $self->dbdef_table->primary_key;
789 if ( $primary_key ) {
790 my $col = $self->dbdef_table->column($primary_key);
793 uc($col->type) =~ /^(BIG)?SERIAL\d?/
794 || ( driver_name eq 'Pg'
795 && defined($col->default)
796 && $col->default =~ /^nextval\(/i
798 || ( driver_name eq 'mysql'
799 && defined($col->local)
800 && $col->local =~ /AUTO_INCREMENT/i
802 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
805 my $table = $self->table;
808 # Encrypt before the database
809 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
810 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
811 $self->{'saved'} = $self->getfield($field);
812 $self->setfield($field, $self->encrypt($self->getfield($field)));
817 #false laziness w/delete
819 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
822 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
825 my $statement = "INSERT INTO $table ";
826 if ( @real_fields ) {
829 join( ', ', @real_fields ).
831 join( ', ', @values ).
835 $statement .= 'DEFAULT VALUES';
837 warn "[debug]$me $statement\n" if $DEBUG > 1;
838 my $sth = dbh->prepare($statement) or return dbh->errstr;
840 local $SIG{HUP} = 'IGNORE';
841 local $SIG{INT} = 'IGNORE';
842 local $SIG{QUIT} = 'IGNORE';
843 local $SIG{TERM} = 'IGNORE';
844 local $SIG{TSTP} = 'IGNORE';
845 local $SIG{PIPE} = 'IGNORE';
847 $sth->execute or return $sth->errstr;
849 # get inserted id from the database, if applicable & needed
850 if ( $db_seq && ! $self->getfield($primary_key) ) {
851 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
855 if ( driver_name eq 'Pg' ) {
857 #my $oid = $sth->{'pg_oid_status'};
858 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
860 my $default = $self->dbdef_table->column($primary_key)->default;
861 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
862 dbh->rollback if $FS::UID::AutoCommit;
863 return "can't parse $table.$primary_key default value".
864 " for sequence name: $default";
868 my $i_sql = "SELECT currval('$sequence')";
869 my $i_sth = dbh->prepare($i_sql) or do {
870 dbh->rollback if $FS::UID::AutoCommit;
873 $i_sth->execute() or do { #$i_sth->execute($oid)
874 dbh->rollback if $FS::UID::AutoCommit;
875 return $i_sth->errstr;
877 $insertid = $i_sth->fetchrow_arrayref->[0];
879 } elsif ( driver_name eq 'mysql' ) {
881 $insertid = dbh->{'mysql_insertid'};
882 # work around mysql_insertid being null some of the time, ala RT :/
883 unless ( $insertid ) {
884 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
885 "using SELECT LAST_INSERT_ID();";
886 my $i_sql = "SELECT LAST_INSERT_ID()";
887 my $i_sth = dbh->prepare($i_sql) or do {
888 dbh->rollback if $FS::UID::AutoCommit;
891 $i_sth->execute or do {
892 dbh->rollback if $FS::UID::AutoCommit;
893 return $i_sth->errstr;
895 $insertid = $i_sth->fetchrow_arrayref->[0];
900 dbh->rollback if $FS::UID::AutoCommit;
901 return "don't know how to retreive inserted ids from ". driver_name.
902 ", try using counterfiles (maybe run dbdef-create?)";
906 $self->setfield($primary_key, $insertid);
911 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
912 $self->virtual_fields;
913 if (@virtual_fields) {
914 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
916 my $vfieldpart = $self->vfieldpart_hashref;
918 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
921 my $v_sth = dbh->prepare($v_statement) or do {
922 dbh->rollback if $FS::UID::AutoCommit;
926 foreach (keys(%v_values)) {
927 $v_sth->execute($self->getfield($primary_key),
931 dbh->rollback if $FS::UID::AutoCommit;
932 return $v_sth->errstr;
939 if ( defined dbdef->table('h_'. $table) ) {
940 my $h_statement = $self->_h_statement('insert');
941 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
942 $h_sth = dbh->prepare($h_statement) or do {
943 dbh->rollback if $FS::UID::AutoCommit;
949 $h_sth->execute or return $h_sth->errstr if $h_sth;
951 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
953 # Now that it has been saved, reset the encrypted fields so that $new
955 foreach my $field (keys %{$saved}) {
956 $self->setfield($field, $saved->{$field});
964 Depriciated (use insert instead).
969 cluck "warning: FS::Record::add deprecated!";
970 insert @_; #call method in this scope
975 Delete this record from the database. If there is an error, returns the error,
976 otherwise returns false.
983 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
985 $self->getfield($_) eq ''
986 #? "( $_ IS NULL OR $_ = \"\" )"
987 ? ( driver_name eq 'Pg'
989 : "( $_ IS NULL OR $_ = \"\" )"
991 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
992 } ( $self->dbdef_table->primary_key )
993 ? ( $self->dbdef_table->primary_key)
994 : real_fields($self->table)
996 warn "[debug]$me $statement\n" if $DEBUG > 1;
997 my $sth = dbh->prepare($statement) or return dbh->errstr;
1000 if ( defined dbdef->table('h_'. $self->table) ) {
1001 my $h_statement = $self->_h_statement('delete');
1002 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1003 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1008 my $primary_key = $self->dbdef_table->primary_key;
1011 my $vfp = $self->vfieldpart_hashref;
1012 foreach($self->virtual_fields) {
1013 next if $self->getfield($_) eq '';
1014 unless(@del_vfields) {
1015 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1016 $v_sth = dbh->prepare($st) or return dbh->errstr;
1018 push @del_vfields, $_;
1021 local $SIG{HUP} = 'IGNORE';
1022 local $SIG{INT} = 'IGNORE';
1023 local $SIG{QUIT} = 'IGNORE';
1024 local $SIG{TERM} = 'IGNORE';
1025 local $SIG{TSTP} = 'IGNORE';
1026 local $SIG{PIPE} = 'IGNORE';
1028 my $rc = $sth->execute or return $sth->errstr;
1029 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1030 $h_sth->execute or return $h_sth->errstr if $h_sth;
1031 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1032 or return $v_sth->errstr
1033 foreach (@del_vfields);
1035 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1037 #no need to needlessly destoy the data either (causes problems actually)
1038 #undef $self; #no need to keep object!
1045 Depriciated (use delete instead).
1050 cluck "warning: FS::Record::del deprecated!";
1051 &delete(@_); #call method in this scope
1054 =item replace OLD_RECORD
1056 Replace the OLD_RECORD with this one in the database. If there is an error,
1057 returns the error, otherwise returns false.
1062 my ($new, $old) = (shift, shift);
1064 $old = $new->replace_old unless defined($old);
1066 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1068 if ( $new->can('replace_check') ) {
1069 my $error = $new->replace_check($old);
1070 return $error if $error;
1073 return "Records not in same table!" unless $new->table eq $old->table;
1075 my $primary_key = $old->dbdef_table->primary_key;
1076 return "Can't change primary key $primary_key ".
1077 'from '. $old->getfield($primary_key).
1078 ' to ' . $new->getfield($primary_key)
1080 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1082 my $error = $new->check;
1083 return $error if $error;
1085 # Encrypt for replace
1087 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1088 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1089 $saved->{$field} = $new->getfield($field);
1090 $new->setfield($field, $new->encrypt($new->getfield($field)));
1094 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1095 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1096 ? ($_, $new->getfield($_)) : () } $old->fields;
1098 unless (keys(%diff) || $no_update_diff ) {
1099 carp "[warning]$me $new -> replace $old: records identical"
1100 unless $nowarn_identical;
1104 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1106 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1107 } real_fields($old->table)
1112 if ( $old->getfield($_) eq '' ) {
1114 #false laziness w/qsearch
1115 if ( driver_name eq 'Pg' ) {
1116 my $type = $old->dbdef_table->column($_)->type;
1117 if ( $type =~ /(int|(big)?serial)/i ) {
1120 qq-( $_ IS NULL OR $_ = '' )-;
1123 qq-( $_ IS NULL OR $_ = "" )-;
1127 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1130 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1133 warn "[debug]$me $statement\n" if $DEBUG > 1;
1134 my $sth = dbh->prepare($statement) or return dbh->errstr;
1137 if ( defined dbdef->table('h_'. $old->table) ) {
1138 my $h_old_statement = $old->_h_statement('replace_old');
1139 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1140 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1146 if ( defined dbdef->table('h_'. $new->table) ) {
1147 my $h_new_statement = $new->_h_statement('replace_new');
1148 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1149 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1154 # For virtual fields we have three cases with different SQL
1155 # statements: add, replace, delete
1159 my (@add_vfields, @rep_vfields, @del_vfields);
1160 my $vfp = $old->vfieldpart_hashref;
1161 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1162 if($diff{$_} eq '') {
1164 unless(@del_vfields) {
1165 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1166 "AND vfieldpart = ?";
1167 warn "[debug]$me $st\n" if $DEBUG > 2;
1168 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1170 push @del_vfields, $_;
1171 } elsif($old->getfield($_) eq '') {
1173 unless(@add_vfields) {
1174 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1176 warn "[debug]$me $st\n" if $DEBUG > 2;
1177 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1179 push @add_vfields, $_;
1182 unless(@rep_vfields) {
1183 my $st = "UPDATE virtual_field SET value = ? ".
1184 "WHERE recnum = ? AND vfieldpart = ?";
1185 warn "[debug]$me $st\n" if $DEBUG > 2;
1186 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1188 push @rep_vfields, $_;
1192 local $SIG{HUP} = 'IGNORE';
1193 local $SIG{INT} = 'IGNORE';
1194 local $SIG{QUIT} = 'IGNORE';
1195 local $SIG{TERM} = 'IGNORE';
1196 local $SIG{TSTP} = 'IGNORE';
1197 local $SIG{PIPE} = 'IGNORE';
1199 my $rc = $sth->execute or return $sth->errstr;
1200 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1201 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1202 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1204 $v_del_sth->execute($old->getfield($primary_key),
1206 or return $v_del_sth->errstr
1207 foreach(@del_vfields);
1209 $v_add_sth->execute($new->getfield($_),
1210 $old->getfield($primary_key),
1212 or return $v_add_sth->errstr
1213 foreach(@add_vfields);
1215 $v_rep_sth->execute($new->getfield($_),
1216 $old->getfield($primary_key),
1218 or return $v_rep_sth->errstr
1219 foreach(@rep_vfields);
1221 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1223 # Now that it has been saved, reset the encrypted fields so that $new
1224 # can still be used.
1225 foreach my $field (keys %{$saved}) {
1226 $new->setfield($field, $saved->{$field});
1234 my( $self ) = shift;
1235 warn "[$me] replace called with no arguments; autoloading old record\n"
1238 my $primary_key = $self->dbdef_table->primary_key;
1239 if ( $primary_key ) {
1240 $self->by_key( $self->$primary_key() ) #this is what's returned
1241 or croak "can't find ". $self->table. ".$primary_key ".
1242 $self->$primary_key();
1244 croak $self->table. " has no primary key; pass old record as argument";
1251 Depriciated (use replace instead).
1256 cluck "warning: FS::Record::rep deprecated!";
1257 replace @_; #call method in this scope
1262 Checks virtual fields (using check_blocks). Subclasses should still provide
1263 a check method to validate real fields, foreign keys, etc., and call this
1264 method via $self->SUPER::check.
1266 (FIXME: Should this method try to make sure that it I<is> being called from
1267 a subclass's check method, to keep the current semantics as far as possible?)
1272 #confess "FS::Record::check not implemented; supply one in subclass!";
1275 foreach my $field ($self->virtual_fields) {
1276 for ($self->getfield($field)) {
1277 # See notes on check_block in FS::part_virtual_field.
1278 eval $self->pvf($field)->check_block;
1280 #this is bad, probably want to follow the stack backtrace up and see
1282 my $err = "Fatal error checking $field for $self";
1284 return "$err (see log for backtrace): $@";
1287 $self->setfield($field, $_);
1294 my( $self, $action, $time ) = @_;
1299 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1300 real_fields($self->table);
1303 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1304 # You can see if it changed by the paymask...
1305 if ($conf->exists('encryption') ) {
1306 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1308 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1310 "INSERT INTO h_". $self->table. " ( ".
1311 join(', ', qw(history_date history_user history_action), @fields ).
1313 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1320 B<Warning>: External use is B<deprecated>.
1322 Replaces COLUMN in record with a unique number, using counters in the
1323 filesystem. Used by the B<insert> method on single-field unique columns
1324 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1325 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1327 Returns the new value.
1332 my($self,$field) = @_;
1333 my($table)=$self->table;
1335 croak "Unique called on field $field, but it is ",
1336 $self->getfield($field),
1338 if $self->getfield($field);
1340 #warn "table $table is tainted" if is_tainted($table);
1341 #warn "field $field is tainted" if is_tainted($field);
1343 my($counter) = new File::CounterFile "$table.$field",0;
1345 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1347 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1350 my $index = $counter->inc;
1351 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1353 $index =~ /^(\d*)$/;
1356 $self->setfield($field,$index);
1360 =item ut_float COLUMN
1362 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1363 null. If there is an error, returns the error, otherwise returns false.
1368 my($self,$field)=@_ ;
1369 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1370 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1371 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1372 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1373 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1374 $self->setfield($field,$1);
1377 =item ut_floatn COLUMN
1379 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1380 null. If there is an error, returns the error, otherwise returns false.
1384 #false laziness w/ut_ipn
1386 my( $self, $field ) = @_;
1387 if ( $self->getfield($field) =~ /^()$/ ) {
1388 $self->setfield($field,'');
1391 $self->ut_float($field);
1395 =item ut_sfloat COLUMN
1397 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1398 May not be null. If there is an error, returns the error, otherwise returns
1404 my($self,$field)=@_ ;
1405 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1406 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1407 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1408 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1409 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1410 $self->setfield($field,$1);
1413 =item ut_sfloatn COLUMN
1415 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1416 null. If there is an error, returns the error, otherwise returns false.
1421 my( $self, $field ) = @_;
1422 if ( $self->getfield($field) =~ /^()$/ ) {
1423 $self->setfield($field,'');
1426 $self->ut_sfloat($field);
1430 =item ut_snumber 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 or empty (numeric) $field: ". $self->getfield($field);
1441 $self->setfield($field, "$1$2");
1445 =item ut_snumbern COLUMN
1447 Check/untaint signed numeric data (whole numbers). If there is an error,
1448 returns the error, otherwise returns false.
1453 my($self, $field) = @_;
1454 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1455 or return "Illegal (numeric) $field: ". $self->getfield($field);
1457 return "Illegal (numeric) $field: ". $self->getfield($field)
1460 $self->setfield($field, "$1$2");
1464 =item ut_number COLUMN
1466 Check/untaint simple numeric data (whole numbers). May not be null. If there
1467 is an error, returns the error, otherwise returns false.
1472 my($self,$field)=@_;
1473 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1474 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1475 $self->setfield($field,$1);
1479 =item ut_numbern COLUMN
1481 Check/untaint simple numeric data (whole numbers). May be null. If there is
1482 an error, returns the error, otherwise returns false.
1487 my($self,$field)=@_;
1488 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1489 or return "Illegal (numeric) $field: ". $self->getfield($field);
1490 $self->setfield($field,$1);
1494 =item ut_money COLUMN
1496 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1497 is an error, returns the error, otherwise returns false.
1502 my($self,$field)=@_;
1503 $self->setfield($field, 0) if $self->getfield($field) eq '';
1504 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1505 or return "Illegal (money) $field: ". $self->getfield($field);
1506 #$self->setfield($field, "$1$2$3" || 0);
1507 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1511 =item ut_text COLUMN
1513 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1514 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1515 May not be null. If there is an error, returns the error, otherwise returns
1521 my($self,$field)=@_;
1522 #warn "msgcat ". \&msgcat. "\n";
1523 #warn "notexist ". \¬exist. "\n";
1524 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1525 $self->getfield($field)
1526 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1527 or return gettext('illegal_or_empty_text'). " $field: ".
1528 $self->getfield($field);
1529 $self->setfield($field,$1);
1533 =item ut_textn COLUMN
1535 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1536 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1537 May be null. If there is an error, returns the error, otherwise returns false.
1542 my($self,$field)=@_;
1543 $self->getfield($field)
1544 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1545 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1546 $self->setfield($field,$1);
1550 =item ut_alpha COLUMN
1552 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1553 an error, returns the error, otherwise returns false.
1558 my($self,$field)=@_;
1559 $self->getfield($field) =~ /^(\w+)$/
1560 or return "Illegal or empty (alphanumeric) $field: ".
1561 $self->getfield($field);
1562 $self->setfield($field,$1);
1566 =item ut_alpha COLUMN
1568 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1569 error, returns the error, otherwise returns false.
1574 my($self,$field)=@_;
1575 $self->getfield($field) =~ /^(\w*)$/
1576 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1577 $self->setfield($field,$1);
1581 =item ut_alpha_lower COLUMN
1583 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1584 there is an error, returns the error, otherwise returns false.
1588 sub ut_alpha_lower {
1589 my($self,$field)=@_;
1590 $self->getfield($field) =~ /[[:upper:]]/
1591 and return "Uppercase characters are not permitted in $field";
1592 $self->ut_alpha($field);
1595 =item ut_phonen COLUMN [ COUNTRY ]
1597 Check/untaint phone numbers. May be null. If there is an error, returns
1598 the error, otherwise returns false.
1600 Takes an optional two-letter ISO country code; without it or with unsupported
1601 countries, ut_phonen simply calls ut_alphan.
1606 my( $self, $field, $country ) = @_;
1607 return $self->ut_alphan($field) unless defined $country;
1608 my $phonen = $self->getfield($field);
1609 if ( $phonen eq '' ) {
1610 $self->setfield($field,'');
1611 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1613 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1614 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1615 $phonen = "$1-$2-$3";
1616 $phonen .= " x$4" if $4;
1617 $self->setfield($field,$phonen);
1619 warn "warning: don't know how to check phone numbers for country $country";
1620 return $self->ut_textn($field);
1627 Check/untaint hexadecimal values.
1632 my($self, $field) = @_;
1633 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1634 or return "Illegal (hex) $field: ". $self->getfield($field);
1635 $self->setfield($field, uc($1));
1639 =item ut_hexn COLUMN
1641 Check/untaint hexadecimal values. May be null.
1646 my($self, $field) = @_;
1647 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1648 or return "Illegal (hex) $field: ". $self->getfield($field);
1649 $self->setfield($field, uc($1));
1654 Check/untaint ip addresses. IPv4 only for now.
1659 my( $self, $field ) = @_;
1660 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1661 or return "Illegal (IP address) $field: ". $self->getfield($field);
1662 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1663 $self->setfield($field, "$1.$2.$3.$4");
1669 Check/untaint ip addresses. IPv4 only for now. May be null.
1674 my( $self, $field ) = @_;
1675 if ( $self->getfield($field) =~ /^()$/ ) {
1676 $self->setfield($field,'');
1679 $self->ut_ip($field);
1683 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
1685 Check/untaint coordinates.
1686 Accepts the following forms:
1696 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
1697 The latter form (that is, the MMM are thousands of minutes) is
1698 assumed if the "MMM" is exactly three digits or two digits > 59.
1700 To be safe, just use the DDD.DDDDD form.
1702 If LOWER or UPPER are specified, then the coordinate is checked
1703 for lower and upper bounds, respectively.
1709 my ($self, $field) = (shift, shift);
1711 my $lower = shift if scalar(@_);
1712 my $upper = shift if scalar(@_);
1713 my $coord = $self->getfield($field);
1714 my $neg = $coord =~ s/^(-)//;
1716 my ($d, $m, $s) = (0, 0, 0);
1719 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
1720 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
1721 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
1723 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
1726 return "Invalid (coordinate with minutes > 59) $field: "
1727 . $self->getfield($field);
1730 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
1732 if (defined($lower) and ($coord < $lower)) {
1733 return "Invalid (coordinate < $lower) $field: "
1734 . $self->getfield($field);;
1737 if (defined($upper) and ($coord > $upper)) {
1738 return "Invalid (coordinate > $upper) $field: "
1739 . $self->getfield($field);;
1742 $self->setfield($field, $coord);
1746 return "Invalid (coordinate) $field: " . $self->getfield($field);
1750 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
1752 Same as ut_coord, except optionally null.
1758 my ($self, $field) = (shift, shift);
1760 if ($self->getfield($field) =~ /^$/) {
1763 return $self->ut_coord($field, @_);
1769 =item ut_domain COLUMN
1771 Check/untaint host and domain names.
1776 my( $self, $field ) = @_;
1777 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1778 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1779 or return "Illegal (domain) $field: ". $self->getfield($field);
1780 $self->setfield($field,$1);
1784 =item ut_name COLUMN
1786 Check/untaint proper names; allows alphanumerics, spaces and the following
1787 punctuation: , . - '
1794 my( $self, $field ) = @_;
1795 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1796 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1797 $self->setfield($field,$1);
1803 Check/untaint zip codes.
1807 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1810 my( $self, $field, $country ) = @_;
1812 if ( $country eq 'US' ) {
1814 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1815 or return gettext('illegal_zip'). " $field for country $country: ".
1816 $self->getfield($field);
1817 $self->setfield($field, $1);
1819 } elsif ( $country eq 'CA' ) {
1821 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1822 or return gettext('illegal_zip'). " $field for country $country: ".
1823 $self->getfield($field);
1824 $self->setfield($field, "$1 $2");
1828 if ( $self->getfield($field) =~ /^\s*$/
1829 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1832 $self->setfield($field,'');
1834 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1835 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1836 $self->setfield($field,$1);
1844 =item ut_country COLUMN
1846 Check/untaint country codes. Country names are changed to codes, if possible -
1847 see L<Locale::Country>.
1852 my( $self, $field ) = @_;
1853 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1854 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1855 && country2code($1) ) {
1856 $self->setfield($field,uc(country2code($1)));
1859 $self->getfield($field) =~ /^(\w\w)$/
1860 or return "Illegal (country) $field: ". $self->getfield($field);
1861 $self->setfield($field,uc($1));
1865 =item ut_anything COLUMN
1867 Untaints arbitrary data. Be careful.
1872 my( $self, $field ) = @_;
1873 $self->getfield($field) =~ /^(.*)$/s
1874 or return "Illegal $field: ". $self->getfield($field);
1875 $self->setfield($field,$1);
1879 =item ut_enum COLUMN CHOICES_ARRAYREF
1881 Check/untaint a column, supplying all possible choices, like the "enum" type.
1886 my( $self, $field, $choices ) = @_;
1887 foreach my $choice ( @$choices ) {
1888 if ( $self->getfield($field) eq $choice ) {
1889 $self->setfield($choice);
1893 return "Illegal (enum) field $field: ". $self->getfield($field);
1896 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1898 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1899 on the column first.
1903 sub ut_foreign_key {
1904 my( $self, $field, $table, $foreign ) = @_;
1905 qsearchs($table, { $foreign => $self->getfield($field) })
1906 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1907 " in $table.$foreign";
1911 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1913 Like ut_foreign_key, except the null value is also allowed.
1917 sub ut_foreign_keyn {
1918 my( $self, $field, $table, $foreign ) = @_;
1919 $self->getfield($field)
1920 ? $self->ut_foreign_key($field, $table, $foreign)
1924 =item ut_agentnum_acl
1926 Checks this column as an agentnum, taking into account the current users's
1931 sub ut_agentnum_acl {
1932 my( $self, $field, $null_acl ) = @_;
1934 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1935 return "Illegal agentnum: $error" if $error;
1937 my $curuser = $FS::CurrentUser::CurrentUser;
1939 if ( $self->$field() ) {
1941 return "Access denied"
1942 unless $curuser->agentnum($self->$field());
1946 return "Access denied"
1947 unless $curuser->access_right($null_acl);
1955 =item virtual_fields [ TABLE ]
1957 Returns a list of virtual fields defined for the table. This should not
1958 be exported, and should only be called as an instance or class method.
1962 sub virtual_fields {
1965 $table = $self->table or confess "virtual_fields called on non-table";
1967 confess "Unknown table $table" unless dbdef->table($table);
1969 return () unless dbdef->table('part_virtual_field');
1971 unless ( $virtual_fields_cache{$table} ) {
1972 my $query = 'SELECT name from part_virtual_field ' .
1973 "WHERE dbtable = '$table'";
1975 my $result = $dbh->selectcol_arrayref($query);
1976 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1978 $virtual_fields_cache{$table} = $result;
1981 @{$virtual_fields_cache{$table}};
1986 =item fields [ TABLE ]
1988 This is a wrapper for real_fields and virtual_fields. Code that called
1989 fields before should probably continue to call fields.
1994 my $something = shift;
1996 if($something->isa('FS::Record')) {
1997 $table = $something->table;
1999 $table = $something;
2000 $something = "FS::$table";
2002 return (real_fields($table), $something->virtual_fields());
2005 =item pvf FIELD_NAME
2007 Returns the FS::part_virtual_field object corresponding to a field in the
2008 record (specified by FIELD_NAME).
2013 my ($self, $name) = (shift, shift);
2015 if(grep /^$name$/, $self->virtual_fields) {
2016 return qsearchs('part_virtual_field', { dbtable => $self->table,
2022 =item vfieldpart_hashref TABLE
2024 Returns a hashref of virtual field names and vfieldparts applicable to the given
2029 sub vfieldpart_hashref {
2031 my $table = $self->table;
2033 return {} unless dbdef->table('part_virtual_field');
2036 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2037 "dbtable = '$table'";
2038 my $sth = $dbh->prepare($statement);
2039 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2040 return { map { $_->{name}, $_->{vfieldpart} }
2041 @{$sth->fetchall_arrayref({})} };
2045 =item encrypt($value)
2047 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2049 Returns the encrypted string.
2051 You should generally not have to worry about calling this, as the system handles this for you.
2056 my ($self, $value) = @_;
2059 if ($conf->exists('encryption')) {
2060 if ($self->is_encrypted($value)) {
2061 # Return the original value if it isn't plaintext.
2062 $encrypted = $value;
2065 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2066 # RSA doesn't like the empty string so let's pack it up
2067 # The database doesn't like the RSA data so uuencode it
2068 my $length = length($value)+1;
2069 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2071 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2078 =item is_encrypted($value)
2080 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2086 my ($self, $value) = @_;
2087 # Possible Bug - Some work may be required here....
2089 if ($value =~ /^M/ && length($value) > 80) {
2096 =item decrypt($value)
2098 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2100 You should generally not have to worry about calling this, as the system handles this for you.
2105 my ($self,$value) = @_;
2106 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2107 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2109 if (ref($rsa_decrypt) =~ /::RSA/) {
2110 my $encrypted = unpack ("u*", $value);
2111 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2112 if ($@) {warn "Decryption Failed"};
2120 #Initialize the Module
2121 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2123 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2124 $rsa_module = $conf->config('encryptionmodule');
2128 eval ("require $rsa_module"); # No need to import the namespace
2131 # Initialize Encryption
2132 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2133 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2134 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2137 # Intitalize Decryption
2138 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2139 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2140 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2144 =item h_search ACTION
2146 Given an ACTION, either "insert", or "delete", returns the appropriate history
2147 record corresponding to this record, if any.
2152 my( $self, $action ) = @_;
2154 my $table = $self->table;
2157 my $primary_key = dbdef->table($table)->primary_key;
2160 'table' => "h_$table",
2161 'hashref' => { $primary_key => $self->$primary_key(),
2162 'history_action' => $action,
2170 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2171 appropriate history record corresponding to this record, if any.
2176 my($self, $action) = @_;
2177 my $h = $self->h_search($action);
2178 $h ? $h->history_date : '';
2187 =item real_fields [ TABLE ]
2189 Returns a list of the real columns in the specified table. Called only by
2190 fields() and other subroutines elsewhere in FS::Record.
2197 my($table_obj) = dbdef->table($table);
2198 confess "Unknown table $table" unless $table_obj;
2199 $table_obj->columns;
2202 =item _quote VALUE, TABLE, COLUMN
2204 This is an internal function used to construct SQL statements. It returns
2205 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2206 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2211 my($value, $table, $column) = @_;
2212 my $column_obj = dbdef->table($table)->column($column);
2213 my $column_type = $column_obj->type;
2214 my $nullable = $column_obj->null;
2216 warn " $table.$column: $value ($column_type".
2217 ( $nullable ? ' NULL' : ' NOT NULL' ).
2218 ")\n" if $DEBUG > 2;
2220 if ( $value eq '' && $nullable ) {
2222 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2223 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2226 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2227 ! $column_type =~ /(char|binary|text)$/i ) {
2236 This is deprecated. Don't use it.
2238 It returns a hash-type list with the fields of this record's table set true.
2243 carp "warning: hfields is deprecated";
2246 foreach (fields($table)) {
2255 "$_: ". $self->getfield($_). "|"
2256 } (fields($self->table)) );
2259 sub DESTROY { return; }
2263 # #use Carp qw(cluck);
2264 # #cluck "DESTROYING $self";
2265 # warn "DESTROYING $self";
2269 # return ! eval { join('',@_), kill 0; 1; };
2272 =item str2time_sql [ DRIVER_NAME ]
2274 Returns a function to convert to unix time based on database type, such as
2275 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2276 the str2time_sql_closing method to return a closing string rather than just
2277 using a closing parenthesis as previously suggested.
2279 You can pass an optional driver name such as "Pg", "mysql" or
2280 $dbh->{Driver}->{Name} to return a function for that database instead of
2281 the current database.
2286 my $driver = shift || driver_name;
2288 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2289 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2291 warn "warning: unknown database type $driver; guessing how to convert ".
2292 "dates to UNIX timestamps";
2293 return 'EXTRACT(EPOCH FROM ';
2297 =item str2time_sql_closing [ DRIVER_NAME ]
2299 Returns the closing suffix of a function to convert to unix time based on
2300 database type, such as ")::integer" for Pg or ")" for mysql.
2302 You can pass an optional driver name such as "Pg", "mysql" or
2303 $dbh->{Driver}->{Name} to return a function for that database instead of
2304 the current database.
2308 sub str2time_sql_closing {
2309 my $driver = shift || driver_name;
2311 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2319 This module should probably be renamed, since much of the functionality is
2320 of general use. It is not completely unlike Adapter::DBI (see below).
2322 Exported qsearch and qsearchs should be deprecated in favor of method calls
2323 (against an FS::Record object like the old search and searchs that qsearch
2324 and qsearchs were on top of.)
2326 The whole fields / hfields mess should be removed.
2328 The various WHERE clauses should be subroutined.
2330 table string should be deprecated in favor of DBIx::DBSchema::Table.
2332 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2333 true maps to the database (and WHERE clauses) would also help.
2335 The ut_ methods should ask the dbdef for a default length.
2337 ut_sqltype (like ut_varchar) should all be defined
2339 A fallback check method should be provided which uses the dbdef.
2341 The ut_money method assumes money has two decimal digits.
2343 The Pg money kludge in the new method only strips `$'.
2345 The ut_phonen method only checks US-style phone numbers.
2347 The _quote function should probably use ut_float instead of a regex.
2349 All the subroutines probably should be methods, here or elsewhere.
2351 Probably should borrow/use some dbdef methods where appropriate (like sub
2354 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2355 or allow it to be set. Working around it is ugly any way around - DBI should
2356 be fixed. (only affects RDBMS which return uppercase column names)
2358 ut_zip should take an optional country like ut_phone.
2362 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2364 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.