communigate: domain aliases, enabled services & administrator domain, RT#7083
[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   };
140 }
141
142 sub table { 'svc_domain'; }
143
144 sub search_sql {
145   my($class, $string) = @_;
146   $class->search_sql_field('domain', $string);
147 }
148
149
150 =item label
151
152 Returns the domain.
153
154 =cut
155
156 sub label {
157   my $self = shift;
158   $self->domain;
159 }
160
161 =item insert [ , OPTION => VALUE ... ]
162
163 Adds this domain to the database.  If there is an error, returns the error,
164 otherwise returns false.
165
166 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
167 defined.  An FS::cust_svc record will be created and inserted.
168
169 The additional field I<action> should be set to I<N> for new domains, I<M>
170 for transfers, or I<I> for no action (registered elsewhere).
171
172 A registration or transfer email will be submitted unless
173 $FS::svc_domain::whois_hack is true.
174
175 The additional field I<email> can be used to manually set the admin contact
176 email address on this email.  Otherwise, the svc_acct records for this package 
177 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
178 in the same package, it is automatically used.  Otherwise an error is returned.
179
180 If any I<soamachine> configuration file exists, an SOA record is added to
181 the domain_record table (see <FS::domain_record>).
182
183 If any records are defined in the I<defaultrecords> configuration file,
184 appropriate records are added to the domain_record table (see
185 L<FS::domain_record>).
186
187 Currently available options are: I<depend_jobnum>
188
189 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
190 jobnums), all provisioning jobs will have a dependancy on the supplied
191 jobnum(s) (they will not run until the specific job(s) complete(s)).
192
193 =cut
194
195 sub insert {
196   my $self = shift;
197   my $error;
198
199   local $SIG{HUP} = 'IGNORE';
200   local $SIG{INT} = 'IGNORE';
201   local $SIG{QUIT} = 'IGNORE';
202   local $SIG{TERM} = 'IGNORE';
203   local $SIG{TSTP} = 'IGNORE';
204   local $SIG{PIPE} = 'IGNORE';
205
206   my $oldAutoCommit = $FS::UID::AutoCommit;
207   local $FS::UID::AutoCommit = 0;
208   my $dbh = dbh;
209
210   $error = $self->SUPER::insert(@_);
211   if ( $error ) {
212     $dbh->rollback if $oldAutoCommit;
213     return $error;
214   }
215
216   if ( $soamachine ) {
217     my $soa = new FS::domain_record {
218       'svcnum'  => $self->svcnum,
219       'reczone' => '@',
220       'recaf'   => 'IN',
221       'rectype' => 'SOA',
222       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
223                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
224     };
225     $error = $soa->insert;
226     if ( $error ) {
227       $dbh->rollback if $oldAutoCommit;
228       return "couldn't insert SOA record for new domain: $error";
229     }
230
231     foreach my $record ( @defaultrecords ) {
232       my($zone,$af,$type,$data) = split(/\s+/,$record,4);
233       my $domain_record = new FS::domain_record {
234         'svcnum'  => $self->svcnum,
235         'reczone' => $zone,
236         'recaf'   => $af,
237         'rectype' => $type,
238         'recdata' => $data,
239       };
240       my $error = $domain_record->insert;
241       if ( $error ) {
242         $dbh->rollback if $oldAutoCommit;
243         return "couldn't insert record for new domain: $error";
244       }
245     }
246
247   }
248
249   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
250
251   ''; #no error
252 }
253
254 =item delete
255
256 Deletes this domain from the database.  If there is an error, returns the
257 error, otherwise returns false.
258
259 The corresponding FS::cust_svc record will be deleted as well.
260
261 =cut
262
263 sub delete {
264   my $self = shift;
265
266   return "Can't delete a domain which has accounts!"
267     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
268
269   #return "Can't delete a domain with (domain_record) zone entries!"
270   #  if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
271
272   local $SIG{HUP} = 'IGNORE';
273   local $SIG{INT} = 'IGNORE';
274   local $SIG{QUIT} = 'IGNORE';
275   local $SIG{TERM} = 'IGNORE';
276   local $SIG{TSTP} = 'IGNORE';
277   local $SIG{PIPE} = 'IGNORE';
278
279   my $oldAutoCommit = $FS::UID::AutoCommit;
280   local $FS::UID::AutoCommit = 0;
281   my $dbh = dbh;
282
283   foreach my $domain_record ( reverse $self->domain_record ) {
284     my $error = $domain_record->delete;
285     if ( $error ) {
286       $dbh->rollback if $oldAutoCommit;
287       return "can't delete DNS entry: ".
288              join(' ', map $domain_record->$_(),
289                            qw( reczone recaf rectype recdata )
290                  ).
291              ":$error";
292     }
293   }
294
295   my $error = $self->SUPER::delete(@_);
296   if ( $error ) {
297     $dbh->rollback if $oldAutoCommit;
298     return $error;
299   }
300
301   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
302 }
303
304 =item replace OLD_RECORD
305
306 Replaces OLD_RECORD with this one in the database.  If there is an error,
307 returns the error, otherwise returns false.
308
309 =cut
310
311 sub replace {
312   my $new = shift;
313
314   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
315               ? shift
316               : $new->replace_old;
317
318   return "Can't change domain - reorder."
319     if $old->getfield('domain') ne $new->getfield('domain')
320     && ! $conf->exists('svc_domain-edit_domain'); 
321
322   # Better to do it here than to force the caller to remember that svc_domain is weird.
323   $new->setfield(action => 'I');
324   my $error = $new->SUPER::replace($old, @_);
325   return $error if $error;
326 }
327
328 =item suspend
329
330 Just returns false (no error) for now.
331
332 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
333
334 =item unsuspend
335
336 Just returns false (no error) for now.
337
338 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
339
340 =item cancel
341
342 Just returns false (no error) for now.
343
344 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
345
346 =item check
347
348 Checks all fields to make sure this is a valid domain.  If there is an error,
349 returns the error, otherwise returns false.  Called by the insert and replace
350 methods.
351
352 Sets any fixed values; see L<FS::part_svc>.
353
354 =cut
355
356 sub check {
357   my $self = shift;
358
359   my $x = $self->setfixed;
360   return $x unless ref($x);
361   #my $part_svc = $x;
362
363   my $error = $self->ut_numbern('svcnum')
364               || $self->ut_numbern('catchall')
365               || $self->ut_numbern('max_accounts')
366               || $self->ut_textn('cgp_aliases') #well
367   ;
368   return $error if $error;
369
370   #hmm
371   my $pkgnum;
372   if ( $self->svcnum ) {
373     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
374     $pkgnum = $cust_svc->pkgnum;
375   } else {
376     $pkgnum = $self->pkgnum;
377   }
378
379   my($recref) = $self->hashref;
380
381   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
382   if ( $recref->{domain} =~ /^([\w\-]{1,63})\.(com|net|org|edu|tv|info|biz)$/ ) {
383     $recref->{domain} = "$1.$2";
384     $recref->{suffix} ||= $2;
385   # hmmmmmmmm.
386   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)\.(\w+)$/ ) {
387     $recref->{domain} = "$1.$2";
388     # need to match a list of suffixes - no guarantee they're top-level..
389     # http://wiki.mozilla.org/TLD_List
390     # but this will have to do for now...
391     $recref->{suffix} ||= $2;
392   } else {
393     return "Illegal domain ". $recref->{domain}.
394            " (or unknown registry - try \$whois_hack)";
395   }
396
397   $self->suffix =~ /(^|\.)(\w+)$/
398     or return "can't parse suffix for TLD: ". $self->suffix;
399   my $tld = $2;
400   return "No such TLD: .$tld" unless tld_exists($tld);
401
402   if ( $recref->{catchall} ne '' ) {
403     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
404     return "Unknown catchall" unless $svc_acct;
405   }
406
407   $self->ut_alphan('suffix')
408     or $self->ut_foreign_keyn('registrarnum', 'registrar', 'registrarnum')
409     or $self->ut_textn('registrarkey')
410     or $self->ut_numbern('setup_date')
411     or $self->ut_numbern('renewal_interval')
412     or $self->ut_numbern('expiration_date')
413     or $self->SUPER::check;
414
415 }
416
417 sub _check_duplicate {
418   my $self = shift;
419
420   $self->lock_table;
421
422   if ( qsearchs( 'svc_domain', { 'domain' => $self->domain } ) ) {
423     return "Domain in use (here)";
424   } else {
425     return '';
426   }
427 }
428
429 =item domain_record
430
431 =cut
432
433 sub domain_record {
434   my $self = shift;
435
436   my %order = (
437     'SOA'   => 1,
438     'NS'    => 2,
439     'MX'    => 3,
440     'CNAME' => 4,
441     'A'     => 5,
442     'TXT'   => 6,
443     'PTR'   => 7,
444   );
445
446   my %sort = (
447     #'SOA'   => sub { $_[0]->recdata cmp $_[1]->recdata }, #sure hope not though
448 #    'SOA'   => sub { 0; },
449 #    'NS'    => sub { 0; },
450     'MX'    => sub { my( $a_weight, $a_name ) = split(/\s+/, $_[0]->recdata);
451                      my( $b_weight, $b_name ) = split(/\s+/, $_[1]->recdata);
452                      $a_weight <=> $b_weight or $a_name cmp $b_name;
453                    },
454     'CNAME' => sub { $_[0]->reczone cmp $_[1]->reczone },
455     'A'     => sub { $_[0]->reczone cmp $_[1]->reczone },
456
457 #    'TXT'   => sub { 0; },
458     'PTR'   => sub { $_[0]->reczone <=> $_[1]->reczone },
459   );
460
461   map { $_ } #return $self->num_domain_record( PARAMS ) unless wantarray;
462   sort {    $order{$a->rectype} <=> $order{$b->rectype}
463          or &{ $sort{$a->rectype} || sub { 0; } }($a, $b)
464        }
465        qsearch('domain_record', { svcnum => $self->svcnum } );
466
467 }
468
469 sub catchall_svc_acct {
470   my $self = shift;
471   if ( $self->catchall ) {
472     qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } );
473   } else {
474     '';
475   }
476 }
477
478 =item whois
479
480 # Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
481 # undef if the domain is not found in whois.
482
483 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
484
485 =cut
486
487 sub whois {
488   #$whois_hack or new Net::Whois::Domain $_[0]->domain;
489   #$whois_hack or die "whois_hack not set...\n";
490 }
491
492 =back
493
494 =head1 BUGS
495
496 Delete doesn't send a registration template.
497
498 All registries should be supported.
499
500 Should change action to a real field.
501
502 The $recref stuff in sub check should be cleaned up.
503
504 =head1 SEE ALSO
505
506 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
507 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, schema.html from the base
508 documentation, config.html from the base documentation.
509
510 =cut
511
512 1;
513
514