4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
7 $nowarn_identical $no_update_diff $no_check_foreign
10 use Carp qw(carp cluck croak confess);
11 use Scalar::Util qw( blessed );
12 use File::CounterFile;
14 use DBI qw(:sql_types);
15 use DBIx::DBSchema 0.33;
16 use FS::UID qw(dbh getotaker datasrc driver_name);
18 use FS::Schema qw(dbdef);
20 use FS::Msgcat qw(gettext);
21 #use FS::Conf; #dependency loop bs, in install_callback below instead
23 use FS::part_virtual_field;
29 #export dbdef for now... everything else expects to find it here
30 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
31 str2time_sql str2time_sql_closing );
36 $nowarn_identical = 0;
38 $no_check_foreign = 0;
45 FS::UID->install_callback( sub {
48 $conf = FS::Conf->new;
49 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
55 FS::Record - Database record objects
60 use FS::Record qw(dbh fields qsearch qsearchs);
62 $record = new FS::Record 'table', \%hash;
63 $record = new FS::Record 'table', { 'column' => 'value', ... };
65 $record = qsearchs FS::Record 'table', \%hash;
66 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
67 @records = qsearch FS::Record 'table', \%hash;
68 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
70 $table = $record->table;
71 $dbdef_table = $record->dbdef_table;
73 $value = $record->get('column');
74 $value = $record->getfield('column');
75 $value = $record->column;
77 $record->set( 'column' => 'value' );
78 $record->setfield( 'column' => 'value' );
79 $record->column('value');
81 %hash = $record->hash;
83 $hashref = $record->hashref;
85 $error = $record->insert;
87 $error = $record->delete;
89 $error = $new_record->replace($old_record);
91 # external use deprecated - handled by the database (at least for Pg, mysql)
92 $value = $record->unique('column');
94 $error = $record->ut_float('column');
95 $error = $record->ut_floatn('column');
96 $error = $record->ut_number('column');
97 $error = $record->ut_numbern('column');
98 $error = $record->ut_snumber('column');
99 $error = $record->ut_snumbern('column');
100 $error = $record->ut_money('column');
101 $error = $record->ut_text('column');
102 $error = $record->ut_textn('column');
103 $error = $record->ut_alpha('column');
104 $error = $record->ut_alphan('column');
105 $error = $record->ut_phonen('column');
106 $error = $record->ut_anything('column');
107 $error = $record->ut_name('column');
109 $quoted_value = _quote($value,'table','field');
112 $fields = hfields('table');
113 if ( $fields->{Field} ) { # etc.
115 @fields = fields 'table'; #as a subroutine
116 @fields = $record->fields; #as a method call
121 (Mostly) object-oriented interface to database records. Records are currently
122 implemented on top of DBI. FS::Record is intended as a base class for
123 table-specific classes to inherit from, i.e. FS::cust_main.
129 =item new [ TABLE, ] HASHREF
131 Creates a new record. It doesn't store it in the database, though. See
132 L<"insert"> for that.
134 Note that the object stores this hash reference, not a distinct copy of the
135 hash it points to. You can ask the object for a copy with the I<hash>
138 TABLE can only be omitted when a dervived class overrides the table method.
144 my $class = ref($proto) || $proto;
146 bless ($self, $class);
148 unless ( defined ( $self->table ) ) {
149 $self->{'Table'} = shift;
150 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
153 $self->{'Hash'} = shift;
155 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
156 $self->{'Hash'}{$field}='';
159 $self->_rebless if $self->can('_rebless');
161 $self->{'modified'} = 0;
163 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
170 my $class = ref($proto) || $proto;
172 bless ($self, $class);
174 $self->{'Table'} = shift unless defined ( $self->table );
176 my $hashref = $self->{'Hash'} = shift;
178 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
179 my $obj = $cache->cache->{$hashref->{$cache->key}};
180 $obj->_cache($hashref, $cache) if $obj->can('_cache');
183 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
190 my $class = ref($proto) || $proto;
192 bless ($self, $class);
193 if ( defined $self->table ) {
194 cluck "create constructor is deprecated, use new!";
197 croak "FS::Record::create called (not from a subclass)!";
201 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
203 Searches the database for all records matching (at least) the key/value pairs
204 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
205 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
208 The preferred usage is to pass a hash reference of named parameters:
210 my @records = qsearch( {
211 'table' => 'table_name',
212 'hashref' => { 'field' => 'value'
213 'field' => { 'op' => '<',
218 #these are optional...
220 'extra_sql' => 'AND field ',
221 'order_by' => 'ORDER BY something',
222 #'cache_obj' => '', #optional
223 'addl_from' => 'LEFT JOIN othtable USING ( field )',
228 Much code still uses old-style positional parameters, this is also probably
229 fine in the common case where there are only two parameters:
231 my @records = qsearch( 'table', { 'field' => 'value' } );
233 ###oops, argh, FS::Record::new only lets us create database fields.
234 #Normal behaviour if SELECT is not specified is `*', as in
235 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
236 #feature where you can specify SELECT - remember, the objects returned,
237 #although blessed into the appropriate `FS::TABLE' package, will only have the
238 #fields you specify. This might have unwanted results if you then go calling
239 #regular FS::TABLE methods
244 my %TYPE = (); #for debugging
247 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
249 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
251 $stable = $opt->{'table'} or die "table name is required";
252 $record = $opt->{'hashref'} || {};
253 $select = $opt->{'select'} || '*';
254 $extra_sql = $opt->{'extra_sql'} || '';
255 $order_by = $opt->{'order_by'} || '';
256 $cache = $opt->{'cache_obj'} || '';
257 $addl_from = $opt->{'addl_from'} || '';
258 $debug = $opt->{'debug'} || '';
260 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
264 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
266 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
270 my $table = $cache ? $cache->table : $stable;
271 my $dbdef_table = dbdef->table($table)
272 or die "No schema for table $table found - ".
273 "do you need to run freeside-upgrade?";
274 my $pkey = $dbdef_table->primary_key;
276 my @real_fields = grep exists($record->{$_}), real_fields($table);
278 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
279 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
281 cluck "warning: FS::$table not loaded; virtual fields not searchable";
282 @virtual_fields = ();
285 my $statement = "SELECT $select FROM $stable";
286 $statement .= " $addl_from" if $addl_from;
287 if ( @real_fields or @virtual_fields ) {
288 $statement .= ' WHERE '. join(' AND ',
289 get_real_fields($table, $record, \@real_fields) ,
290 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
294 $statement .= " $extra_sql" if defined($extra_sql);
295 $statement .= " $order_by" if defined($order_by);
297 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
298 my $sth = $dbh->prepare($statement)
299 or croak "$dbh->errstr doing $statement";
304 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
307 my $value = $record->{$field};
308 $value = $value->{'value'} if ref($value);
309 my $type = dbdef->table($table)->column($field)->type;
311 my $TYPE = SQL_VARCHAR;
312 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
315 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
316 } elsif ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/)
317 || ( $type =~ /(real|float4)/i
318 && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/
326 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
328 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
331 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
335 # $sth->execute( map $record->{$_},
336 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
337 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
339 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
341 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
342 @virtual_fields = "FS::$table"->virtual_fields;
344 cluck "warning: FS::$table not loaded; virtual fields not returned either";
345 @virtual_fields = ();
349 tie %result, "Tie::IxHash";
350 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
351 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
352 %result = map { $_->{$pkey}, $_ } @stuff;
354 @result{@stuff} = @stuff;
359 if ( keys(%result) and @virtual_fields ) {
361 "SELECT virtual_field.recnum, part_virtual_field.name, ".
362 "virtual_field.value ".
363 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
364 "WHERE part_virtual_field.dbtable = '$table' AND ".
365 "virtual_field.recnum IN (".
366 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
367 join(q!', '!, @virtual_fields) . "')";
368 warn "[debug]$me $statement\n" if $DEBUG > 1;
369 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
370 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
372 foreach (@{ $sth->fetchall_arrayref({}) }) {
373 my $recnum = $_->{recnum};
374 my $name = $_->{name};
375 my $value = $_->{value};
376 if (exists($result{$recnum})) {
377 $result{$recnum}->{$name} = $value;
382 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
383 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
384 #derivied class didn't override new method, so this optimization is safe
387 new_or_cached( "FS::$table", { %{$_} }, $cache )
391 new( "FS::$table", { %{$_} } )
395 #okay, its been tested
396 # warn "untested code (class FS::$table uses custom new method)";
398 eval 'FS::'. $table. '->new( { %{$_} } )';
402 # Check for encrypted fields and decrypt them.
403 ## only in the local copy, not the cached object
404 if ( $conf && $conf->exists('encryption') # $conf doesn't exist when doing
405 # the initial search for
407 && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
408 foreach my $record (@return) {
409 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
410 # Set it directly... This may cause a problem in the future...
411 $record->setfield($field, $record->decrypt($record->getfield($field)));
416 cluck "warning: FS::$table not loaded; returning FS::Record objects";
418 FS::Record->new( $table, { %{$_} } );
424 ## makes this easier to read
426 sub get_virtual_fields {
430 my $virtual_fields = shift;
436 if ( ref($record->{$_}) ) {
437 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
438 if ( uc($op) eq 'ILIKE' ) {
440 $record->{$_}{'value'} = lc($record->{$_}{'value'});
441 $column = "LOWER($_)";
443 $record->{$_} = $record->{$_}{'value'};
446 # ... EXISTS ( SELECT name, value FROM part_virtual_field
448 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
449 # WHERE recnum = svc_acct.svcnum
450 # AND (name, value) = ('egad', 'brain') )
452 my $value = $record->{$_};
456 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
457 "( SELECT part_virtual_field.name, virtual_field.value ".
458 "FROM part_virtual_field JOIN virtual_field ".
459 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
460 "WHERE virtual_field.recnum = ${table}.${pkey} ".
461 "AND part_virtual_field.name = '${column}'".
463 " AND virtual_field.value ${op} '${value}'"
467 } @{ $virtual_fields } ) ;
470 sub get_real_fields {
473 my $real_fields = shift;
475 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
481 if ( ref($record->{$_}) ) {
482 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
483 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
484 if ( uc($op) eq 'ILIKE' ) {
486 $record->{$_}{'value'} = lc($record->{$_}{'value'});
487 $column = "LOWER($_)";
489 $record->{$_} = $record->{$_}{'value'}
492 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
494 if ( driver_name eq 'Pg' ) {
495 my $type = dbdef->table($table)->column($column)->type;
496 if ( $type =~ /(int|(big)?serial)/i ) {
497 qq-( $column IS NULL )-;
499 qq-( $column IS NULL OR $column = '' )-;
502 qq-( $column IS NULL OR $column = "" )-;
504 } elsif ( $op eq '!=' ) {
505 if ( driver_name eq 'Pg' ) {
506 my $type = dbdef->table($table)->column($column)->type;
507 if ( $type =~ /(int|(big)?serial)/i ) {
508 qq-( $column IS NOT NULL )-;
510 qq-( $column IS NOT NULL AND $column != '' )-;
513 qq-( $column IS NOT NULL AND $column != "" )-;
516 if ( driver_name eq 'Pg' ) {
517 qq-( $column $op '' )-;
519 qq-( $column $op "" )-;
525 } @{ $real_fields } );
528 =item by_key PRIMARY_KEY_VALUE
530 This is a class method that returns the record with the given primary key
531 value. This method is only useful in FS::Record subclasses. For example:
533 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
537 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
542 my ($class, $pkey_value) = @_;
544 my $table = $class->table
545 or croak "No table for $class found";
547 my $dbdef_table = dbdef->table($table)
548 or die "No schema for table $table found - ".
549 "do you need to create it or run dbdef-create?";
550 my $pkey = $dbdef_table->primary_key
551 or die "No primary key for table $table";
553 return qsearchs($table, { $pkey => $pkey_value });
556 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
558 Experimental JOINed search method. Using this method, you can execute a
559 single SELECT spanning multiple tables, and cache the results for subsequent
560 method calls. Interface will almost definately change in an incompatible
568 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
569 my $cache = FS::SearchCache->new( $ptable, $pkey );
572 grep { !$saw{$_->getfield($pkey)}++ }
573 qsearch($table, $record, $select, $extra_sql, $cache )
577 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
579 Same as qsearch, except that if more than one record matches, it B<carp>s but
580 returns the first. If this happens, you either made a logic error in asking
581 for a single item, or your data is corrupted.
585 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
587 my(@result) = qsearch(@_);
588 cluck "warning: Multiple records in scalar search ($table)"
589 if scalar(@result) > 1;
590 #should warn more vehemently if the search was on a primary key?
591 scalar(@result) ? ($result[0]) : ();
602 Returns the table name.
607 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
614 Returns the DBIx::DBSchema::Table object for the table.
620 my($table)=$self->table;
621 dbdef->table($table);
626 Returns the primary key for the table.
632 my $pkey = $self->dbdef_table->primary_key;
635 =item get, getfield COLUMN
637 Returns the value of the column/field/key COLUMN.
642 my($self,$field) = @_;
643 # to avoid "Use of unitialized value" errors
644 if ( defined ( $self->{Hash}->{$field} ) ) {
645 $self->{Hash}->{$field};
655 =item set, setfield COLUMN, VALUE
657 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
662 my($self,$field,$value) = @_;
663 $self->{'modified'} = 1;
664 $self->{'Hash'}->{$field} = $value;
671 =item AUTLOADED METHODS
673 $record->column is a synonym for $record->get('column');
675 $record->column('value') is a synonym for $record->set('column','value');
682 my($field)=$AUTOLOAD;
684 if ( defined($value) ) {
685 confess "errant AUTOLOAD $field for $self (arg $value)"
686 unless blessed($self) && $self->can('setfield');
687 $self->setfield($field,$value);
689 confess "errant AUTOLOAD $field for $self (no args)"
690 unless blessed($self) && $self->can('getfield');
691 $self->getfield($field);
697 # my $field = $AUTOLOAD;
699 # if ( defined($_[1]) ) {
700 # $_[0]->setfield($field, $_[1]);
702 # $_[0]->getfield($field);
708 Returns a list of the column/value pairs, usually for assigning to a new hash.
710 To make a distinct duplicate of an FS::Record object, you can do:
712 $new = new FS::Record ( $old->table, { $old->hash } );
718 confess $self. ' -> hash: Hash attribute is undefined'
719 unless defined($self->{'Hash'});
720 %{ $self->{'Hash'} };
725 Returns a reference to the column/value hash. This may be deprecated in the
726 future; if there's a reason you can't just use the autoloaded or get/set
738 Returns true if any of this object's values have been modified with set (or via
739 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
749 =item select_for_update
751 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
756 sub select_for_update {
758 my $primary_key = $self->primary_key;
761 'table' => $self->table,
762 'hashref' => { $primary_key => $self->$primary_key() },
763 'extra_sql' => 'FOR UPDATE',
769 Inserts this record to the database. If there is an error, returns the error,
770 otherwise returns false.
778 warn "$self -> insert" if $DEBUG;
780 my $error = $self->check;
781 return $error if $error;
783 #single-field unique keys are given a value if false
784 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
785 foreach ( $self->dbdef_table->unique_singles) {
786 $self->unique($_) unless $self->getfield($_);
789 #and also the primary key, if the database isn't going to
790 my $primary_key = $self->dbdef_table->primary_key;
792 if ( $primary_key ) {
793 my $col = $self->dbdef_table->column($primary_key);
796 uc($col->type) =~ /^(BIG)?SERIAL\d?/
797 || ( driver_name eq 'Pg'
798 && defined($col->default)
799 && $col->default =~ /^nextval\(/i
801 || ( driver_name eq 'mysql'
802 && defined($col->local)
803 && $col->local =~ /AUTO_INCREMENT/i
805 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
808 my $table = $self->table;
810 # Encrypt before the database
811 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
812 && scalar( eval '@FS::'. $table . '::encrypted_fields')
813 && $conf->exists('encryption')
815 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
816 $self->{'saved'} = $self->getfield($field);
817 $self->setfield($field, $self->encrypt($self->getfield($field)));
821 #false laziness w/delete
823 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
826 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
829 my $statement = "INSERT INTO $table ";
830 if ( @real_fields ) {
833 join( ', ', @real_fields ).
835 join( ', ', @values ).
839 $statement .= 'DEFAULT VALUES';
841 warn "[debug]$me $statement\n" if $DEBUG > 1;
842 my $sth = dbh->prepare($statement) or return dbh->errstr;
844 local $SIG{HUP} = 'IGNORE';
845 local $SIG{INT} = 'IGNORE';
846 local $SIG{QUIT} = 'IGNORE';
847 local $SIG{TERM} = 'IGNORE';
848 local $SIG{TSTP} = 'IGNORE';
849 local $SIG{PIPE} = 'IGNORE';
851 $sth->execute or return $sth->errstr;
853 # get inserted id from the database, if applicable & needed
854 if ( $db_seq && ! $self->getfield($primary_key) ) {
855 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
859 if ( driver_name eq 'Pg' ) {
861 #my $oid = $sth->{'pg_oid_status'};
862 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
864 my $default = $self->dbdef_table->column($primary_key)->default;
865 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
866 dbh->rollback if $FS::UID::AutoCommit;
867 return "can't parse $table.$primary_key default value".
868 " for sequence name: $default";
872 my $i_sql = "SELECT currval('$sequence')";
873 my $i_sth = dbh->prepare($i_sql) or do {
874 dbh->rollback if $FS::UID::AutoCommit;
877 $i_sth->execute() or do { #$i_sth->execute($oid)
878 dbh->rollback if $FS::UID::AutoCommit;
879 return $i_sth->errstr;
881 $insertid = $i_sth->fetchrow_arrayref->[0];
883 } elsif ( driver_name eq 'mysql' ) {
885 $insertid = dbh->{'mysql_insertid'};
886 # work around mysql_insertid being null some of the time, ala RT :/
887 unless ( $insertid ) {
888 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
889 "using SELECT LAST_INSERT_ID();";
890 my $i_sql = "SELECT LAST_INSERT_ID()";
891 my $i_sth = dbh->prepare($i_sql) or do {
892 dbh->rollback if $FS::UID::AutoCommit;
895 $i_sth->execute or do {
896 dbh->rollback if $FS::UID::AutoCommit;
897 return $i_sth->errstr;
899 $insertid = $i_sth->fetchrow_arrayref->[0];
904 dbh->rollback if $FS::UID::AutoCommit;
905 return "don't know how to retreive inserted ids from ". driver_name.
906 ", try using counterfiles (maybe run dbdef-create?)";
910 $self->setfield($primary_key, $insertid);
915 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
916 $self->virtual_fields;
917 if (@virtual_fields) {
918 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
920 my $vfieldpart = $self->vfieldpart_hashref;
922 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
925 my $v_sth = dbh->prepare($v_statement) or do {
926 dbh->rollback if $FS::UID::AutoCommit;
930 foreach (keys(%v_values)) {
931 $v_sth->execute($self->getfield($primary_key),
935 dbh->rollback if $FS::UID::AutoCommit;
936 return $v_sth->errstr;
943 if ( defined dbdef->table('h_'. $table) ) {
944 my $h_statement = $self->_h_statement('insert');
945 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
946 $h_sth = dbh->prepare($h_statement) or do {
947 dbh->rollback if $FS::UID::AutoCommit;
953 $h_sth->execute or return $h_sth->errstr if $h_sth;
955 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
957 # Now that it has been saved, reset the encrypted fields so that $new
959 foreach my $field (keys %{$saved}) {
960 $self->setfield($field, $saved->{$field});
968 Depriciated (use insert instead).
973 cluck "warning: FS::Record::add deprecated!";
974 insert @_; #call method in this scope
979 Delete this record from the database. If there is an error, returns the error,
980 otherwise returns false.
987 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
989 $self->getfield($_) eq ''
990 #? "( $_ IS NULL OR $_ = \"\" )"
991 ? ( driver_name eq 'Pg'
993 : "( $_ IS NULL OR $_ = \"\" )"
995 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
996 } ( $self->dbdef_table->primary_key )
997 ? ( $self->dbdef_table->primary_key)
998 : real_fields($self->table)
1000 warn "[debug]$me $statement\n" if $DEBUG > 1;
1001 my $sth = dbh->prepare($statement) or return dbh->errstr;
1004 if ( defined dbdef->table('h_'. $self->table) ) {
1005 my $h_statement = $self->_h_statement('delete');
1006 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1007 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1012 my $primary_key = $self->dbdef_table->primary_key;
1015 my $vfp = $self->vfieldpart_hashref;
1016 foreach($self->virtual_fields) {
1017 next if $self->getfield($_) eq '';
1018 unless(@del_vfields) {
1019 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1020 $v_sth = dbh->prepare($st) or return dbh->errstr;
1022 push @del_vfields, $_;
1025 local $SIG{HUP} = 'IGNORE';
1026 local $SIG{INT} = 'IGNORE';
1027 local $SIG{QUIT} = 'IGNORE';
1028 local $SIG{TERM} = 'IGNORE';
1029 local $SIG{TSTP} = 'IGNORE';
1030 local $SIG{PIPE} = 'IGNORE';
1032 my $rc = $sth->execute or return $sth->errstr;
1033 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1034 $h_sth->execute or return $h_sth->errstr if $h_sth;
1035 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1036 or return $v_sth->errstr
1037 foreach (@del_vfields);
1039 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1041 #no need to needlessly destoy the data either (causes problems actually)
1042 #undef $self; #no need to keep object!
1049 Depriciated (use delete instead).
1054 cluck "warning: FS::Record::del deprecated!";
1055 &delete(@_); #call method in this scope
1058 =item replace OLD_RECORD
1060 Replace the OLD_RECORD with this one in the database. If there is an error,
1061 returns the error, otherwise returns false.
1066 my ($new, $old) = (shift, shift);
1068 $old = $new->replace_old unless defined($old);
1070 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1072 if ( $new->can('replace_check') ) {
1073 my $error = $new->replace_check($old);
1074 return $error if $error;
1077 return "Records not in same table!" unless $new->table eq $old->table;
1079 my $primary_key = $old->dbdef_table->primary_key;
1080 return "Can't change primary key $primary_key ".
1081 'from '. $old->getfield($primary_key).
1082 ' to ' . $new->getfield($primary_key)
1084 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1086 my $error = $new->check;
1087 return $error if $error;
1089 # Encrypt for replace
1091 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1092 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1093 $saved->{$field} = $new->getfield($field);
1094 $new->setfield($field, $new->encrypt($new->getfield($field)));
1098 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1099 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1100 ? ($_, $new->getfield($_)) : () } $old->fields;
1102 unless (keys(%diff) || $no_update_diff ) {
1103 carp "[warning]$me $new -> replace $old: records identical"
1104 unless $nowarn_identical;
1108 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1110 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1111 } real_fields($old->table)
1116 if ( $old->getfield($_) eq '' ) {
1118 #false laziness w/qsearch
1119 if ( driver_name eq 'Pg' ) {
1120 my $type = $old->dbdef_table->column($_)->type;
1121 if ( $type =~ /(int|(big)?serial)/i ) {
1124 qq-( $_ IS NULL OR $_ = '' )-;
1127 qq-( $_ IS NULL OR $_ = "" )-;
1131 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1134 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1137 warn "[debug]$me $statement\n" if $DEBUG > 1;
1138 my $sth = dbh->prepare($statement) or return dbh->errstr;
1141 if ( defined dbdef->table('h_'. $old->table) ) {
1142 my $h_old_statement = $old->_h_statement('replace_old');
1143 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1144 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1150 if ( defined dbdef->table('h_'. $new->table) ) {
1151 my $h_new_statement = $new->_h_statement('replace_new');
1152 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1153 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1158 # For virtual fields we have three cases with different SQL
1159 # statements: add, replace, delete
1163 my (@add_vfields, @rep_vfields, @del_vfields);
1164 my $vfp = $old->vfieldpart_hashref;
1165 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1166 if($diff{$_} eq '') {
1168 unless(@del_vfields) {
1169 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1170 "AND vfieldpart = ?";
1171 warn "[debug]$me $st\n" if $DEBUG > 2;
1172 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1174 push @del_vfields, $_;
1175 } elsif($old->getfield($_) eq '') {
1177 unless(@add_vfields) {
1178 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1180 warn "[debug]$me $st\n" if $DEBUG > 2;
1181 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1183 push @add_vfields, $_;
1186 unless(@rep_vfields) {
1187 my $st = "UPDATE virtual_field SET value = ? ".
1188 "WHERE recnum = ? AND vfieldpart = ?";
1189 warn "[debug]$me $st\n" if $DEBUG > 2;
1190 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1192 push @rep_vfields, $_;
1196 local $SIG{HUP} = 'IGNORE';
1197 local $SIG{INT} = 'IGNORE';
1198 local $SIG{QUIT} = 'IGNORE';
1199 local $SIG{TERM} = 'IGNORE';
1200 local $SIG{TSTP} = 'IGNORE';
1201 local $SIG{PIPE} = 'IGNORE';
1203 my $rc = $sth->execute or return $sth->errstr;
1204 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1205 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1206 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1208 $v_del_sth->execute($old->getfield($primary_key),
1210 or return $v_del_sth->errstr
1211 foreach(@del_vfields);
1213 $v_add_sth->execute($new->getfield($_),
1214 $old->getfield($primary_key),
1216 or return $v_add_sth->errstr
1217 foreach(@add_vfields);
1219 $v_rep_sth->execute($new->getfield($_),
1220 $old->getfield($primary_key),
1222 or return $v_rep_sth->errstr
1223 foreach(@rep_vfields);
1225 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1227 # Now that it has been saved, reset the encrypted fields so that $new
1228 # can still be used.
1229 foreach my $field (keys %{$saved}) {
1230 $new->setfield($field, $saved->{$field});
1238 my( $self ) = shift;
1239 warn "[$me] replace called with no arguments; autoloading old record\n"
1242 my $primary_key = $self->dbdef_table->primary_key;
1243 if ( $primary_key ) {
1244 $self->by_key( $self->$primary_key() ) #this is what's returned
1245 or croak "can't find ". $self->table. ".$primary_key ".
1246 $self->$primary_key();
1248 croak $self->table. " has no primary key; pass old record as argument";
1255 Depriciated (use replace instead).
1260 cluck "warning: FS::Record::rep deprecated!";
1261 replace @_; #call method in this scope
1266 Checks virtual fields (using check_blocks). Subclasses should still provide
1267 a check method to validate real fields, foreign keys, etc., and call this
1268 method via $self->SUPER::check.
1270 (FIXME: Should this method try to make sure that it I<is> being called from
1271 a subclass's check method, to keep the current semantics as far as possible?)
1276 #confess "FS::Record::check not implemented; supply one in subclass!";
1279 foreach my $field ($self->virtual_fields) {
1280 for ($self->getfield($field)) {
1281 # See notes on check_block in FS::part_virtual_field.
1282 eval $self->pvf($field)->check_block;
1284 #this is bad, probably want to follow the stack backtrace up and see
1286 my $err = "Fatal error checking $field for $self";
1288 return "$err (see log for backtrace): $@";
1291 $self->setfield($field, $_);
1298 my( $self, $action, $time ) = @_;
1303 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1304 real_fields($self->table);
1307 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1308 # You can see if it changed by the paymask...
1309 if ($conf && $conf->exists('encryption') ) {
1310 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1312 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1314 "INSERT INTO h_". $self->table. " ( ".
1315 join(', ', qw(history_date history_user history_action), @fields ).
1317 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1324 B<Warning>: External use is B<deprecated>.
1326 Replaces COLUMN in record with a unique number, using counters in the
1327 filesystem. Used by the B<insert> method on single-field unique columns
1328 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1329 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1331 Returns the new value.
1336 my($self,$field) = @_;
1337 my($table)=$self->table;
1339 croak "Unique called on field $field, but it is ",
1340 $self->getfield($field),
1342 if $self->getfield($field);
1344 #warn "table $table is tainted" if is_tainted($table);
1345 #warn "field $field is tainted" if is_tainted($field);
1347 my($counter) = new File::CounterFile "$table.$field",0;
1349 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1351 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1354 my $index = $counter->inc;
1355 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1357 $index =~ /^(\d*)$/;
1360 $self->setfield($field,$index);
1364 =item ut_float COLUMN
1366 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1367 null. If there is an error, returns the error, otherwise returns false.
1372 my($self,$field)=@_ ;
1373 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1374 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1375 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1376 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1377 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1378 $self->setfield($field,$1);
1381 =item ut_floatn COLUMN
1383 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1384 null. If there is an error, returns the error, otherwise returns false.
1388 #false laziness w/ut_ipn
1390 my( $self, $field ) = @_;
1391 if ( $self->getfield($field) =~ /^()$/ ) {
1392 $self->setfield($field,'');
1395 $self->ut_float($field);
1399 =item ut_sfloat COLUMN
1401 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1402 May not be null. If there is an error, returns the error, otherwise returns
1408 my($self,$field)=@_ ;
1409 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1410 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1411 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1412 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1413 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1414 $self->setfield($field,$1);
1417 =item ut_sfloatn COLUMN
1419 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1420 null. If there is an error, returns the error, otherwise returns false.
1425 my( $self, $field ) = @_;
1426 if ( $self->getfield($field) =~ /^()$/ ) {
1427 $self->setfield($field,'');
1430 $self->ut_sfloat($field);
1434 =item ut_snumber COLUMN
1436 Check/untaint signed numeric data (whole numbers). If there is an error,
1437 returns the error, otherwise returns false.
1442 my($self, $field) = @_;
1443 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1444 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1445 $self->setfield($field, "$1$2");
1449 =item ut_snumbern COLUMN
1451 Check/untaint signed numeric data (whole numbers). If there is an error,
1452 returns the error, otherwise returns false.
1457 my($self, $field) = @_;
1458 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1459 or return "Illegal (numeric) $field: ". $self->getfield($field);
1461 return "Illegal (numeric) $field: ". $self->getfield($field)
1464 $self->setfield($field, "$1$2");
1468 =item ut_number COLUMN
1470 Check/untaint simple numeric data (whole numbers). May not be null. If there
1471 is an error, returns the error, otherwise returns false.
1476 my($self,$field)=@_;
1477 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1478 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1479 $self->setfield($field,$1);
1483 =item ut_numbern COLUMN
1485 Check/untaint simple numeric data (whole numbers). May be null. If there is
1486 an error, returns the error, otherwise returns false.
1491 my($self,$field)=@_;
1492 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1493 or return "Illegal (numeric) $field: ". $self->getfield($field);
1494 $self->setfield($field,$1);
1498 =item ut_money COLUMN
1500 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1501 is an error, returns the error, otherwise returns false.
1506 my($self,$field)=@_;
1507 $self->setfield($field, 0) if $self->getfield($field) eq '';
1508 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1509 or return "Illegal (money) $field: ". $self->getfield($field);
1510 #$self->setfield($field, "$1$2$3" || 0);
1511 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1515 =item ut_text COLUMN
1517 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1518 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1519 May not be null. If there is an error, returns the error, otherwise returns
1525 my($self,$field)=@_;
1526 #warn "msgcat ". \&msgcat. "\n";
1527 #warn "notexist ". \¬exist. "\n";
1528 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1529 $self->getfield($field)
1530 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1531 or return gettext('illegal_or_empty_text'). " $field: ".
1532 $self->getfield($field);
1533 $self->setfield($field,$1);
1537 =item ut_textn COLUMN
1539 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1540 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1541 May be null. If there is an error, returns the error, otherwise returns false.
1546 my($self,$field)=@_;
1547 $self->getfield($field)
1548 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1549 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1550 $self->setfield($field,$1);
1554 =item ut_alpha COLUMN
1556 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1557 an error, returns the error, otherwise returns false.
1562 my($self,$field)=@_;
1563 $self->getfield($field) =~ /^(\w+)$/
1564 or return "Illegal or empty (alphanumeric) $field: ".
1565 $self->getfield($field);
1566 $self->setfield($field,$1);
1570 =item ut_alpha COLUMN
1572 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1573 error, returns the error, otherwise returns false.
1578 my($self,$field)=@_;
1579 $self->getfield($field) =~ /^(\w*)$/
1580 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1581 $self->setfield($field,$1);
1585 =item ut_alpha_lower COLUMN
1587 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1588 there is an error, returns the error, otherwise returns false.
1592 sub ut_alpha_lower {
1593 my($self,$field)=@_;
1594 $self->getfield($field) =~ /[[:upper:]]/
1595 and return "Uppercase characters are not permitted in $field";
1596 $self->ut_alpha($field);
1599 =item ut_phonen COLUMN [ COUNTRY ]
1601 Check/untaint phone numbers. May be null. If there is an error, returns
1602 the error, otherwise returns false.
1604 Takes an optional two-letter ISO country code; without it or with unsupported
1605 countries, ut_phonen simply calls ut_alphan.
1610 my( $self, $field, $country ) = @_;
1611 return $self->ut_alphan($field) unless defined $country;
1612 my $phonen = $self->getfield($field);
1613 if ( $phonen eq '' ) {
1614 $self->setfield($field,'');
1615 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1617 $phonen = $conf->config('cust_main-default_areacode').$phonen
1618 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
1619 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1620 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1621 $phonen = "$1-$2-$3";
1622 $phonen .= " x$4" if $4;
1623 $self->setfield($field,$phonen);
1625 warn "warning: don't know how to check phone numbers for country $country";
1626 return $self->ut_textn($field);
1633 Check/untaint hexadecimal values.
1638 my($self, $field) = @_;
1639 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1640 or return "Illegal (hex) $field: ". $self->getfield($field);
1641 $self->setfield($field, uc($1));
1645 =item ut_hexn COLUMN
1647 Check/untaint hexadecimal values. May be null.
1652 my($self, $field) = @_;
1653 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1654 or return "Illegal (hex) $field: ". $self->getfield($field);
1655 $self->setfield($field, uc($1));
1660 Check/untaint ip addresses. IPv4 only for now.
1665 my( $self, $field ) = @_;
1666 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1667 or return "Illegal (IP address) $field: ". $self->getfield($field);
1668 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1669 $self->setfield($field, "$1.$2.$3.$4");
1675 Check/untaint ip addresses. IPv4 only for now. May be null.
1680 my( $self, $field ) = @_;
1681 if ( $self->getfield($field) =~ /^()$/ ) {
1682 $self->setfield($field,'');
1685 $self->ut_ip($field);
1689 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
1691 Check/untaint coordinates.
1692 Accepts the following forms:
1702 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
1703 The latter form (that is, the MMM are thousands of minutes) is
1704 assumed if the "MMM" is exactly three digits or two digits > 59.
1706 To be safe, just use the DDD.DDDDD form.
1708 If LOWER or UPPER are specified, then the coordinate is checked
1709 for lower and upper bounds, respectively.
1715 my ($self, $field) = (shift, shift);
1717 my $lower = shift if scalar(@_);
1718 my $upper = shift if scalar(@_);
1719 my $coord = $self->getfield($field);
1720 my $neg = $coord =~ s/^(-)//;
1722 my ($d, $m, $s) = (0, 0, 0);
1725 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
1726 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
1727 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
1729 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
1732 return "Invalid (coordinate with minutes > 59) $field: "
1733 . $self->getfield($field);
1736 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
1738 if (defined($lower) and ($coord < $lower)) {
1739 return "Invalid (coordinate < $lower) $field: "
1740 . $self->getfield($field);;
1743 if (defined($upper) and ($coord > $upper)) {
1744 return "Invalid (coordinate > $upper) $field: "
1745 . $self->getfield($field);;
1748 $self->setfield($field, $coord);
1752 return "Invalid (coordinate) $field: " . $self->getfield($field);
1756 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
1758 Same as ut_coord, except optionally null.
1764 my ($self, $field) = (shift, shift);
1766 if ($self->getfield($field) =~ /^$/) {
1769 return $self->ut_coord($field, @_);
1775 =item ut_domain COLUMN
1777 Check/untaint host and domain names.
1782 my( $self, $field ) = @_;
1783 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1784 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1785 or return "Illegal (domain) $field: ". $self->getfield($field);
1786 $self->setfield($field,$1);
1790 =item ut_name COLUMN
1792 Check/untaint proper names; allows alphanumerics, spaces and the following
1793 punctuation: , . - '
1800 my( $self, $field ) = @_;
1801 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1802 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1803 $self->setfield($field,$1);
1809 Check/untaint zip codes.
1813 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1816 my( $self, $field, $country ) = @_;
1818 if ( $country eq 'US' ) {
1820 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1821 or return gettext('illegal_zip'). " $field for country $country: ".
1822 $self->getfield($field);
1823 $self->setfield($field, $1);
1825 } elsif ( $country eq 'CA' ) {
1827 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1828 or return gettext('illegal_zip'). " $field for country $country: ".
1829 $self->getfield($field);
1830 $self->setfield($field, "$1 $2");
1834 if ( $self->getfield($field) =~ /^\s*$/
1835 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1838 $self->setfield($field,'');
1840 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1841 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1842 $self->setfield($field,$1);
1850 =item ut_country COLUMN
1852 Check/untaint country codes. Country names are changed to codes, if possible -
1853 see L<Locale::Country>.
1858 my( $self, $field ) = @_;
1859 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1860 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1861 && country2code($1) ) {
1862 $self->setfield($field,uc(country2code($1)));
1865 $self->getfield($field) =~ /^(\w\w)$/
1866 or return "Illegal (country) $field: ". $self->getfield($field);
1867 $self->setfield($field,uc($1));
1871 =item ut_anything COLUMN
1873 Untaints arbitrary data. Be careful.
1878 my( $self, $field ) = @_;
1879 $self->getfield($field) =~ /^(.*)$/s
1880 or return "Illegal $field: ". $self->getfield($field);
1881 $self->setfield($field,$1);
1885 =item ut_enum COLUMN CHOICES_ARRAYREF
1887 Check/untaint a column, supplying all possible choices, like the "enum" type.
1892 my( $self, $field, $choices ) = @_;
1893 foreach my $choice ( @$choices ) {
1894 if ( $self->getfield($field) eq $choice ) {
1895 $self->setfield($choice);
1899 return "Illegal (enum) field $field: ". $self->getfield($field);
1902 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1904 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1905 on the column first.
1909 sub ut_foreign_key {
1910 my( $self, $field, $table, $foreign ) = @_;
1911 return '' if $no_check_foreign;
1912 qsearchs($table, { $foreign => $self->getfield($field) })
1913 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1914 " in $table.$foreign";
1918 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1920 Like ut_foreign_key, except the null value is also allowed.
1924 sub ut_foreign_keyn {
1925 my( $self, $field, $table, $foreign ) = @_;
1926 $self->getfield($field)
1927 ? $self->ut_foreign_key($field, $table, $foreign)
1931 =item ut_agentnum_acl
1933 Checks this column as an agentnum, taking into account the current users's
1938 sub ut_agentnum_acl {
1939 my( $self, $field, $null_acl ) = @_;
1941 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1942 return "Illegal agentnum: $error" if $error;
1944 my $curuser = $FS::CurrentUser::CurrentUser;
1946 if ( $self->$field() ) {
1948 return "Access denied"
1949 unless $curuser->agentnum($self->$field());
1953 return "Access denied"
1954 unless $curuser->access_right($null_acl);
1962 =item virtual_fields [ TABLE ]
1964 Returns a list of virtual fields defined for the table. This should not
1965 be exported, and should only be called as an instance or class method.
1969 sub virtual_fields {
1972 $table = $self->table or confess "virtual_fields called on non-table";
1974 confess "Unknown table $table" unless dbdef->table($table);
1976 return () unless dbdef->table('part_virtual_field');
1978 unless ( $virtual_fields_cache{$table} ) {
1979 my $query = 'SELECT name from part_virtual_field ' .
1980 "WHERE dbtable = '$table'";
1982 my $result = $dbh->selectcol_arrayref($query);
1983 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1985 $virtual_fields_cache{$table} = $result;
1988 @{$virtual_fields_cache{$table}};
1993 =item fields [ TABLE ]
1995 This is a wrapper for real_fields and virtual_fields. Code that called
1996 fields before should probably continue to call fields.
2001 my $something = shift;
2003 if($something->isa('FS::Record')) {
2004 $table = $something->table;
2006 $table = $something;
2007 $something = "FS::$table";
2009 return (real_fields($table), $something->virtual_fields());
2012 =item pvf FIELD_NAME
2014 Returns the FS::part_virtual_field object corresponding to a field in the
2015 record (specified by FIELD_NAME).
2020 my ($self, $name) = (shift, shift);
2022 if(grep /^$name$/, $self->virtual_fields) {
2023 return qsearchs('part_virtual_field', { dbtable => $self->table,
2029 =item vfieldpart_hashref TABLE
2031 Returns a hashref of virtual field names and vfieldparts applicable to the given
2036 sub vfieldpart_hashref {
2038 my $table = $self->table;
2040 return {} unless dbdef->table('part_virtual_field');
2043 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2044 "dbtable = '$table'";
2045 my $sth = $dbh->prepare($statement);
2046 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2047 return { map { $_->{name}, $_->{vfieldpart} }
2048 @{$sth->fetchall_arrayref({})} };
2052 =item encrypt($value)
2054 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2056 Returns the encrypted string.
2058 You should generally not have to worry about calling this, as the system handles this for you.
2063 my ($self, $value) = @_;
2066 if ($conf->exists('encryption')) {
2067 if ($self->is_encrypted($value)) {
2068 # Return the original value if it isn't plaintext.
2069 $encrypted = $value;
2072 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2073 # RSA doesn't like the empty string so let's pack it up
2074 # The database doesn't like the RSA data so uuencode it
2075 my $length = length($value)+1;
2076 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2078 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2085 =item is_encrypted($value)
2087 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2093 my ($self, $value) = @_;
2094 # Possible Bug - Some work may be required here....
2096 if ($value =~ /^M/ && length($value) > 80) {
2103 =item decrypt($value)
2105 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2107 You should generally not have to worry about calling this, as the system handles this for you.
2112 my ($self,$value) = @_;
2113 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2114 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2116 if (ref($rsa_decrypt) =~ /::RSA/) {
2117 my $encrypted = unpack ("u*", $value);
2118 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2119 if ($@) {warn "Decryption Failed"};
2127 #Initialize the Module
2128 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2130 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2131 $rsa_module = $conf->config('encryptionmodule');
2135 eval ("require $rsa_module"); # No need to import the namespace
2138 # Initialize Encryption
2139 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2140 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2141 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2144 # Intitalize Decryption
2145 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2146 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2147 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2151 =item h_search ACTION
2153 Given an ACTION, either "insert", or "delete", returns the appropriate history
2154 record corresponding to this record, if any.
2159 my( $self, $action ) = @_;
2161 my $table = $self->table;
2164 my $primary_key = dbdef->table($table)->primary_key;
2167 'table' => "h_$table",
2168 'hashref' => { $primary_key => $self->$primary_key(),
2169 'history_action' => $action,
2177 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2178 appropriate history record corresponding to this record, if any.
2183 my($self, $action) = @_;
2184 my $h = $self->h_search($action);
2185 $h ? $h->history_date : '';
2194 =item real_fields [ TABLE ]
2196 Returns a list of the real columns in the specified table. Called only by
2197 fields() and other subroutines elsewhere in FS::Record.
2204 my($table_obj) = dbdef->table($table);
2205 confess "Unknown table $table" unless $table_obj;
2206 $table_obj->columns;
2209 =item _quote VALUE, TABLE, COLUMN
2211 This is an internal function used to construct SQL statements. It returns
2212 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2213 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2218 my($value, $table, $column) = @_;
2219 my $column_obj = dbdef->table($table)->column($column);
2220 my $column_type = $column_obj->type;
2221 my $nullable = $column_obj->null;
2223 warn " $table.$column: $value ($column_type".
2224 ( $nullable ? ' NULL' : ' NOT NULL' ).
2225 ")\n" if $DEBUG > 2;
2227 if ( $value eq '' && $nullable ) {
2229 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2230 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2233 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2234 ! $column_type =~ /(char|binary|text)$/i ) {
2243 This is deprecated. Don't use it.
2245 It returns a hash-type list with the fields of this record's table set true.
2250 carp "warning: hfields is deprecated";
2253 foreach (fields($table)) {
2262 "$_: ". $self->getfield($_). "|"
2263 } (fields($self->table)) );
2266 sub DESTROY { return; }
2270 # #use Carp qw(cluck);
2271 # #cluck "DESTROYING $self";
2272 # warn "DESTROYING $self";
2276 # return ! eval { join('',@_), kill 0; 1; };
2279 =item str2time_sql [ DRIVER_NAME ]
2281 Returns a function to convert to unix time based on database type, such as
2282 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2283 the str2time_sql_closing method to return a closing string rather than just
2284 using a closing parenthesis as previously suggested.
2286 You can pass an optional driver name such as "Pg", "mysql" or
2287 $dbh->{Driver}->{Name} to return a function for that database instead of
2288 the current database.
2293 my $driver = shift || driver_name;
2295 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2296 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2298 warn "warning: unknown database type $driver; guessing how to convert ".
2299 "dates to UNIX timestamps";
2300 return 'EXTRACT(EPOCH FROM ';
2304 =item str2time_sql_closing [ DRIVER_NAME ]
2306 Returns the closing suffix of a function to convert to unix time based on
2307 database type, such as ")::integer" for Pg or ")" for mysql.
2309 You can pass an optional driver name such as "Pg", "mysql" or
2310 $dbh->{Driver}->{Name} to return a function for that database instead of
2311 the current database.
2315 sub str2time_sql_closing {
2316 my $driver = shift || driver_name;
2318 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2326 This module should probably be renamed, since much of the functionality is
2327 of general use. It is not completely unlike Adapter::DBI (see below).
2329 Exported qsearch and qsearchs should be deprecated in favor of method calls
2330 (against an FS::Record object like the old search and searchs that qsearch
2331 and qsearchs were on top of.)
2333 The whole fields / hfields mess should be removed.
2335 The various WHERE clauses should be subroutined.
2337 table string should be deprecated in favor of DBIx::DBSchema::Table.
2339 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2340 true maps to the database (and WHERE clauses) would also help.
2342 The ut_ methods should ask the dbdef for a default length.
2344 ut_sqltype (like ut_varchar) should all be defined
2346 A fallback check method should be provided which uses the dbdef.
2348 The ut_money method assumes money has two decimal digits.
2350 The Pg money kludge in the new method only strips `$'.
2352 The ut_phonen method only checks US-style phone numbers.
2354 The _quote function should probably use ut_float instead of a regex.
2356 All the subroutines probably should be methods, here or elsewhere.
2358 Probably should borrow/use some dbdef methods where appropriate (like sub
2361 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2362 or allow it to be set. Working around it is ugly any way around - DBI should
2363 be fixed. (only affects RDBMS which return uppercase column names)
2365 ut_zip should take an optional country like ut_phone.
2369 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2371 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.