d6eaf257903c3b09be7e10acb97c725efd2da9f5
[freeside.git] / FS / FS / svc_domain.pm
1 package FS::svc_domain;
2
3 use strict;
4 use vars qw( @ISA $whois_hack $conf
5   @defaultrecords $soadefaultttl $soaemail $soaexpire $soamachine
6   $soarefresh $soaretry
7 );
8 use Carp;
9 use Scalar::Util qw( blessed );
10 use Date::Format;
11 #use Net::Whois::Raw;
12 use Net::Domain::TLD qw(tld_exists);
13 use FS::Record qw(fields qsearch qsearchs dbh);
14 use FS::Conf;
15 use FS::svc_Common;
16 use FS::svc_Parent_Mixin;
17 use FS::cust_svc;
18 use FS::svc_acct;
19 use FS::cust_pkg;
20 use FS::cust_main;
21 use FS::domain_record;
22 use FS::queue;
23
24 @ISA = qw( FS::svc_Parent_Mixin FS::svc_Common );
25
26 #ask FS::UID to run this stuff for us later
27 $FS::UID::callback{'FS::domain'} = sub { 
28   $conf = new FS::Conf;
29
30   @defaultrecords = $conf->config('defaultrecords');
31   $soadefaultttl = $conf->config('soadefaultttl');
32   $soaemail      = $conf->config('soaemail');
33   $soaexpire     = $conf->config('soaexpire');
34   $soamachine    = $conf->config('soamachine');
35   $soarefresh    = $conf->config('soarefresh');
36   $soaretry      = $conf->config('soaretry');
37
38 };
39
40 =head1 NAME
41
42 FS::svc_domain - Object methods for svc_domain records
43
44 =head1 SYNOPSIS
45
46   use FS::svc_domain;
47
48   $record = new FS::svc_domain \%hash;
49   $record = new FS::svc_domain { 'column' => 'value' };
50
51   $error = $record->insert;
52
53   $error = $new_record->replace($old_record);
54
55   $error = $record->delete;
56
57   $error = $record->check;
58
59   $error = $record->suspend;
60
61   $error = $record->unsuspend;
62
63   $error = $record->cancel;
64
65 =head1 DESCRIPTION
66
67 An FS::svc_domain object represents a domain.  FS::svc_domain inherits from
68 FS::svc_Common.  The following fields are currently supported:
69
70 =over 4
71
72 =item svcnum - primary key (assigned automatically for new accounts)
73
74 =item domain
75
76 =item catchall - optional svcnum of an svc_acct record, designating an email catchall account.
77
78 =item suffix - 
79
80 =item parent_svcnum -
81
82 =item registrarnum - Registrar (see L<FS::registrar>)
83
84 =item registrarkey - Registrar key or password for this domain
85
86 =item setup_date - UNIX timestamp
87
88 =item renewal_interval - Number of days before expiration date to start renewal
89
90 =item expiration_date - UNIX timestamp
91
92 =item max_accounts
93
94 =back
95
96 =head1 METHODS
97
98 =over 4
99
100 =item new HASHREF
101
102 Creates a new domain.  To add the domain to the database, see L<"insert">.
103
104 =cut
105
106 sub table_info {
107   {
108     'name' => 'Domain',
109     'sorts' => 'domain',
110     'display_weight' => 20,
111     'cancel_weight'  => 60,
112     'fields' => {
113       'domain' => 'Domain',
114       'parent_svcnum' => { 
115                          label => 'Parent domain / Communigate administrator domain',
116                          type  => 'select',
117                          select_table => 'svc_domain',
118                          select_key => 'svcnum',
119                          select_label => 'domain',
120                          disable_inventory => 1,
121                          disable_select    => 1,
122                        },
123       'max_accounts' => { label => 'Maximum number of accounts',
124                           'disable_inventory' => 1,
125                         },
126       'cgp_aliases' => { 
127                          label => 'Communigate aliases',
128                          type  => 'text',
129                          disable_inventory => 1,
130                          disable_select    => 1,
131                        },
132       'cgp_accessmodes' => { 
133                              label => 'Communigate enabled services',
134                              type  => 'communigate_pro-accessmodes',
135                              disable_inventory => 1,
136                              disable_select    => 1,
137                            },
138
139       'acct_def_cgp_accessmodes' => { 
140                              label => 'Acct. default Communigate enabled services',
141                              type  => 'communigate_pro-accessmodes',
142                              disable_inventory => 1,
143                              disable_select    => 1,
144                            },
145       'acct_def_password_selfchange' => { label => 'Acct. default Password modification',
146                                  type  => 'checkbox',
147                             disable_inventory => 1,
148                             disable_select    => 1,
149                                },
150       'acct_def_password_recover'    => { label => 'Acct. default Password recovery',
151                                  type  => 'checkbox',
152                             disable_inventory => 1,
153                             disable_select    => 1,
154                                },
155       'acct_def_cgp_deletemode' => { 
156                             label => 'Acct. default Communigate message delete method',
157                             type  => 'select',
158                             select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
159                             disable_inventory => 1,
160                             disable_select    => 1,
161                           },
162       'acct_def_cgp_emptytrash' => { 
163                             label => 'Acct. default Communigate on logout remove trash',
164                             type  => 'text',
165                             disable_inventory => 1,
166                             disable_select    => 1,
167                           },
168       'acct_def_quota'     => { 
169                        label => 'Acct. default Quota', #Mail storage limit
170                        type => 'text',
171                        disable_inventory => 1,
172                        disable_select => 1,
173                      },
174       'acct_def_file_quota'=> { 
175                        label => 'Acct. default File storage limit',
176                        type => 'text',
177                        disable_inventory => 1,
178                        disable_select => 1,
179                      },
180       'acct_def_file_maxnum'=> { 
181                        label => 'Acct. default Number of files limit',
182                        type => 'text',
183                        disable_inventory => 1,
184                        disable_select => 1,
185                      },
186       'acct_def_file_maxsize'=> { 
187                        label => 'Acct. default File size limit',
188                        type => 'text',
189                        disable_inventory => 1,
190                        disable_select => 1,
191                      },
192
193
194     },
195   };
196 }
197
198 sub table { 'svc_domain'; }
199
200 sub search_sql {
201   my($class, $string) = @_;
202   $class->search_sql_field('domain', $string);
203 }
204
205
206 =item label
207
208 Returns the domain.
209
210 =cut
211
212 sub label {
213   my $self = shift;
214   $self->domain;
215 }
216
217 =item insert [ , OPTION => VALUE ... ]
218
219 Adds this domain to the database.  If there is an error, returns the error,
220 otherwise returns false.
221
222 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
223 defined.  An FS::cust_svc record will be created and inserted.
224
225 The additional field I<action> should be set to I<N> for new domains, I<M>
226 for transfers, or I<I> for no action (registered elsewhere).
227
228 A registration or transfer email will be submitted unless
229 $FS::svc_domain::whois_hack is true.
230
231 The additional field I<email> can be used to manually set the admin contact
232 email address on this email.  Otherwise, the svc_acct records for this package 
233 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
234 in the same package, it is automatically used.  Otherwise an error is returned.
235
236 If any I<soamachine> configuration file exists, an SOA record is added to
237 the domain_record table (see <FS::domain_record>).
238
239 If any records are defined in the I<defaultrecords> configuration file,
240 appropriate records are added to the domain_record table (see
241 L<FS::domain_record>).
242
243 Currently available options are: I<depend_jobnum>
244
245 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
246 jobnums), all provisioning jobs will have a dependancy on the supplied
247 jobnum(s) (they will not run until the specific job(s) complete(s)).
248
249 =cut
250
251 sub insert {
252   my $self = shift;
253   my $error;
254
255   local $SIG{HUP} = 'IGNORE';
256   local $SIG{INT} = 'IGNORE';
257   local $SIG{QUIT} = 'IGNORE';
258   local $SIG{TERM} = 'IGNORE';
259   local $SIG{TSTP} = 'IGNORE';
260   local $SIG{PIPE} = 'IGNORE';
261
262   my $oldAutoCommit = $FS::UID::AutoCommit;
263   local $FS::UID::AutoCommit = 0;
264   my $dbh = dbh;
265
266   $error = $self->SUPER::insert(@_);
267   if ( $error ) {
268     $dbh->rollback if $oldAutoCommit;
269     return $error;
270   }
271
272   if ( $soamachine ) {
273     my $soa = new FS::domain_record {
274       'svcnum'  => $self->svcnum,
275       'reczone' => '@',
276       'recaf'   => 'IN',
277       'rectype' => 'SOA',
278       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
279                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
280     };
281     $error = $soa->insert;
282     if ( $error ) {
283       $dbh->rollback if $oldAutoCommit;
284       return "couldn't insert SOA record for new domain: $error";
285     }
286
287     foreach my $record ( @defaultrecords ) {
288       my($zone,$af,$type,$data) = split(/\s+/,$record,4);
289       my $domain_record = new FS::domain_record {
290         'svcnum'  => $self->svcnum,
291         'reczone' => $zone,
292         'recaf'   => $af,
293         'rectype' => $type,
294         'recdata' => $data,
295       };
296       my $error = $domain_record->insert;
297       if ( $error ) {
298         $dbh->rollback if $oldAutoCommit;
299         return "couldn't insert record for new domain: $error";
300       }
301     }
302
303   }
304
305   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
306
307   ''; #no error
308 }
309
310 =item delete
311
312 Deletes this domain from the database.  If there is an error, returns the
313 error, otherwise returns false.
314
315 The corresponding FS::cust_svc record will be deleted as well.
316
317 =cut
318
319 sub delete {
320   my $self = shift;
321
322   return "Can't delete a domain which has accounts!"
323     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
324
325   #return "Can't delete a domain with (domain_record) zone entries!"
326   #  if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
327
328   local $SIG{HUP} = 'IGNORE';
329   local $SIG{INT} = 'IGNORE';
330   local $SIG{QUIT} = 'IGNORE';
331   local $SIG{TERM} = 'IGNORE';
332   local $SIG{TSTP} = 'IGNORE';
333   local $SIG{PIPE} = 'IGNORE';
334
335   my $oldAutoCommit = $FS::UID::AutoCommit;
336   local $FS::UID::AutoCommit = 0;
337   my $dbh = dbh;
338
339   foreach my $domain_record ( reverse $self->domain_record ) {
340     my $error = $domain_record->delete;
341     if ( $error ) {
342       $dbh->rollback if $oldAutoCommit;
343       return "can't delete DNS entry: ".
344              join(' ', map $domain_record->$_(),
345                            qw( reczone recaf rectype recdata )
346                  ).
347              ":$error";
348     }
349   }
350
351   my $error = $self->SUPER::delete(@_);
352   if ( $error ) {
353     $dbh->rollback if $oldAutoCommit;
354     return $error;
355   }
356
357   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
358 }
359
360 =item replace OLD_RECORD
361
362 Replaces OLD_RECORD with this one in the database.  If there is an error,
363 returns the error, otherwise returns false.
364
365 =cut
366
367 sub replace {
368   my $new = shift;
369
370   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
371               ? shift
372               : $new->replace_old;
373
374   return "Can't change domain - reorder."
375     if $old->getfield('domain') ne $new->getfield('domain')
376     && ! $conf->exists('svc_domain-edit_domain'); 
377
378   # Better to do it here than to force the caller to remember that svc_domain is weird.
379   $new->setfield(action => 'I');
380   my $error = $new->SUPER::replace($old, @_);
381   return $error if $error;
382 }
383
384 =item suspend
385
386 Just returns false (no error) for now.
387
388 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
389
390 =item unsuspend
391
392 Just returns false (no error) for now.
393
394 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
395
396 =item cancel
397
398 Just returns false (no error) for now.
399
400 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
401
402 =item check
403
404 Checks all fields to make sure this is a valid domain.  If there is an error,
405 returns the error, otherwise returns false.  Called by the insert and replace
406 methods.
407
408 Sets any fixed values; see L<FS::part_svc>.
409
410 =cut
411
412 sub check {
413   my $self = shift;
414
415   my $x = $self->setfixed;
416   return $x unless ref($x);
417   #my $part_svc = $x;
418
419   my $error = $self->ut_numbern('svcnum')
420               || $self->ut_numbern('catchall')
421               || $self->ut_numbern('max_accounts')
422               || $self->ut_textn('cgp_aliases') #well
423               || $self->ut_enum('acct_def_password_selfchange', [ '', 'Y' ])
424               || $self->ut_enum('acct_def_password_recover',    [ '', 'Y' ])
425               || $self->ut_textn('acct_def_cgp_accessmodes')
426               || $self->ut_alphan('acct_def_quota')
427               || $self->ut_alphan('acct_def_file_quota')
428               || $self->ut_alphan('acct_def_maxnum')
429               || $self->ut_alphan('acct_def_maxsize')
430               || $self->ut_alphasn('acct_def_cgp_deletemode')
431               || $self->ut_alphan('acct_def_cgp_emptytrash')
432   ;
433   return $error if $error;
434
435   #hmm
436   my $pkgnum;
437   if ( $self->svcnum ) {
438     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
439     $pkgnum = $cust_svc->pkgnum;
440   } else {
441     $pkgnum = $self->pkgnum;
442   }
443
444   my($recref) = $self->hashref;
445
446   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
447   if ( $recref->{domain} =~ /^([\w\-]{1,63})\.(com|net|org|edu|tv|info|biz)$/ ) {
448     $recref->{domain} = "$1.$2";
449     $recref->{suffix} ||= $2;
450   # hmmmmmmmm.
451   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)\.(\w+)$/ ) {
452     $recref->{domain} = "$1.$2";
453     # need to match a list of suffixes - no guarantee they're top-level..
454     # http://wiki.mozilla.org/TLD_List
455     # but this will have to do for now...
456     $recref->{suffix} ||= $2;
457   } else {
458     return "Illegal domain ". $recref->{domain}.
459            " (or unknown registry - try \$whois_hack)";
460   }
461
462   $self->suffix =~ /(^|\.)(\w+)$/
463     or return "can't parse suffix for TLD: ". $self->suffix;
464   my $tld = $2;
465   return "No such TLD: .$tld" unless tld_exists($tld);
466
467   if ( $recref->{catchall} ne '' ) {
468     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
469     return "Unknown catchall" unless $svc_acct;
470   }
471
472   $self->ut_alphan('suffix')
473     or $self->ut_foreign_keyn('registrarnum', 'registrar', 'registrarnum')
474     or $self->ut_textn('registrarkey')
475     or $self->ut_numbern('setup_date')
476     or $self->ut_numbern('renewal_interval')
477     or $self->ut_numbern('expiration_date')
478     or $self->SUPER::check;
479
480 }
481
482 sub _check_duplicate {
483   my $self = shift;
484
485   $self->lock_table;
486
487   if ( qsearchs( 'svc_domain', { 'domain' => $self->domain } ) ) {
488     return "Domain in use (here)";
489   } else {
490     return '';
491   }
492 }
493
494 =item domain_record
495
496 =cut
497
498 sub domain_record {
499   my $self = shift;
500
501   my %order = (
502     'SOA'   => 1,
503     'NS'    => 2,
504     'MX'    => 3,
505     'CNAME' => 4,
506     'A'     => 5,
507     'TXT'   => 6,
508     'PTR'   => 7,
509   );
510
511   my %sort = (
512     #'SOA'   => sub { $_[0]->recdata cmp $_[1]->recdata }, #sure hope not though
513 #    'SOA'   => sub { 0; },
514 #    'NS'    => sub { 0; },
515     'MX'    => sub { my( $a_weight, $a_name ) = split(/\s+/, $_[0]->recdata);
516                      my( $b_weight, $b_name ) = split(/\s+/, $_[1]->recdata);
517                      $a_weight <=> $b_weight or $a_name cmp $b_name;
518                    },
519     'CNAME' => sub { $_[0]->reczone cmp $_[1]->reczone },
520     'A'     => sub { $_[0]->reczone cmp $_[1]->reczone },
521
522 #    'TXT'   => sub { 0; },
523     'PTR'   => sub { $_[0]->reczone <=> $_[1]->reczone },
524   );
525
526   map { $_ } #return $self->num_domain_record( PARAMS ) unless wantarray;
527   sort {    $order{$a->rectype} <=> $order{$b->rectype}
528          or &{ $sort{$a->rectype} || sub { 0; } }($a, $b)
529        }
530        qsearch('domain_record', { svcnum => $self->svcnum } );
531
532 }
533
534 sub catchall_svc_acct {
535   my $self = shift;
536   if ( $self->catchall ) {
537     qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } );
538   } else {
539     '';
540   }
541 }
542
543 =item whois
544
545 # Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
546 # undef if the domain is not found in whois.
547
548 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
549
550 =cut
551
552 sub whois {
553   #$whois_hack or new Net::Whois::Domain $_[0]->domain;
554   #$whois_hack or die "whois_hack not set...\n";
555 }
556
557 =back
558
559 =head1 BUGS
560
561 Delete doesn't send a registration template.
562
563 All registries should be supported.
564
565 Should change action to a real field.
566
567 The $recref stuff in sub check should be cleaned up.
568
569 =head1 SEE ALSO
570
571 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
572 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, schema.html from the base
573 documentation, config.html from the base documentation.
574
575 =cut
576
577 1;
578
579