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