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
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;
811 # Encrypt before the database
812 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . '::encrypted_fields')) {
813 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
814 $self->{'saved'} = $self->getfield($field);
815 $self->setfield($field, $self->encrypt($self->getfield($field)));
820 #false laziness w/delete
822 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
825 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
828 my $statement = "INSERT INTO $table ";
829 if ( @real_fields ) {
832 join( ', ', @real_fields ).
834 join( ', ', @values ).
838 $statement .= 'DEFAULT VALUES';
840 warn "[debug]$me $statement\n" if $DEBUG > 1;
841 my $sth = dbh->prepare($statement) or return dbh->errstr;
843 local $SIG{HUP} = 'IGNORE';
844 local $SIG{INT} = 'IGNORE';
845 local $SIG{QUIT} = 'IGNORE';
846 local $SIG{TERM} = 'IGNORE';
847 local $SIG{TSTP} = 'IGNORE';
848 local $SIG{PIPE} = 'IGNORE';
850 $sth->execute or return $sth->errstr;
852 # get inserted id from the database, if applicable & needed
853 if ( $db_seq && ! $self->getfield($primary_key) ) {
854 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
858 if ( driver_name eq 'Pg' ) {
860 #my $oid = $sth->{'pg_oid_status'};
861 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
863 my $default = $self->dbdef_table->column($primary_key)->default;
864 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
865 dbh->rollback if $FS::UID::AutoCommit;
866 return "can't parse $table.$primary_key default value".
867 " for sequence name: $default";
871 my $i_sql = "SELECT currval('$sequence')";
872 my $i_sth = dbh->prepare($i_sql) or do {
873 dbh->rollback if $FS::UID::AutoCommit;
876 $i_sth->execute() or do { #$i_sth->execute($oid)
877 dbh->rollback if $FS::UID::AutoCommit;
878 return $i_sth->errstr;
880 $insertid = $i_sth->fetchrow_arrayref->[0];
882 } elsif ( driver_name eq 'mysql' ) {
884 $insertid = dbh->{'mysql_insertid'};
885 # work around mysql_insertid being null some of the time, ala RT :/
886 unless ( $insertid ) {
887 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
888 "using SELECT LAST_INSERT_ID();";
889 my $i_sql = "SELECT LAST_INSERT_ID()";
890 my $i_sth = dbh->prepare($i_sql) or do {
891 dbh->rollback if $FS::UID::AutoCommit;
894 $i_sth->execute or do {
895 dbh->rollback if $FS::UID::AutoCommit;
896 return $i_sth->errstr;
898 $insertid = $i_sth->fetchrow_arrayref->[0];
903 dbh->rollback if $FS::UID::AutoCommit;
904 return "don't know how to retreive inserted ids from ". driver_name.
905 ", try using counterfiles (maybe run dbdef-create?)";
909 $self->setfield($primary_key, $insertid);
914 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
915 $self->virtual_fields;
916 if (@virtual_fields) {
917 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
919 my $vfieldpart = $self->vfieldpart_hashref;
921 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
924 my $v_sth = dbh->prepare($v_statement) or do {
925 dbh->rollback if $FS::UID::AutoCommit;
929 foreach (keys(%v_values)) {
930 $v_sth->execute($self->getfield($primary_key),
934 dbh->rollback if $FS::UID::AutoCommit;
935 return $v_sth->errstr;
942 if ( defined dbdef->table('h_'. $table) ) {
943 my $h_statement = $self->_h_statement('insert');
944 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
945 $h_sth = dbh->prepare($h_statement) or do {
946 dbh->rollback if $FS::UID::AutoCommit;
952 $h_sth->execute or return $h_sth->errstr if $h_sth;
954 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
956 # Now that it has been saved, reset the encrypted fields so that $new
958 foreach my $field (keys %{$saved}) {
959 $self->setfield($field, $saved->{$field});
967 Depriciated (use insert instead).
972 cluck "warning: FS::Record::add deprecated!";
973 insert @_; #call method in this scope
978 Delete this record from the database. If there is an error, returns the error,
979 otherwise returns false.
986 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
988 $self->getfield($_) eq ''
989 #? "( $_ IS NULL OR $_ = \"\" )"
990 ? ( driver_name eq 'Pg'
992 : "( $_ IS NULL OR $_ = \"\" )"
994 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
995 } ( $self->dbdef_table->primary_key )
996 ? ( $self->dbdef_table->primary_key)
997 : real_fields($self->table)
999 warn "[debug]$me $statement\n" if $DEBUG > 1;
1000 my $sth = dbh->prepare($statement) or return dbh->errstr;
1003 if ( defined dbdef->table('h_'. $self->table) ) {
1004 my $h_statement = $self->_h_statement('delete');
1005 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1006 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1011 my $primary_key = $self->dbdef_table->primary_key;
1014 my $vfp = $self->vfieldpart_hashref;
1015 foreach($self->virtual_fields) {
1016 next if $self->getfield($_) eq '';
1017 unless(@del_vfields) {
1018 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1019 $v_sth = dbh->prepare($st) or return dbh->errstr;
1021 push @del_vfields, $_;
1024 local $SIG{HUP} = 'IGNORE';
1025 local $SIG{INT} = 'IGNORE';
1026 local $SIG{QUIT} = 'IGNORE';
1027 local $SIG{TERM} = 'IGNORE';
1028 local $SIG{TSTP} = 'IGNORE';
1029 local $SIG{PIPE} = 'IGNORE';
1031 my $rc = $sth->execute or return $sth->errstr;
1032 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1033 $h_sth->execute or return $h_sth->errstr if $h_sth;
1034 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1035 or return $v_sth->errstr
1036 foreach (@del_vfields);
1038 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1040 #no need to needlessly destoy the data either (causes problems actually)
1041 #undef $self; #no need to keep object!
1048 Depriciated (use delete instead).
1053 cluck "warning: FS::Record::del deprecated!";
1054 &delete(@_); #call method in this scope
1057 =item replace OLD_RECORD
1059 Replace the OLD_RECORD with this one in the database. If there is an error,
1060 returns the error, otherwise returns false.
1065 my ($new, $old) = (shift, shift);
1067 $old = $new->replace_old unless defined($old);
1069 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1071 if ( $new->can('replace_check') ) {
1072 my $error = $new->replace_check($old);
1073 return $error if $error;
1076 return "Records not in same table!" unless $new->table eq $old->table;
1078 my $primary_key = $old->dbdef_table->primary_key;
1079 return "Can't change primary key $primary_key ".
1080 'from '. $old->getfield($primary_key).
1081 ' to ' . $new->getfield($primary_key)
1083 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1085 my $error = $new->check;
1086 return $error if $error;
1088 # Encrypt for replace
1090 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1091 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1092 $saved->{$field} = $new->getfield($field);
1093 $new->setfield($field, $new->encrypt($new->getfield($field)));
1097 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1098 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1099 ? ($_, $new->getfield($_)) : () } $old->fields;
1101 unless (keys(%diff) || $no_update_diff ) {
1102 carp "[warning]$me $new -> replace $old: records identical"
1103 unless $nowarn_identical;
1107 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1109 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1110 } real_fields($old->table)
1115 if ( $old->getfield($_) eq '' ) {
1117 #false laziness w/qsearch
1118 if ( driver_name eq 'Pg' ) {
1119 my $type = $old->dbdef_table->column($_)->type;
1120 if ( $type =~ /(int|(big)?serial)/i ) {
1123 qq-( $_ IS NULL OR $_ = '' )-;
1126 qq-( $_ IS NULL OR $_ = "" )-;
1130 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1133 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1136 warn "[debug]$me $statement\n" if $DEBUG > 1;
1137 my $sth = dbh->prepare($statement) or return dbh->errstr;
1140 if ( defined dbdef->table('h_'. $old->table) ) {
1141 my $h_old_statement = $old->_h_statement('replace_old');
1142 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1143 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1149 if ( defined dbdef->table('h_'. $new->table) ) {
1150 my $h_new_statement = $new->_h_statement('replace_new');
1151 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1152 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1157 # For virtual fields we have three cases with different SQL
1158 # statements: add, replace, delete
1162 my (@add_vfields, @rep_vfields, @del_vfields);
1163 my $vfp = $old->vfieldpart_hashref;
1164 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1165 if($diff{$_} eq '') {
1167 unless(@del_vfields) {
1168 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1169 "AND vfieldpart = ?";
1170 warn "[debug]$me $st\n" if $DEBUG > 2;
1171 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1173 push @del_vfields, $_;
1174 } elsif($old->getfield($_) eq '') {
1176 unless(@add_vfields) {
1177 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1179 warn "[debug]$me $st\n" if $DEBUG > 2;
1180 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1182 push @add_vfields, $_;
1185 unless(@rep_vfields) {
1186 my $st = "UPDATE virtual_field SET value = ? ".
1187 "WHERE recnum = ? AND vfieldpart = ?";
1188 warn "[debug]$me $st\n" if $DEBUG > 2;
1189 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1191 push @rep_vfields, $_;
1195 local $SIG{HUP} = 'IGNORE';
1196 local $SIG{INT} = 'IGNORE';
1197 local $SIG{QUIT} = 'IGNORE';
1198 local $SIG{TERM} = 'IGNORE';
1199 local $SIG{TSTP} = 'IGNORE';
1200 local $SIG{PIPE} = 'IGNORE';
1202 my $rc = $sth->execute or return $sth->errstr;
1203 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1204 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1205 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1207 $v_del_sth->execute($old->getfield($primary_key),
1209 or return $v_del_sth->errstr
1210 foreach(@del_vfields);
1212 $v_add_sth->execute($new->getfield($_),
1213 $old->getfield($primary_key),
1215 or return $v_add_sth->errstr
1216 foreach(@add_vfields);
1218 $v_rep_sth->execute($new->getfield($_),
1219 $old->getfield($primary_key),
1221 or return $v_rep_sth->errstr
1222 foreach(@rep_vfields);
1224 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1226 # Now that it has been saved, reset the encrypted fields so that $new
1227 # can still be used.
1228 foreach my $field (keys %{$saved}) {
1229 $new->setfield($field, $saved->{$field});
1237 my( $self ) = shift;
1238 warn "[$me] replace called with no arguments; autoloading old record\n"
1241 my $primary_key = $self->dbdef_table->primary_key;
1242 if ( $primary_key ) {
1243 $self->by_key( $self->$primary_key() ) #this is what's returned
1244 or croak "can't find ". $self->table. ".$primary_key ".
1245 $self->$primary_key();
1247 croak $self->table. " has no primary key; pass old record as argument";
1254 Depriciated (use replace instead).
1259 cluck "warning: FS::Record::rep deprecated!";
1260 replace @_; #call method in this scope
1265 Checks virtual fields (using check_blocks). Subclasses should still provide
1266 a check method to validate real fields, foreign keys, etc., and call this
1267 method via $self->SUPER::check.
1269 (FIXME: Should this method try to make sure that it I<is> being called from
1270 a subclass's check method, to keep the current semantics as far as possible?)
1275 #confess "FS::Record::check not implemented; supply one in subclass!";
1278 foreach my $field ($self->virtual_fields) {
1279 for ($self->getfield($field)) {
1280 # See notes on check_block in FS::part_virtual_field.
1281 eval $self->pvf($field)->check_block;
1283 #this is bad, probably want to follow the stack backtrace up and see
1285 my $err = "Fatal error checking $field for $self";
1287 return "$err (see log for backtrace): $@";
1290 $self->setfield($field, $_);
1297 my( $self, $action, $time ) = @_;
1302 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1303 real_fields($self->table);
1306 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1307 # You can see if it changed by the paymask...
1308 if ($conf->exists('encryption') ) {
1309 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1311 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1313 "INSERT INTO h_". $self->table. " ( ".
1314 join(', ', qw(history_date history_user history_action), @fields ).
1316 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1323 B<Warning>: External use is B<deprecated>.
1325 Replaces COLUMN in record with a unique number, using counters in the
1326 filesystem. Used by the B<insert> method on single-field unique columns
1327 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1328 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1330 Returns the new value.
1335 my($self,$field) = @_;
1336 my($table)=$self->table;
1338 croak "Unique called on field $field, but it is ",
1339 $self->getfield($field),
1341 if $self->getfield($field);
1343 #warn "table $table is tainted" if is_tainted($table);
1344 #warn "field $field is tainted" if is_tainted($field);
1346 my($counter) = new File::CounterFile "$table.$field",0;
1348 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1350 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1353 my $index = $counter->inc;
1354 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1356 $index =~ /^(\d*)$/;
1359 $self->setfield($field,$index);
1363 =item ut_float COLUMN
1365 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1366 null. If there is an error, returns the error, otherwise returns false.
1371 my($self,$field)=@_ ;
1372 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1373 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1374 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1375 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1376 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1377 $self->setfield($field,$1);
1380 =item ut_floatn COLUMN
1382 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1383 null. If there is an error, returns the error, otherwise returns false.
1387 #false laziness w/ut_ipn
1389 my( $self, $field ) = @_;
1390 if ( $self->getfield($field) =~ /^()$/ ) {
1391 $self->setfield($field,'');
1394 $self->ut_float($field);
1398 =item ut_sfloat COLUMN
1400 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1401 May not be null. If there is an error, returns the error, otherwise returns
1407 my($self,$field)=@_ ;
1408 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1409 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1410 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1411 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1412 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1413 $self->setfield($field,$1);
1416 =item ut_sfloatn COLUMN
1418 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1419 null. If there is an error, returns the error, otherwise returns false.
1424 my( $self, $field ) = @_;
1425 if ( $self->getfield($field) =~ /^()$/ ) {
1426 $self->setfield($field,'');
1429 $self->ut_sfloat($field);
1433 =item ut_snumber COLUMN
1435 Check/untaint signed numeric data (whole numbers). If there is an error,
1436 returns the error, otherwise returns false.
1441 my($self, $field) = @_;
1442 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1443 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1444 $self->setfield($field, "$1$2");
1448 =item ut_snumbern COLUMN
1450 Check/untaint signed numeric data (whole numbers). If there is an error,
1451 returns the error, otherwise returns false.
1456 my($self, $field) = @_;
1457 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1458 or return "Illegal (numeric) $field: ". $self->getfield($field);
1460 return "Illegal (numeric) $field: ". $self->getfield($field)
1463 $self->setfield($field, "$1$2");
1467 =item ut_number COLUMN
1469 Check/untaint simple numeric data (whole numbers). May not be null. If there
1470 is an error, returns the error, otherwise returns false.
1475 my($self,$field)=@_;
1476 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1477 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1478 $self->setfield($field,$1);
1482 =item ut_numbern COLUMN
1484 Check/untaint simple numeric data (whole numbers). May be null. If there is
1485 an error, returns the error, otherwise returns false.
1490 my($self,$field)=@_;
1491 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1492 or return "Illegal (numeric) $field: ". $self->getfield($field);
1493 $self->setfield($field,$1);
1497 =item ut_money COLUMN
1499 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1500 is an error, returns the error, otherwise returns false.
1505 my($self,$field)=@_;
1506 $self->setfield($field, 0) if $self->getfield($field) eq '';
1507 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1508 or return "Illegal (money) $field: ". $self->getfield($field);
1509 #$self->setfield($field, "$1$2$3" || 0);
1510 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1514 =item ut_text COLUMN
1516 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1517 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1518 May not be null. If there is an error, returns the error, otherwise returns
1524 my($self,$field)=@_;
1525 #warn "msgcat ". \&msgcat. "\n";
1526 #warn "notexist ". \¬exist. "\n";
1527 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1528 $self->getfield($field)
1529 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1530 or return gettext('illegal_or_empty_text'). " $field: ".
1531 $self->getfield($field);
1532 $self->setfield($field,$1);
1536 =item ut_textn COLUMN
1538 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1539 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1540 May be null. If there is an error, returns the error, otherwise returns false.
1545 my($self,$field)=@_;
1546 $self->getfield($field)
1547 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1548 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1549 $self->setfield($field,$1);
1553 =item ut_alpha COLUMN
1555 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1556 an error, returns the error, otherwise returns false.
1561 my($self,$field)=@_;
1562 $self->getfield($field) =~ /^(\w+)$/
1563 or return "Illegal or empty (alphanumeric) $field: ".
1564 $self->getfield($field);
1565 $self->setfield($field,$1);
1569 =item ut_alpha COLUMN
1571 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1572 error, returns the error, otherwise returns false.
1577 my($self,$field)=@_;
1578 $self->getfield($field) =~ /^(\w*)$/
1579 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1580 $self->setfield($field,$1);
1584 =item ut_alpha_lower COLUMN
1586 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
1587 there is an error, returns the error, otherwise returns false.
1591 sub ut_alpha_lower {
1592 my($self,$field)=@_;
1593 $self->getfield($field) =~ /[[:upper:]]/
1594 and return "Uppercase characters are not permitted in $field";
1595 $self->ut_alpha($field);
1598 =item ut_phonen COLUMN [ COUNTRY ]
1600 Check/untaint phone numbers. May be null. If there is an error, returns
1601 the error, otherwise returns false.
1603 Takes an optional two-letter ISO country code; without it or with unsupported
1604 countries, ut_phonen simply calls ut_alphan.
1609 my( $self, $field, $country ) = @_;
1610 return $self->ut_alphan($field) unless defined $country;
1611 my $phonen = $self->getfield($field);
1612 if ( $phonen eq '' ) {
1613 $self->setfield($field,'');
1614 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1616 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1617 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1618 $phonen = "$1-$2-$3";
1619 $phonen .= " x$4" if $4;
1620 $self->setfield($field,$phonen);
1622 warn "warning: don't know how to check phone numbers for country $country";
1623 return $self->ut_textn($field);
1630 Check/untaint hexadecimal values.
1635 my($self, $field) = @_;
1636 $self->getfield($field) =~ /^([\da-fA-F]+)$/
1637 or return "Illegal (hex) $field: ". $self->getfield($field);
1638 $self->setfield($field, uc($1));
1642 =item ut_hexn COLUMN
1644 Check/untaint hexadecimal values. May be null.
1649 my($self, $field) = @_;
1650 $self->getfield($field) =~ /^([\da-fA-F]*)$/
1651 or return "Illegal (hex) $field: ". $self->getfield($field);
1652 $self->setfield($field, uc($1));
1657 Check/untaint ip addresses. IPv4 only for now.
1662 my( $self, $field ) = @_;
1663 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1664 or return "Illegal (IP address) $field: ". $self->getfield($field);
1665 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1666 $self->setfield($field, "$1.$2.$3.$4");
1672 Check/untaint ip addresses. IPv4 only for now. May be null.
1677 my( $self, $field ) = @_;
1678 if ( $self->getfield($field) =~ /^()$/ ) {
1679 $self->setfield($field,'');
1682 $self->ut_ip($field);
1686 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
1688 Check/untaint coordinates.
1689 Accepts the following forms:
1699 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
1700 The latter form (that is, the MMM are thousands of minutes) is
1701 assumed if the "MMM" is exactly three digits or two digits > 59.
1703 To be safe, just use the DDD.DDDDD form.
1705 If LOWER or UPPER are specified, then the coordinate is checked
1706 for lower and upper bounds, respectively.
1712 my ($self, $field) = (shift, shift);
1714 my $lower = shift if scalar(@_);
1715 my $upper = shift if scalar(@_);
1716 my $coord = $self->getfield($field);
1717 my $neg = $coord =~ s/^(-)//;
1719 my ($d, $m, $s) = (0, 0, 0);
1722 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
1723 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
1724 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
1726 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
1729 return "Invalid (coordinate with minutes > 59) $field: "
1730 . $self->getfield($field);
1733 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
1735 if (defined($lower) and ($coord < $lower)) {
1736 return "Invalid (coordinate < $lower) $field: "
1737 . $self->getfield($field);;
1740 if (defined($upper) and ($coord > $upper)) {
1741 return "Invalid (coordinate > $upper) $field: "
1742 . $self->getfield($field);;
1745 $self->setfield($field, $coord);
1749 return "Invalid (coordinate) $field: " . $self->getfield($field);
1753 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
1755 Same as ut_coord, except optionally null.
1761 my ($self, $field) = (shift, shift);
1763 if ($self->getfield($field) =~ /^$/) {
1766 return $self->ut_coord($field, @_);
1772 =item ut_domain COLUMN
1774 Check/untaint host and domain names.
1779 my( $self, $field ) = @_;
1780 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1781 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1782 or return "Illegal (domain) $field: ". $self->getfield($field);
1783 $self->setfield($field,$1);
1787 =item ut_name COLUMN
1789 Check/untaint proper names; allows alphanumerics, spaces and the following
1790 punctuation: , . - '
1797 my( $self, $field ) = @_;
1798 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1799 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1800 $self->setfield($field,$1);
1806 Check/untaint zip codes.
1810 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
1813 my( $self, $field, $country ) = @_;
1815 if ( $country eq 'US' ) {
1817 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
1818 or return gettext('illegal_zip'). " $field for country $country: ".
1819 $self->getfield($field);
1820 $self->setfield($field, $1);
1822 } elsif ( $country eq 'CA' ) {
1824 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
1825 or return gettext('illegal_zip'). " $field for country $country: ".
1826 $self->getfield($field);
1827 $self->setfield($field, "$1 $2");
1831 if ( $self->getfield($field) =~ /^\s*$/
1832 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
1835 $self->setfield($field,'');
1837 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1838 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1839 $self->setfield($field,$1);
1847 =item ut_country COLUMN
1849 Check/untaint country codes. Country names are changed to codes, if possible -
1850 see L<Locale::Country>.
1855 my( $self, $field ) = @_;
1856 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1857 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1858 && country2code($1) ) {
1859 $self->setfield($field,uc(country2code($1)));
1862 $self->getfield($field) =~ /^(\w\w)$/
1863 or return "Illegal (country) $field: ". $self->getfield($field);
1864 $self->setfield($field,uc($1));
1868 =item ut_anything COLUMN
1870 Untaints arbitrary data. Be careful.
1875 my( $self, $field ) = @_;
1876 $self->getfield($field) =~ /^(.*)$/s
1877 or return "Illegal $field: ". $self->getfield($field);
1878 $self->setfield($field,$1);
1882 =item ut_enum COLUMN CHOICES_ARRAYREF
1884 Check/untaint a column, supplying all possible choices, like the "enum" type.
1889 my( $self, $field, $choices ) = @_;
1890 foreach my $choice ( @$choices ) {
1891 if ( $self->getfield($field) eq $choice ) {
1892 $self->setfield($choice);
1896 return "Illegal (enum) field $field: ". $self->getfield($field);
1899 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1901 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1902 on the column first.
1906 sub ut_foreign_key {
1907 my( $self, $field, $table, $foreign ) = @_;
1908 return '' if $no_check_foreign;
1909 qsearchs($table, { $foreign => $self->getfield($field) })
1910 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1911 " in $table.$foreign";
1915 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1917 Like ut_foreign_key, except the null value is also allowed.
1921 sub ut_foreign_keyn {
1922 my( $self, $field, $table, $foreign ) = @_;
1923 $self->getfield($field)
1924 ? $self->ut_foreign_key($field, $table, $foreign)
1928 =item ut_agentnum_acl
1930 Checks this column as an agentnum, taking into account the current users's
1935 sub ut_agentnum_acl {
1936 my( $self, $field, $null_acl ) = @_;
1938 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
1939 return "Illegal agentnum: $error" if $error;
1941 my $curuser = $FS::CurrentUser::CurrentUser;
1943 if ( $self->$field() ) {
1945 return "Access denied"
1946 unless $curuser->agentnum($self->$field());
1950 return "Access denied"
1951 unless $curuser->access_right($null_acl);
1959 =item virtual_fields [ TABLE ]
1961 Returns a list of virtual fields defined for the table. This should not
1962 be exported, and should only be called as an instance or class method.
1966 sub virtual_fields {
1969 $table = $self->table or confess "virtual_fields called on non-table";
1971 confess "Unknown table $table" unless dbdef->table($table);
1973 return () unless dbdef->table('part_virtual_field');
1975 unless ( $virtual_fields_cache{$table} ) {
1976 my $query = 'SELECT name from part_virtual_field ' .
1977 "WHERE dbtable = '$table'";
1979 my $result = $dbh->selectcol_arrayref($query);
1980 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1982 $virtual_fields_cache{$table} = $result;
1985 @{$virtual_fields_cache{$table}};
1990 =item fields [ TABLE ]
1992 This is a wrapper for real_fields and virtual_fields. Code that called
1993 fields before should probably continue to call fields.
1998 my $something = shift;
2000 if($something->isa('FS::Record')) {
2001 $table = $something->table;
2003 $table = $something;
2004 $something = "FS::$table";
2006 return (real_fields($table), $something->virtual_fields());
2009 =item pvf FIELD_NAME
2011 Returns the FS::part_virtual_field object corresponding to a field in the
2012 record (specified by FIELD_NAME).
2017 my ($self, $name) = (shift, shift);
2019 if(grep /^$name$/, $self->virtual_fields) {
2020 return qsearchs('part_virtual_field', { dbtable => $self->table,
2026 =item vfieldpart_hashref TABLE
2028 Returns a hashref of virtual field names and vfieldparts applicable to the given
2033 sub vfieldpart_hashref {
2035 my $table = $self->table;
2037 return {} unless dbdef->table('part_virtual_field');
2040 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2041 "dbtable = '$table'";
2042 my $sth = $dbh->prepare($statement);
2043 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2044 return { map { $_->{name}, $_->{vfieldpart} }
2045 @{$sth->fetchall_arrayref({})} };
2049 =item encrypt($value)
2051 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2053 Returns the encrypted string.
2055 You should generally not have to worry about calling this, as the system handles this for you.
2060 my ($self, $value) = @_;
2063 if ($conf->exists('encryption')) {
2064 if ($self->is_encrypted($value)) {
2065 # Return the original value if it isn't plaintext.
2066 $encrypted = $value;
2069 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2070 # RSA doesn't like the empty string so let's pack it up
2071 # The database doesn't like the RSA data so uuencode it
2072 my $length = length($value)+1;
2073 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2075 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2082 =item is_encrypted($value)
2084 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2090 my ($self, $value) = @_;
2091 # Possible Bug - Some work may be required here....
2093 if ($value =~ /^M/ && length($value) > 80) {
2100 =item decrypt($value)
2102 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2104 You should generally not have to worry about calling this, as the system handles this for you.
2109 my ($self,$value) = @_;
2110 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2111 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2113 if (ref($rsa_decrypt) =~ /::RSA/) {
2114 my $encrypted = unpack ("u*", $value);
2115 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2116 if ($@) {warn "Decryption Failed"};
2124 #Initialize the Module
2125 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2127 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2128 $rsa_module = $conf->config('encryptionmodule');
2132 eval ("require $rsa_module"); # No need to import the namespace
2135 # Initialize Encryption
2136 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2137 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2138 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2141 # Intitalize Decryption
2142 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2143 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2144 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2148 =item h_search ACTION
2150 Given an ACTION, either "insert", or "delete", returns the appropriate history
2151 record corresponding to this record, if any.
2156 my( $self, $action ) = @_;
2158 my $table = $self->table;
2161 my $primary_key = dbdef->table($table)->primary_key;
2164 'table' => "h_$table",
2165 'hashref' => { $primary_key => $self->$primary_key(),
2166 'history_action' => $action,
2174 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2175 appropriate history record corresponding to this record, if any.
2180 my($self, $action) = @_;
2181 my $h = $self->h_search($action);
2182 $h ? $h->history_date : '';
2191 =item real_fields [ TABLE ]
2193 Returns a list of the real columns in the specified table. Called only by
2194 fields() and other subroutines elsewhere in FS::Record.
2201 my($table_obj) = dbdef->table($table);
2202 confess "Unknown table $table" unless $table_obj;
2203 $table_obj->columns;
2206 =item _quote VALUE, TABLE, COLUMN
2208 This is an internal function used to construct SQL statements. It returns
2209 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2210 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2215 my($value, $table, $column) = @_;
2216 my $column_obj = dbdef->table($table)->column($column);
2217 my $column_type = $column_obj->type;
2218 my $nullable = $column_obj->null;
2220 warn " $table.$column: $value ($column_type".
2221 ( $nullable ? ' NULL' : ' NOT NULL' ).
2222 ")\n" if $DEBUG > 2;
2224 if ( $value eq '' && $nullable ) {
2226 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2227 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2230 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2231 ! $column_type =~ /(char|binary|text)$/i ) {
2240 This is deprecated. Don't use it.
2242 It returns a hash-type list with the fields of this record's table set true.
2247 carp "warning: hfields is deprecated";
2250 foreach (fields($table)) {
2259 "$_: ". $self->getfield($_). "|"
2260 } (fields($self->table)) );
2263 sub DESTROY { return; }
2267 # #use Carp qw(cluck);
2268 # #cluck "DESTROYING $self";
2269 # warn "DESTROYING $self";
2273 # return ! eval { join('',@_), kill 0; 1; };
2276 =item str2time_sql [ DRIVER_NAME ]
2278 Returns a function to convert to unix time based on database type, such as
2279 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2280 the str2time_sql_closing method to return a closing string rather than just
2281 using a closing parenthesis as previously suggested.
2283 You can pass an optional driver name such as "Pg", "mysql" or
2284 $dbh->{Driver}->{Name} to return a function for that database instead of
2285 the current database.
2290 my $driver = shift || driver_name;
2292 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2293 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2295 warn "warning: unknown database type $driver; guessing how to convert ".
2296 "dates to UNIX timestamps";
2297 return 'EXTRACT(EPOCH FROM ';
2301 =item str2time_sql_closing [ DRIVER_NAME ]
2303 Returns the closing suffix of a function to convert to unix time based on
2304 database type, such as ")::integer" for Pg or ")" for mysql.
2306 You can pass an optional driver name such as "Pg", "mysql" or
2307 $dbh->{Driver}->{Name} to return a function for that database instead of
2308 the current database.
2312 sub str2time_sql_closing {
2313 my $driver = shift || driver_name;
2315 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2323 This module should probably be renamed, since much of the functionality is
2324 of general use. It is not completely unlike Adapter::DBI (see below).
2326 Exported qsearch and qsearchs should be deprecated in favor of method calls
2327 (against an FS::Record object like the old search and searchs that qsearch
2328 and qsearchs were on top of.)
2330 The whole fields / hfields mess should be removed.
2332 The various WHERE clauses should be subroutined.
2334 table string should be deprecated in favor of DBIx::DBSchema::Table.
2336 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2337 true maps to the database (and WHERE clauses) would also help.
2339 The ut_ methods should ask the dbdef for a default length.
2341 ut_sqltype (like ut_varchar) should all be defined
2343 A fallback check method should be provided which uses the dbdef.
2345 The ut_money method assumes money has two decimal digits.
2347 The Pg money kludge in the new method only strips `$'.
2349 The ut_phonen method only checks US-style phone numbers.
2351 The _quote function should probably use ut_float instead of a regex.
2353 All the subroutines probably should be methods, here or elsewhere.
2355 Probably should borrow/use some dbdef methods where appropriate (like sub
2358 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2359 or allow it to be set. Working around it is ugly any way around - DBI should
2360 be fixed. (only affects RDBMS which return uppercase column names)
2362 ut_zip should take an optional country like ut_phone.
2366 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2368 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.