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