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