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