- add init file installation to Makefile, add unified init file
[freeside.git] / FS / FS / Record.pm
1 package FS::Record;
2
3 use strict;
4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5              $me );
6 use subs qw(reload_dbdef);
7 use Exporter;
8 use Carp qw(carp cluck croak confess);
9 use File::CounterFile;
10 use Locale::Country;
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.19;
13 use FS::UID qw(dbh checkruid getotaker datasrc driver_name);
14 use FS::SearchCache;
15 use FS::Msgcat qw(gettext);
16
17 @ISA = qw(Exporter);
18 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
19
20 $DEBUG = 0;
21 $me = '[FS::Record]';
22
23 #ask FS::UID to run this stuff for us later
24 $FS::UID::callback{'FS::Record'} = sub { 
25   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
26   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
27   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
28 };
29
30 =head1 NAME
31
32 FS::Record - Database record objects
33
34 =head1 SYNOPSIS
35
36     use FS::Record;
37     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
38
39     $record = new FS::Record 'table', \%hash;
40     $record = new FS::Record 'table', { 'column' => 'value', ... };
41
42     $record  = qsearchs FS::Record 'table', \%hash;
43     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
44     @records = qsearch  FS::Record 'table', \%hash; 
45     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
46
47     $table = $record->table;
48     $dbdef_table = $record->dbdef_table;
49
50     $value = $record->get('column');
51     $value = $record->getfield('column');
52     $value = $record->column;
53
54     $record->set( 'column' => 'value' );
55     $record->setfield( 'column' => 'value' );
56     $record->column('value');
57
58     %hash = $record->hash;
59
60     $hashref = $record->hashref;
61
62     $error = $record->insert;
63     #$error = $record->add; #deprecated
64
65     $error = $record->delete;
66     #$error = $record->del; #deprecated
67
68     $error = $new_record->replace($old_record);
69     #$error = $new_record->rep($old_record); #deprecated
70
71     $value = $record->unique('column');
72
73     $error = $record->ut_float('column');
74     $error = $record->ut_number('column');
75     $error = $record->ut_numbern('column');
76     $error = $record->ut_money('column');
77     $error = $record->ut_text('column');
78     $error = $record->ut_textn('column');
79     $error = $record->ut_alpha('column');
80     $error = $record->ut_alphan('column');
81     $error = $record->ut_phonen('column');
82     $error = $record->ut_anything('column');
83     $error = $record->ut_name('column');
84
85     $dbdef = reload_dbdef;
86     $dbdef = reload_dbdef "/non/standard/filename";
87     $dbdef = dbdef;
88
89     $quoted_value = _quote($value,'table','field');
90
91     #depriciated
92     $fields = hfields('table');
93     if ( $fields->{Field} ) { # etc.
94
95     @fields = fields 'table'; #as a subroutine
96     @fields = $record->fields; #as a method call
97
98
99 =head1 DESCRIPTION
100
101 (Mostly) object-oriented interface to database records.  Records are currently
102 implemented on top of DBI.  FS::Record is intended as a base class for
103 table-specific classes to inherit from, i.e. FS::cust_main.
104
105 =head1 CONSTRUCTORS
106
107 =over 4
108
109 =item new [ TABLE, ] HASHREF
110
111 Creates a new record.  It doesn't store it in the database, though.  See
112 L<"insert"> for that.
113
114 Note that the object stores this hash reference, not a distinct copy of the
115 hash it points to.  You can ask the object for a copy with the I<hash> 
116 method.
117
118 TABLE can only be omitted when a dervived class overrides the table method.
119
120 =cut
121
122 sub new { 
123   my $proto = shift;
124   my $class = ref($proto) || $proto;
125   my $self = {};
126   bless ($self, $class);
127
128   unless ( defined ( $self->table ) ) {
129     $self->{'Table'} = shift;
130     carp "warning: FS::Record::new called with table name ". $self->{'Table'};
131   }
132
133   my $hashref = $self->{'Hash'} = shift;
134
135   foreach my $field ( $self->fields ) { 
136     $hashref->{$field}='' unless defined $hashref->{$field};
137     #trim the '$' and ',' from money fields for Pg (belong HERE?)
138     #(what about Pg i18n?)
139     if ( driver_name =~ /^Pg$/i
140          && $self->dbdef_table->column($field)->type eq 'money' ) {
141       ${$hashref}{$field} =~ s/^\$//;
142       ${$hashref}{$field} =~ s/\,//;
143     }
144   }
145
146   $self->_cache($hashref, shift) if $self->can('_cache') && @_;
147
148   $self;
149 }
150
151 sub new_or_cached {
152   my $proto = shift;
153   my $class = ref($proto) || $proto;
154   my $self = {};
155   bless ($self, $class);
156
157   $self->{'Table'} = shift unless defined ( $self->table );
158
159   my $hashref = $self->{'Hash'} = shift;
160   my $cache = shift;
161   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
162     my $obj = $cache->cache->{$hashref->{$cache->key}};
163     $obj->_cache($hashref, $cache) if $obj->can('_cache');
164     $obj;
165   } else {
166     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
167   }
168
169 }
170
171 sub create {
172   my $proto = shift;
173   my $class = ref($proto) || $proto;
174   my $self = {};
175   bless ($self, $class);
176   if ( defined $self->table ) {
177     cluck "create constructor is depriciated, use new!";
178     $self->new(@_);
179   } else {
180     croak "FS::Record::create called (not from a subclass)!";
181   }
182 }
183
184 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
185
186 Searches the database for all records matching (at least) the key/value pairs
187 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
188 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
189 objects.
190
191 ###oops, argh, FS::Record::new only lets us create database fields.
192 #Normal behaviour if SELECT is not specified is `*', as in
193 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
194 #feature where you can specify SELECT - remember, the objects returned,
195 #although blessed into the appropriate `FS::TABLE' package, will only have the
196 #fields you specify.  This might have unwanted results if you then go calling
197 #regular FS::TABLE methods
198 #on it.
199
200 =cut
201
202 sub qsearch {
203   my($stable, $record, $select, $extra_sql, $cache ) = @_;
204   #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
205   #for jsearch
206   $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
207   $stable = $1;
208   $select ||= '*';
209   my $dbh = dbh;
210
211   my $table = $cache ? $cache->table : $stable;
212
213   my @fields = grep exists($record->{$_}), fields($table);
214
215   my $statement = "SELECT $select FROM $stable";
216   if ( @fields ) {
217     $statement .= ' WHERE '. join(' AND ', map {
218
219       my $op = '=';
220       if ( ref($record->{$_}) ) {
221         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
222         $op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name !~ /^Pg$/i;
223         $record->{$_} = $record->{$_}{'value'}
224       }
225
226       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
227         if ( $op eq '=' ) {
228           if ( driver_name =~ /^Pg$/i ) {
229             qq-( $_ IS NULL OR $_ = '' )-;
230           } else {
231             qq-( $_ IS NULL OR $_ = "" )-;
232           }
233         } elsif ( $op eq '!=' ) {
234           if ( driver_name =~ /^Pg$/i ) {
235             qq-( $_ IS NOT NULL AND $_ != '' )-;
236           } else {
237             qq-( $_ IS NOT NULL AND $_ != "" )-;
238           }
239         } else {
240           if ( driver_name =~ /^Pg$/i ) {
241             qq-( $_ $op '' )-;
242           } else {
243             qq-( $_ $op "" )-;
244           }
245         }
246       } else {
247         "$_ $op ?";
248       }
249     } @fields );
250   }
251   $statement .= " $extra_sql" if defined($extra_sql);
252
253   warn "[debug]$me $statement\n" if $DEBUG;
254   my $sth = $dbh->prepare($statement)
255     or croak "$dbh->errstr doing $statement";
256
257   my $bind = 1;
258
259   foreach my $field (
260     grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
261   ) {
262     if ( $record->{$field} =~ /^\d+(\.\d+)?$/
263          && $dbdef->table($table)->column($field)->type =~ /(int)/i
264     ) {
265       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
266     } else {
267       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
268     }
269   }
270
271 #  $sth->execute( map $record->{$_},
272 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
273 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
274
275   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
276
277   $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
278
279   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
280     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
281       #derivied class didn't override new method, so this optimization is safe
282       if ( $cache ) {
283         map {
284           new_or_cached( "FS::$table", { %{$_} }, $cache )
285         } @{$sth->fetchall_arrayref( {} )};
286       } else {
287         map {
288           new( "FS::$table", { %{$_} } )
289         } @{$sth->fetchall_arrayref( {} )};
290       }
291     } else {
292       warn "untested code (class FS::$table uses custom new method)";
293       map {
294         eval 'FS::'. $table. '->new( { %{$_} } )';
295       } @{$sth->fetchall_arrayref( {} )};
296     }
297   } else {
298     cluck "warning: FS::$table not loaded; returning FS::Record objects";
299     map {
300       FS::Record->new( $table, { %{$_} } );
301     } @{$sth->fetchall_arrayref( {} )};
302   }
303
304 }
305
306 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
307
308 Experimental JOINed search method.  Using this method, you can execute a
309 single SELECT spanning multiple tables, and cache the results for subsequent
310 method calls.  Interface will almost definately change in an incompatible
311 fashion.
312
313 Arguments: 
314
315 =cut
316
317 sub jsearch {
318   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
319   my $cache = FS::SearchCache->new( $ptable, $pkey );
320   my %saw;
321   ( $cache,
322     grep { !$saw{$_->getfield($pkey)}++ }
323       qsearch($table, $record, $select, $extra_sql, $cache )
324   );
325 }
326
327 =item qsearchs TABLE, HASHREF
328
329 Same as qsearch, except that if more than one record matches, it B<carp>s but
330 returns the first.  If this happens, you either made a logic error in asking
331 for a single item, or your data is corrupted.
332
333 =cut
334
335 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
336   my(@result) = qsearch(@_);
337   carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
338     #should warn more vehemently if the search was on a primary key?
339   scalar(@result) ? ($result[0]) : ();
340 }
341
342 =back
343
344 =head1 METHODS
345
346 =over 4
347
348 =item table
349
350 Returns the table name.
351
352 =cut
353
354 sub table {
355 #  cluck "warning: FS::Record::table depriciated; supply one in subclass!";
356   my $self = shift;
357   $self -> {'Table'};
358 }
359
360 =item dbdef_table
361
362 Returns the DBIx::DBSchema::Table object for the table.
363
364 =cut
365
366 sub dbdef_table {
367   my($self)=@_;
368   my($table)=$self->table;
369   $dbdef->table($table);
370 }
371
372 =item get, getfield COLUMN
373
374 Returns the value of the column/field/key COLUMN.
375
376 =cut
377
378 sub get {
379   my($self,$field) = @_;
380   # to avoid "Use of unitialized value" errors
381   if ( defined ( $self->{Hash}->{$field} ) ) {
382     $self->{Hash}->{$field};
383   } else { 
384     '';
385   }
386 }
387 sub getfield {
388   my $self = shift;
389   $self->get(@_);
390 }
391
392 =item set, setfield COLUMN, VALUE
393
394 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
395
396 =cut
397
398 sub set { 
399   my($self,$field,$value) = @_;
400   $self->{'Hash'}->{$field} = $value;
401 }
402 sub setfield {
403   my $self = shift;
404   $self->set(@_);
405 }
406
407 =item AUTLOADED METHODS
408
409 $record->column is a synonym for $record->get('column');
410
411 $record->column('value') is a synonym for $record->set('column','value');
412
413 =cut
414
415 # readable/safe
416 sub AUTOLOAD {
417   my($self,$value)=@_;
418   my($field)=$AUTOLOAD;
419   $field =~ s/.*://;
420   if ( defined($value) ) {
421     confess "errant AUTOLOAD $field for $self (arg $value)"
422       unless $self->can('setfield');
423     $self->setfield($field,$value);
424   } else {
425     confess "errant AUTOLOAD $field for $self (no args)"
426       unless $self->can('getfield');
427     $self->getfield($field);
428   }    
429 }
430
431 # efficient
432 #sub AUTOLOAD {
433 #  my $field = $AUTOLOAD;
434 #  $field =~ s/.*://;
435 #  if ( defined($_[1]) ) {
436 #    $_[0]->setfield($field, $_[1]);
437 #  } else {
438 #    $_[0]->getfield($field);
439 #  }    
440 #}
441
442 =item hash
443
444 Returns a list of the column/value pairs, usually for assigning to a new hash.
445
446 To make a distinct duplicate of an FS::Record object, you can do:
447
448     $new = new FS::Record ( $old->table, { $old->hash } );
449
450 =cut
451
452 sub hash {
453   my($self) = @_;
454   %{ $self->{'Hash'} }; 
455 }
456
457 =item hashref
458
459 Returns a reference to the column/value hash.
460
461 =cut
462
463 sub hashref {
464   my($self) = @_;
465   $self->{'Hash'};
466 }
467
468 =item insert
469
470 Inserts this record to the database.  If there is an error, returns the error,
471 otherwise returns false.
472
473 =cut
474
475 sub insert {
476   my $self = shift;
477
478   my $error = $self->check;
479   return $error if $error;
480
481   #single-field unique keys are given a value if false
482   #(like MySQL's AUTO_INCREMENT)
483   foreach ( $self->dbdef_table->unique->singles ) {
484     $self->unique($_) unless $self->getfield($_);
485   }
486   #and also the primary key
487   my $primary_key = $self->dbdef_table->primary_key;
488   $self->unique($primary_key) 
489     if $primary_key && ! $self->getfield($primary_key);
490
491   #false laziness w/delete
492   my @fields =
493     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
494     $self->fields
495   ;
496   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
497   #eslaf
498
499   my $statement = "INSERT INTO ". $self->table. " ( ".
500       join( ', ', @fields ).
501     ") VALUES (".
502       join( ', ', @values ).
503     ")"
504   ;
505   warn "[debug]$me $statement\n" if $DEBUG;
506   my $sth = dbh->prepare($statement) or return dbh->errstr;
507
508   my $h_sth;
509   if ( defined $dbdef->table('h_'. $self->table) ) {
510     my $h_statement = $self->_h_statement('insert');
511     warn "[debug]$me $h_statement\n" if $DEBUG;
512     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
513   } else {
514     $h_sth = '';
515   }
516
517   local $SIG{HUP} = 'IGNORE';
518   local $SIG{INT} = 'IGNORE';
519   local $SIG{QUIT} = 'IGNORE'; 
520   local $SIG{TERM} = 'IGNORE';
521   local $SIG{TSTP} = 'IGNORE';
522   local $SIG{PIPE} = 'IGNORE';
523
524   $sth->execute or return $sth->errstr;
525   $h_sth->execute or return $h_sth->errstr if $h_sth;
526   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
527
528   '';
529 }
530
531 =item add
532
533 Depriciated (use insert instead).
534
535 =cut
536
537 sub add {
538   cluck "warning: FS::Record::add depriciated!";
539   insert @_; #call method in this scope
540 }
541
542 =item delete
543
544 Delete this record from the database.  If there is an error, returns the error,
545 otherwise returns false.
546
547 =cut
548
549 sub delete {
550   my $self = shift;
551
552   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
553     map {
554       $self->getfield($_) eq ''
555         #? "( $_ IS NULL OR $_ = \"\" )"
556         ? ( driver_name =~ /^Pg$/i
557               ? "$_ IS NULL"
558               : "( $_ IS NULL OR $_ = \"\" )"
559           )
560         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
561     } ( $self->dbdef_table->primary_key )
562           ? ( $self->dbdef_table->primary_key)
563           : $self->fields
564   );
565   warn "[debug]$me $statement\n" if $DEBUG;
566   my $sth = dbh->prepare($statement) or return dbh->errstr;
567
568   my $h_sth;
569   if ( defined $dbdef->table('h_'. $self->table) ) {
570     my $h_statement = $self->_h_statement('delete');
571     warn "[debug]$me $h_statement\n" if $DEBUG;
572     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
573   } else {
574     $h_sth = '';
575   }
576
577   local $SIG{HUP} = 'IGNORE';
578   local $SIG{INT} = 'IGNORE';
579   local $SIG{QUIT} = 'IGNORE'; 
580   local $SIG{TERM} = 'IGNORE';
581   local $SIG{TSTP} = 'IGNORE';
582   local $SIG{PIPE} = 'IGNORE';
583
584   my $rc = $sth->execute or return $sth->errstr;
585   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
586   $h_sth->execute or return $h_sth->errstr if $h_sth;
587   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
588
589   #no need to needlessly destoy the data either (causes problems actually)
590   #undef $self; #no need to keep object!
591
592   '';
593 }
594
595 =item del
596
597 Depriciated (use delete instead).
598
599 =cut
600
601 sub del {
602   cluck "warning: FS::Record::del depriciated!";
603   &delete(@_); #call method in this scope
604 }
605
606 =item replace OLD_RECORD
607
608 Replace the OLD_RECORD with this one in the database.  If there is an error,
609 returns the error, otherwise returns false.
610
611 =cut
612
613 sub replace {
614   my ( $new, $old ) = ( shift, shift );
615   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
616
617   return "Records not in same table!" unless $new->table eq $old->table;
618
619   my $primary_key = $old->dbdef_table->primary_key;
620   return "Can't change $primary_key"
621     if $primary_key
622        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
623
624   my $error = $new->check;
625   return $error if $error;
626
627   my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
628   unless ( @diff ) {
629     carp "[warning]$me $new -> replace $old: records identical";
630     return '';
631   }
632
633   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
634     map {
635       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
636     } @diff
637   ). ' WHERE '.
638     join(' AND ',
639       map {
640         $old->getfield($_) eq ''
641           #? "( $_ IS NULL OR $_ = \"\" )"
642           ? ( driver_name =~ /^Pg$/i
643                 ? "$_ IS NULL"
644                 : "( $_ IS NULL OR $_ = \"\" )"
645             )
646           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
647       } ( $primary_key ? ( $primary_key ) : $old->fields )
648     )
649   ;
650   warn "[debug]$me $statement\n" if $DEBUG;
651   my $sth = dbh->prepare($statement) or return dbh->errstr;
652
653   my $h_old_sth;
654   if ( defined $dbdef->table('h_'. $old->table) ) {
655     my $h_old_statement = $old->_h_statement('replace_old');
656     warn "[debug]$me $h_old_statement\n" if $DEBUG;
657     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
658   } else {
659     $h_old_sth = '';
660   }
661
662   my $h_new_sth;
663   if ( defined $dbdef->table('h_'. $new->table) ) {
664     my $h_new_statement = $new->_h_statement('replace_new');
665     warn "[debug]$me $h_new_statement\n" if $DEBUG;
666     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
667   } else {
668     $h_new_sth = '';
669   }
670
671   local $SIG{HUP} = 'IGNORE';
672   local $SIG{INT} = 'IGNORE';
673   local $SIG{QUIT} = 'IGNORE'; 
674   local $SIG{TERM} = 'IGNORE';
675   local $SIG{TSTP} = 'IGNORE';
676   local $SIG{PIPE} = 'IGNORE';
677
678   my $rc = $sth->execute or return $sth->errstr;
679   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
680   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
681   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
682   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
683
684   '';
685
686 }
687
688 =item rep
689
690 Depriciated (use replace instead).
691
692 =cut
693
694 sub rep {
695   cluck "warning: FS::Record::rep depriciated!";
696   replace @_; #call method in this scope
697 }
698
699 =item check
700
701 Not yet implemented, croaks.  Derived classes should provide a check method.
702
703 =cut
704
705 sub check {
706   confess "FS::Record::check not implemented; supply one in subclass!";
707 }
708
709 sub _h_statement {
710   my( $self, $action ) = @_;
711
712   my @fields =
713     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
714     $self->fields
715   ;
716   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
717
718   "INSERT INTO h_". $self->table. " ( ".
719       join(', ', qw(history_date history_user history_action), @fields ).
720     ") VALUES (".
721       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
722     ")"
723   ;
724 }
725
726 =item unique COLUMN
727
728 Replaces COLUMN in record with a unique number.  Called by the B<add> method
729 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
730 Returns the new value.
731
732 =cut
733
734 sub unique {
735   my($self,$field) = @_;
736   my($table)=$self->table;
737
738   croak("&FS::UID::checkruid failed") unless &checkruid;
739
740   croak "Unique called on field $field, but it is ",
741         $self->getfield($field),
742         ", not null!"
743     if $self->getfield($field);
744
745   #warn "table $table is tainted" if is_tainted($table);
746   #warn "field $field is tainted" if is_tainted($field);
747
748   my($counter) = new File::CounterFile "$table.$field",0;
749 # hack for web demo
750 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
751 #  my($user)=$1;
752 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
753 # endhack
754
755   my($index)=$counter->inc;
756   $index=$counter->inc
757     while qsearchs($table,{$field=>$index}); #just in case
758
759   $index =~ /^(\d*)$/;
760   $index=$1;
761
762   $self->setfield($field,$index);
763
764 }
765
766 =item ut_float COLUMN
767
768 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
769 null.  If there is an error, returns the error, otherwise returns false.
770
771 =cut
772
773 sub ut_float {
774   my($self,$field)=@_ ;
775   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
776    $self->getfield($field) =~ /^(\d+)$/ ||
777    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
778    $self->getfield($field) =~ /^(\d+e\d+)$/)
779     or return "Illegal or empty (float) $field: ". $self->getfield($field);
780   $self->setfield($field,$1);
781   '';
782 }
783
784 =item ut_number COLUMN
785
786 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
787 is an error, returns the error, otherwise returns false.
788
789 =cut
790
791 sub ut_number {
792   my($self,$field)=@_;
793   $self->getfield($field) =~ /^(\d+)$/
794     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
795   $self->setfield($field,$1);
796   '';
797 }
798
799 =item ut_numbern COLUMN
800
801 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
802 an error, returns the error, otherwise returns false.
803
804 =cut
805
806 sub ut_numbern {
807   my($self,$field)=@_;
808   $self->getfield($field) =~ /^(\d*)$/
809     or return "Illegal (numeric) $field: ". $self->getfield($field);
810   $self->setfield($field,$1);
811   '';
812 }
813
814 =item ut_money COLUMN
815
816 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
817 is an error, returns the error, otherwise returns false.
818
819 =cut
820
821 sub ut_money {
822   my($self,$field)=@_;
823   $self->setfield($field, 0) if $self->getfield($field) eq '';
824   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
825     or return "Illegal (money) $field: ". $self->getfield($field);
826   #$self->setfield($field, "$1$2$3" || 0);
827   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
828   '';
829 }
830
831 =item ut_text COLUMN
832
833 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
834 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
835 May not be null.  If there is an error, returns the error, otherwise returns
836 false.
837
838 =cut
839
840 sub ut_text {
841   my($self,$field)=@_;
842   #warn "msgcat ". \&msgcat. "\n";
843   #warn "notexist ". \&notexist. "\n";
844   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
845   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
846     or return gettext('illegal_or_empty_text'). " $field: ".
847                $self->getfield($field);
848   $self->setfield($field,$1);
849   '';
850 }
851
852 =item ut_textn COLUMN
853
854 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
855 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
856 May be null.  If there is an error, returns the error, otherwise returns false.
857
858 =cut
859
860 sub ut_textn {
861   my($self,$field)=@_;
862   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
863     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
864   $self->setfield($field,$1);
865   '';
866 }
867
868 =item ut_alpha COLUMN
869
870 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
871 an error, returns the error, otherwise returns false.
872
873 =cut
874
875 sub ut_alpha {
876   my($self,$field)=@_;
877   $self->getfield($field) =~ /^(\w+)$/
878     or return "Illegal or empty (alphanumeric) $field: ".
879               $self->getfield($field);
880   $self->setfield($field,$1);
881   '';
882 }
883
884 =item ut_alpha COLUMN
885
886 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
887 error, returns the error, otherwise returns false.
888
889 =cut
890
891 sub ut_alphan {
892   my($self,$field)=@_;
893   $self->getfield($field) =~ /^(\w*)$/ 
894     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
895   $self->setfield($field,$1);
896   '';
897 }
898
899 =item ut_phonen COLUMN [ COUNTRY ]
900
901 Check/untaint phone numbers.  May be null.  If there is an error, returns
902 the error, otherwise returns false.
903
904 Takes an optional two-letter ISO country code; without it or with unsupported
905 countries, ut_phonen simply calls ut_alphan.
906
907 =cut
908
909 sub ut_phonen {
910   my( $self, $field, $country ) = @_;
911   return $self->ut_alphan($field) unless defined $country;
912   my $phonen = $self->getfield($field);
913   if ( $phonen eq '' ) {
914     $self->setfield($field,'');
915   } elsif ( $country eq 'US' || $country eq 'CA' ) {
916     $phonen =~ s/\D//g;
917     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
918       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
919     $phonen = "$1-$2-$3";
920     $phonen .= " x$4" if $4;
921     $self->setfield($field,$phonen);
922   } else {
923     warn "warning: don't know how to check phone numbers for country $country";
924     return $self->ut_textn($field);
925   }
926   '';
927 }
928
929 =item ut_ip COLUMN
930
931 Check/untaint ip addresses.  IPv4 only for now.
932
933 =cut
934
935 sub ut_ip {
936   my( $self, $field ) = @_;
937   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
938     or return "Illegal (IP address) $field: ". $self->getfield($field);
939   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
940   $self->setfield($field, "$1.$2.$3.$3");
941   '';
942 }
943
944 =item ut_ipn COLUMN
945
946 Check/untaint ip addresses.  IPv4 only for now.  May be null.
947
948 =cut
949
950 sub ut_ipn {
951   my( $self, $field ) = @_;
952   if ( $self->getfield($field) =~ /^()$/ ) {
953     $self->setfield($field,'');
954     '';
955   } else {
956     $self->ut_ip($field);
957   }
958 }
959
960 =item ut_domain COLUMN
961
962 Check/untaint host and domain names.
963
964 =cut
965
966 sub ut_domain {
967   my( $self, $field ) = @_;
968   #$self->getfield($field) =~/^(\w+\.)*\w+$/
969   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
970     or return "Illegal (domain) $field: ". $self->getfield($field);
971   $self->setfield($field,$1);
972   '';
973 }
974
975 =item ut_name COLUMN
976
977 Check/untaint proper names; allows alphanumerics, spaces and the following
978 punctuation: , . - '
979
980 May not be null.
981
982 =cut
983
984 sub ut_name {
985   my( $self, $field ) = @_;
986   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
987     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
988   $self->setfield($field,$1);
989   '';
990 }
991
992 =item ut_zip COLUMN
993
994 Check/untaint zip codes.
995
996 =cut
997
998 sub ut_zip {
999   my( $self, $field, $country ) = @_;
1000   if ( $country eq 'US' ) {
1001     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1002       or return gettext('illegal_zip'). " $field for country $country: ".
1003                 $self->getfield($field);
1004     $self->setfield($field,$1);
1005   } else {
1006     $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1007       or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1008     $self->setfield($field,$1);
1009   }
1010   '';
1011 }
1012
1013 =item ut_country COLUMN
1014
1015 Check/untaint country codes.  Country names are changed to codes, if possible -
1016 see L<Locale::Country>.
1017
1018 =cut
1019
1020 sub ut_country {
1021   my( $self, $field ) = @_;
1022   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1023     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1024          && country2code($1) ) {
1025       $self->setfield($field,uc(country2code($1)));
1026     }
1027   }
1028   $self->getfield($field) =~ /^(\w\w)$/
1029     or return "Illegal (country) $field: ". $self->getfield($field);
1030   $self->setfield($field,uc($1));
1031   '';
1032 }
1033
1034 =item ut_anything COLUMN
1035
1036 Untaints arbitrary data.  Be careful.
1037
1038 =cut
1039
1040 sub ut_anything {
1041   my( $self, $field ) = @_;
1042   $self->getfield($field) =~ /^(.*)$/s
1043     or return "Illegal $field: ". $self->getfield($field);
1044   $self->setfield($field,$1);
1045   '';
1046 }
1047
1048 =item ut_enum COLUMN CHOICES_ARRAYREF
1049
1050 Check/untaint a column, supplying all possible choices, like the "enum" type.
1051
1052 =cut
1053
1054 sub ut_enum {
1055   my( $self, $field, $choices ) = @_;
1056   foreach my $choice ( @$choices ) {
1057     if ( $self->getfield($field) eq $choice ) {
1058       $self->setfield($choice);
1059       return '';
1060     }
1061   }
1062   return "Illegal (enum) field $field: ". $self->getfield($field);
1063 }
1064
1065 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1066
1067 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1068 on the column first.
1069
1070 =cut
1071
1072 sub ut_foreign_key {
1073   my( $self, $field, $table, $foreign ) = @_;
1074   qsearchs($table, { $foreign => $self->getfield($field) })
1075     or return "Can't find $field ". $self->getfield($field).
1076               " in $table.$foreign";
1077   '';
1078 }
1079
1080 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1081
1082 Like ut_foreign_key, except the null value is also allowed.
1083
1084 =cut
1085
1086 sub ut_foreign_keyn {
1087   my( $self, $field, $table, $foreign ) = @_;
1088   $self->getfield($field)
1089     ? $self->ut_foreign_key($field, $table, $foreign)
1090     : '';
1091 }
1092
1093 =item fields [ TABLE ]
1094
1095 This can be used as both a subroutine and a method call.  It returns a list
1096 of the columns in this record's table, or an explicitly specified table.
1097 (See L<DBIx::DBSchema::Table>).
1098
1099 =cut
1100
1101 # Usage: @fields = fields($table);
1102 #        @fields = $record->fields;
1103 sub fields {
1104   my $something = shift;
1105   my $table;
1106   if ( ref($something) ) {
1107     $table = $something->table;
1108   } else {
1109     $table = $something;
1110   }
1111   #croak "Usage: \@fields = fields(\$table)\n   or: \@fields = \$record->fields" unless $table;
1112   my($table_obj) = $dbdef->table($table);
1113   confess "Unknown table $table" unless $table_obj;
1114   $table_obj->columns;
1115 }
1116
1117 =back
1118
1119 =head1 SUBROUTINES
1120
1121 =over 4
1122
1123 =item reload_dbdef([FILENAME])
1124
1125 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1126 non-default filename.  This command is executed at startup unless
1127 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1128
1129 =cut
1130
1131 sub reload_dbdef {
1132   my $file = shift || $dbdef_file;
1133   $dbdef = load DBIx::DBSchema $file
1134     or die "can't load database schema from $file";
1135 }
1136
1137 =item dbdef
1138
1139 Returns the current database definition.  See L<DBIx::DBSchema>.
1140
1141 =cut
1142
1143 sub dbdef { $dbdef; }
1144
1145 =item _quote VALUE, TABLE, COLUMN
1146
1147 This is an internal function used to construct SQL statements.  It returns
1148 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1149 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1150
1151 =cut
1152
1153 sub _quote {
1154   my($value,$table,$field)=@_;
1155   my($dbh)=dbh;
1156   if ( $value =~ /^\d+(\.\d+)?$/ && 
1157 #       ! ( datatype($table,$field) =~ /^char/ ) 
1158        ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i ) 
1159   ) {
1160     $value;
1161   } else {
1162     $dbh->quote($value);
1163   }
1164 }
1165
1166 =item hfields TABLE
1167
1168 This is depriciated.  Don't use it.
1169
1170 It returns a hash-type list with the fields of this record's table set true.
1171
1172 =cut
1173
1174 sub hfields {
1175   carp "warning: hfields is depriciated";
1176   my($table)=@_;
1177   my(%hash);
1178   foreach (fields($table)) {
1179     $hash{$_}=1;
1180   }
1181   \%hash;
1182 }
1183
1184 sub _dump {
1185   my($self)=@_;
1186   join("\n", map {
1187     "$_: ". $self->getfield($_). "|"
1188   } (fields($self->table)) );
1189 }
1190
1191 sub DESTROY { return; }
1192
1193 #sub DESTROY {
1194 #  my $self = shift;
1195 #  #use Carp qw(cluck);
1196 #  #cluck "DESTROYING $self";
1197 #  warn "DESTROYING $self";
1198 #}
1199
1200 #sub is_tainted {
1201 #             return ! eval { join('',@_), kill 0; 1; };
1202 #         }
1203
1204 =back
1205
1206 =head1 BUGS
1207
1208 This module should probably be renamed, since much of the functionality is
1209 of general use.  It is not completely unlike Adapter::DBI (see below).
1210
1211 Exported qsearch and qsearchs should be depriciated in favor of method calls
1212 (against an FS::Record object like the old search and searchs that qsearch
1213 and qsearchs were on top of.)
1214
1215 The whole fields / hfields mess should be removed.
1216
1217 The various WHERE clauses should be subroutined.
1218
1219 table string should be depriciated in favor of DBIx::DBSchema::Table.
1220
1221 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1222 true maps to the database (and WHERE clauses) would also help.
1223
1224 The ut_ methods should ask the dbdef for a default length.
1225
1226 ut_sqltype (like ut_varchar) should all be defined
1227
1228 A fallback check method should be provided which uses the dbdef.
1229
1230 The ut_money method assumes money has two decimal digits.
1231
1232 The Pg money kludge in the new method only strips `$'.
1233
1234 The ut_phonen method only checks US-style phone numbers.
1235
1236 The _quote function should probably use ut_float instead of a regex.
1237
1238 All the subroutines probably should be methods, here or elsewhere.
1239
1240 Probably should borrow/use some dbdef methods where appropriate (like sub
1241 fields)
1242
1243 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1244 or allow it to be set.  Working around it is ugly any way around - DBI should
1245 be fixed.  (only affects RDBMS which return uppercase column names)
1246
1247 ut_zip should take an optional country like ut_phone.
1248
1249 =head1 SEE ALSO
1250
1251 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1252
1253 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1254
1255 =cut
1256
1257 1;
1258