DNS, RT#8933
[freeside.git] / FS / FS / svc_domain.pm
1 package FS::svc_domain;
2
3 use strict;
4 use base qw( FS::svc_Parent_Mixin FS::svc_CGP_Mixin FS::svc_CGPRule_Mixin
5              FS::svc_Common );
6 use vars qw( $whois_hack $conf
7   @defaultrecords $soadefaultttl $soaemail $soaexpire $soamachine
8   $soarefresh $soaretry
9 );
10 use Carp;
11 use Scalar::Util qw( blessed );
12 use Date::Format;
13 #use Net::Whois::Raw;
14 use Net::Domain::TLD qw(tld_exists);
15 use FS::Record qw(fields qsearch qsearchs dbh);
16 use FS::Conf;
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 #ask FS::UID to run this stuff for us later
25 $FS::UID::callback{'FS::domain'} = sub { 
26   $conf = new FS::Conf;
27
28   @defaultrecords = $conf->config('defaultrecords');
29   $soadefaultttl = $conf->config('soadefaultttl');
30   $soaemail      = $conf->config('soaemail');
31   $soaexpire     = $conf->config('soaexpire');
32   $soamachine    = $conf->config('soamachine');
33   $soarefresh    = $conf->config('soarefresh');
34   $soaretry      = $conf->config('soaretry');
35
36 };
37
38 =head1 NAME
39
40 FS::svc_domain - Object methods for svc_domain records
41
42 =head1 SYNOPSIS
43
44   use FS::svc_domain;
45
46   $record = new FS::svc_domain \%hash;
47   $record = new FS::svc_domain { 'column' => 'value' };
48
49   $error = $record->insert;
50
51   $error = $new_record->replace($old_record);
52
53   $error = $record->delete;
54
55   $error = $record->check;
56
57   $error = $record->suspend;
58
59   $error = $record->unsuspend;
60
61   $error = $record->cancel;
62
63 =head1 DESCRIPTION
64
65 An FS::svc_domain object represents a domain.  FS::svc_domain inherits from
66 FS::svc_Common.  The following fields are currently supported:
67
68 =over 4
69
70 =item svcnum - primary key (assigned automatically for new accounts)
71
72 =item domain
73
74 =item catchall - optional svcnum of an svc_acct record, designating an email catchall account.
75
76 =item suffix - 
77
78 =item parent_svcnum -
79
80 =item registrarnum - Registrar (see L<FS::registrar>)
81
82 =item registrarkey - Registrar key or password for this domain
83
84 =item setup_date - UNIX timestamp
85
86 =item renewal_interval - Number of days before expiration date to start renewal
87
88 =item expiration_date - UNIX timestamp
89
90 =item max_accounts
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       'parent_svcnum' => { 
113                          label => 'Parent domain / Communigate administrator domain',
114                          type  => 'select',
115                          select_table => 'svc_domain',
116                          select_key => 'svcnum',
117                          select_label => 'domain',
118                          disable_inventory => 1,
119                          disable_select    => 1,
120                        },
121       'max_accounts' => { label => 'Maximum number of accounts',
122                           'disable_inventory' => 1,
123                         },
124       'cgp_aliases' => { 
125                          label => 'Communigate aliases',
126                          type  => 'text',
127                          disable_inventory => 1,
128                          disable_select    => 1,
129                        },
130       'cgp_accessmodes' => { 
131                              label => 'Communigate enabled services',
132                              type  => 'communigate_pro-accessmodes',
133                              disable_inventory => 1,
134                              disable_select    => 1,
135                            },
136
137       'acct_def_cgp_accessmodes' => { 
138                              label => 'Acct. default Communigate enabled services',
139                              type  => 'communigate_pro-accessmodes',
140                              disable_inventory => 1,
141                              disable_select    => 1,
142                            },
143       'acct_def_password_selfchange' => { label => 'Acct. default Password modification',
144                                  type  => 'checkbox',
145                             disable_inventory => 1,
146                             disable_select    => 1,
147                                },
148       'acct_def_password_recover'    => { label => 'Acct. default Password recovery',
149                                  type  => 'checkbox',
150                             disable_inventory => 1,
151                             disable_select    => 1,
152                                },
153       'acct_def_cgp_deletemode' => { 
154                             label => 'Acct. default Communigate message delete method',
155                             type  => 'select',
156                             select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
157                             disable_inventory => 1,
158                             disable_select    => 1,
159                           },
160       'acct_def_cgp_emptytrash' => { 
161                             label => 'Acct. default Communigate on logout remove trash',
162                             type        => 'select',
163                             select_list => __PACKAGE__->cgp_emptytrash_values,
164                             disable_inventory => 1,
165                             disable_select    => 1,
166                           },
167       'acct_def_quota'     => { 
168                        label => 'Acct. default Quota', #Mail storage limit
169                        type => 'text',
170                        disable_inventory => 1,
171                        disable_select => 1,
172                      },
173       'acct_def_file_quota'=> { 
174                        label => 'Acct. default File storage limit',
175                        type => 'text',
176                        disable_inventory => 1,
177                        disable_select => 1,
178                      },
179       'acct_def_file_maxnum'=> { 
180                        label => 'Acct. default Number of files limit',
181                        type => 'text',
182                        disable_inventory => 1,
183                        disable_select => 1,
184                      },
185       'acct_def_file_maxsize'=> { 
186                        label => 'Acct. default File size limit',
187                        type => 'text',
188                        disable_inventory => 1,
189                        disable_select => 1,
190                      },
191       'acct_def_cgp_rulesallowed'   => {
192         label       => 'Acct. default Allowed mail rules',
193         type        => 'select',
194         select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
195         disable_inventory => 1,
196         disable_select    => 1,
197       },
198       'acct_def_cgp_rpopallowed'    => {
199         label => 'Acct. default RPOP modifications',
200         type  => 'checkbox',
201       },
202       'acct_def_cgp_mailtoall'      => {
203         label => 'Acct. default Accepts mail to "all"',
204         type  => 'checkbox',
205       },
206       'acct_def_cgp_addmailtrailer' => {
207         label => 'Acct. default Add trailer to sent mail',
208         type  => 'checkbox',
209       },
210       'acct_def_cgp_archiveafter'   => {
211         label       => 'Archive messages after',
212         type        => 'select',
213         select_hash => [ 
214                          -2 => 'default(730 days)',
215                          0 => 'Never',
216                          86400 => '24 hours',
217                          172800 => '2 days',
218                          259200 => '3 days',
219                          432000 => '5 days',
220                          604800 => '7 days',
221                          1209600 => '2 weeks',
222                          2592000 => '30 days',
223                          7776000 => '90 days',
224                          15552000 => '180 days',
225                          31536000 => '365 days',
226                          63072000 => '730 days',
227                        ],
228         disable_inventory => 1,
229         disable_select    => 1,
230       },
231       'trailer' => {
232         label => 'Mail trailer',
233         type  => 'textarea',
234         disable_inventory => 1,
235         disable_select    => 1,
236       },
237       'acct_def_cgp_language' => {
238                             label => 'Acct. default language',
239                             type  => 'select',
240                             select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
241                             disable_inventory => 1,
242                             disable_select    => 1,
243                         },
244       'acct_def_cgp_timezone' => {
245                             label       => 'Acct. default time zone',
246                             type        => 'select',
247                             select_list => __PACKAGE__->cgp_timezone_values,
248                             disable_inventory => 1,
249                             disable_select    => 1,
250                         },
251       'acct_def_cgp_skinname' => {
252                             label => 'Acct. default layout',
253                             type  => 'select',
254                             select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
255                             disable_inventory => 1,
256                             disable_select    => 1,
257                         },
258       'acct_def_cgp_prontoskinname' => {
259                             label => 'Acct. default Pronto style',
260                             type  => 'select',
261                             select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
262                             disable_inventory => 1,
263                             disable_select    => 1,
264                         },
265       'acct_def_cgp_sendmdnmode' => {
266         label => 'Acct. default send read receipts',
267         type  => 'select',
268         select_list => [ '', 'Never', 'Manually', 'Automatically' ],
269         disable_inventory => 1,
270         disable_select    => 1,
271       },
272     },
273   };
274 }
275
276 sub table { 'svc_domain'; }
277
278 sub search_sql {
279   my($class, $string) = @_;
280   $class->search_sql_field('domain', $string);
281 }
282
283
284 =item label
285
286 Returns the domain.
287
288 =cut
289
290 sub label {
291   my $self = shift;
292   $self->domain;
293 }
294
295 =item insert [ , OPTION => VALUE ... ]
296
297 Adds this domain to the database.  If there is an error, returns the error,
298 otherwise returns false.
299
300 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
301 defined.  An FS::cust_svc record will be created and inserted.
302
303 The additional field I<action> should be set to I<N> for new domains, I<M>
304 for transfers, or I<I> for no action (registered elsewhere).
305
306 A registration or transfer email will be submitted unless
307 $FS::svc_domain::whois_hack is true.
308
309 The additional field I<email> can be used to manually set the admin contact
310 email address on this email.  Otherwise, the svc_acct records for this package 
311 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
312 in the same package, it is automatically used.  Otherwise an error is returned.
313
314 If any I<soamachine> configuration file exists, an SOA record is added to
315 the domain_record table (see <FS::domain_record>).
316
317 If any records are defined in the I<defaultrecords> configuration file,
318 appropriate records are added to the domain_record table (see
319 L<FS::domain_record>).
320
321 Currently available options are: I<depend_jobnum>
322
323 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
324 jobnums), all provisioning jobs will have a dependancy on the supplied
325 jobnum(s) (they will not run until the specific job(s) complete(s)).
326
327 =cut
328
329 sub insert {
330   my $self = shift;
331   my $error;
332
333   local $SIG{HUP} = 'IGNORE';
334   local $SIG{INT} = 'IGNORE';
335   local $SIG{QUIT} = 'IGNORE';
336   local $SIG{TERM} = 'IGNORE';
337   local $SIG{TSTP} = 'IGNORE';
338   local $SIG{PIPE} = 'IGNORE';
339
340   my $oldAutoCommit = $FS::UID::AutoCommit;
341   local $FS::UID::AutoCommit = 0;
342   my $dbh = dbh;
343
344   $error =  $self->SUPER::insert(@_)
345          || $self->insert_defaultrecords;
346   if ( $error ) {
347     $dbh->rollback if $oldAutoCommit;
348     return $error;
349   }
350
351   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
352
353   ''; #no error
354 }
355
356 =item insert_defaultrecords
357
358 =cut
359
360 sub insert_defaultrecords {
361   my $self = shift;
362
363   local $SIG{HUP} = 'IGNORE';
364   local $SIG{INT} = 'IGNORE';
365   local $SIG{QUIT} = 'IGNORE';
366   local $SIG{TERM} = 'IGNORE';
367   local $SIG{TSTP} = 'IGNORE';
368   local $SIG{PIPE} = 'IGNORE';
369
370   my $oldAutoCommit = $FS::UID::AutoCommit;
371   local $FS::UID::AutoCommit = 0;
372   my $dbh = dbh;
373
374   if ( $soamachine ) {
375     my $soa = new FS::domain_record {
376       'svcnum'  => $self->svcnum,
377       'reczone' => '@',
378       'recaf'   => 'IN',
379       'rectype' => 'SOA',
380       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
381                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
382     };
383     my $error = $soa->insert;
384     if ( $error ) {
385       $dbh->rollback if $oldAutoCommit;
386       return "couldn't insert SOA record: $error";
387     }
388
389     foreach my $record ( @defaultrecords ) {
390       my($zone,$af,$type,$data) = split(/\s+/,$record,4);
391       my $domain_record = new FS::domain_record {
392         'svcnum'  => $self->svcnum,
393         'reczone' => $zone,
394         'recaf'   => $af,
395         'rectype' => $type,
396         'recdata' => $data,
397       };
398       my $error = $domain_record->insert;
399       if ( $error ) {
400         $dbh->rollback if $oldAutoCommit;
401         return "couldn't insert record: $error";
402       }
403     }
404
405   }
406
407   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
408
409   ''; #no error
410 }
411
412 =item delete
413
414 Deletes this domain from the database.  If there is an error, returns the
415 error, otherwise returns false.
416
417 The corresponding FS::cust_svc record will be deleted as well.
418
419 =cut
420
421 sub delete {
422   my $self = shift;
423
424   return "Can't delete a domain which has accounts!"
425     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
426
427   #return "Can't delete a domain with (domain_record) zone entries!"
428   #  if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
429
430   local $SIG{HUP} = 'IGNORE';
431   local $SIG{INT} = 'IGNORE';
432   local $SIG{QUIT} = 'IGNORE';
433   local $SIG{TERM} = 'IGNORE';
434   local $SIG{TSTP} = 'IGNORE';
435   local $SIG{PIPE} = 'IGNORE';
436
437   my $oldAutoCommit = $FS::UID::AutoCommit;
438   local $FS::UID::AutoCommit = 0;
439   my $dbh = dbh;
440
441   foreach my $domain_record ( reverse $self->domain_record ) {
442     my $error = $domain_record->delete;
443     if ( $error ) {
444       $dbh->rollback if $oldAutoCommit;
445       return "can't delete DNS entry: ".
446              join(' ', map $domain_record->$_(),
447                            qw( reczone recaf rectype recdata )
448                  ).
449              ":$error";
450     }
451   }
452
453   my $error = $self->SUPER::delete(@_);
454   if ( $error ) {
455     $dbh->rollback if $oldAutoCommit;
456     return $error;
457   }
458
459   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
460 }
461
462 =item replace OLD_RECORD
463
464 Replaces OLD_RECORD with this one in the database.  If there is an error,
465 returns the error, otherwise returns false.
466
467 =cut
468
469 sub replace {
470   my $new = shift;
471
472   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
473               ? shift
474               : $new->replace_old;
475
476   return "Can't change domain - reorder."
477     if $old->getfield('domain') ne $new->getfield('domain')
478     && ! $conf->exists('svc_domain-edit_domain'); 
479
480   # Better to do it here than to force the caller to remember that svc_domain is weird.
481   $new->setfield(action => 'I');
482   my $error = $new->SUPER::replace($old, @_);
483   return $error if $error;
484 }
485
486 =item suspend
487
488 Just returns false (no error) for now.
489
490 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
491
492 =item unsuspend
493
494 Just returns false (no error) for now.
495
496 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
497
498 =item cancel
499
500 Just returns false (no error) for now.
501
502 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
503
504 =item check
505
506 Checks all fields to make sure this is a valid domain.  If there is an error,
507 returns the error, otherwise returns false.  Called by the insert and replace
508 methods.
509
510 Sets any fixed values; see L<FS::part_svc>.
511
512 =cut
513
514 sub check {
515   my $self = shift;
516
517   my $x = $self->setfixed;
518   return $x unless ref($x);
519   #my $part_svc = $x;
520
521   my $error = $self->ut_numbern('svcnum')
522               || $self->ut_numbern('catchall')
523               || $self->ut_numbern('max_accounts')
524               || $self->ut_anything('trailer') #well
525               || $self->ut_textn('cgp_aliases') #well
526               || $self->ut_enum('acct_def_password_selfchange', [ '', 'Y' ])
527               || $self->ut_enum('acct_def_password_recover',    [ '', 'Y' ])
528               || $self->ut_textn('acct_def_cgp_accessmodes')
529               || $self->ut_alphan('acct_def_quota')
530               || $self->ut_alphan('acct_def_file_quota')
531               || $self->ut_alphan('acct_def_maxnum')
532               || $self->ut_alphan('acct_def_maxsize')
533               #settings
534               || $self->ut_alphasn('acct_def_cgp_rulesallowed')
535               || $self->ut_enum('acct_def_cgp_rpopallowed', [ '', 'Y' ])
536               || $self->ut_enum('acct_def_cgp_mailtoall', [ '', 'Y' ])
537               || $self->ut_enum('acct_def_cgp_addmailtrailer', [ '', 'Y' ])
538               || $self->ut_snumbern('acct_def_cgp_archiveafter')
539               #preferences
540               || $self->ut_alphasn('acct_def_cgp_deletemode')
541               || $self->ut_enum('acct_def_cgp_emptytrash',
542                                    $self->cgp_emptytrash_values )
543               || $self->ut_alphan('acct_def_cgp_language')
544               || $self->ut_textn('acct_def_cgp_timezone')
545               || $self->ut_textn('acct_def_cgp_skinname')
546               || $self->ut_textn('acct_def_cgp_prontoskinname')
547               || $self->ut_alphan('acct_def_cgp_sendmdnmode')
548               #mail
549   ;
550   return $error if $error;
551
552   #hmm
553   my $pkgnum;
554   if ( $self->svcnum ) {
555     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
556     $pkgnum = $cust_svc->pkgnum;
557   } else {
558     $pkgnum = $self->pkgnum;
559   }
560
561   my($recref) = $self->hashref;
562
563   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
564   if ( $recref->{domain} =~ /^([\w\-]{1,63})\.(com|net|org|edu|tv|info|biz)$/ ) {
565     $recref->{domain} = "$1.$2";
566     $recref->{suffix} ||= $2;
567   # hmmmmmmmm.
568   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)\.(\w+)$/ ) {
569     $recref->{domain} = "$1.$2";
570     # need to match a list of suffixes - no guarantee they're top-level..
571     # http://wiki.mozilla.org/TLD_List
572     # but this will have to do for now...
573     $recref->{suffix} ||= $2;
574   } else {
575     return "Illegal domain ". $recref->{domain}.
576            " (or unknown registry - try \$whois_hack)";
577   }
578
579   $self->suffix =~ /(^|\.)(\w+)$/
580     or return "can't parse suffix for TLD: ". $self->suffix;
581   my $tld = $2;
582   return "No such TLD: .$tld" unless tld_exists($tld);
583
584   if ( $recref->{catchall} ne '' ) {
585     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
586     return "Unknown catchall" unless $svc_acct;
587   }
588
589   $self->ut_alphan('suffix')
590     or $self->ut_foreign_keyn('registrarnum', 'registrar', 'registrarnum')
591     or $self->ut_textn('registrarkey')
592     or $self->ut_numbern('setup_date')
593     or $self->ut_numbern('renewal_interval')
594     or $self->ut_numbern('expiration_date')
595     or $self->SUPER::check;
596
597 }
598
599 sub _check_duplicate {
600   my $self = shift;
601
602   $self->lock_table;
603
604   if ( qsearchs( 'svc_domain', { 'domain' => $self->domain } ) ) {
605     return "Domain in use (here)";
606   } else {
607     return '';
608   }
609 }
610
611 =item domain_record
612
613 =cut
614
615 sub domain_record {
616   my $self = shift;
617
618   my %order = (
619     'SOA'   => 1,
620     'NS'    => 2,
621     'MX'    => 3,
622     'CNAME' => 4,
623     'A'     => 5,
624     'TXT'   => 6,
625     'PTR'   => 7,
626   );
627
628   my %sort = (
629     #'SOA'   => sub { $_[0]->recdata cmp $_[1]->recdata }, #sure hope not though
630 #    'SOA'   => sub { 0; },
631 #    'NS'    => sub { 0; },
632     'MX'    => sub { my( $a_weight, $a_name ) = split(/\s+/, $_[0]->recdata);
633                      my( $b_weight, $b_name ) = split(/\s+/, $_[1]->recdata);
634                      $a_weight <=> $b_weight or $a_name cmp $b_name;
635                    },
636     'CNAME' => sub { $_[0]->reczone cmp $_[1]->reczone },
637     'A'     => sub { $_[0]->reczone cmp $_[1]->reczone },
638
639 #    'TXT'   => sub { 0; },
640     'PTR'   => sub { $_[0]->reczone <=> $_[1]->reczone },
641   );
642
643   map { $_ } #return $self->num_domain_record( PARAMS ) unless wantarray;
644   sort {    $order{$a->rectype} <=> $order{$b->rectype}
645          or &{ $sort{$a->rectype} || sub { 0; } }($a, $b)
646        }
647        qsearch('domain_record', { svcnum => $self->svcnum } );
648
649 }
650
651 sub catchall_svc_acct {
652   my $self = shift;
653   if ( $self->catchall ) {
654     qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } );
655   } else {
656     '';
657   }
658 }
659
660 =item whois
661
662 # Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
663 # undef if the domain is not found in whois.
664
665 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
666
667 =cut
668
669 sub whois {
670   #$whois_hack or new Net::Whois::Domain $_[0]->domain;
671   #$whois_hack or die "whois_hack not set...\n";
672 }
673
674 =back
675
676 =head1 BUGS
677
678 Delete doesn't send a registration template.
679
680 All registries should be supported.
681
682 Should change action to a real field.
683
684 The $recref stuff in sub check should be cleaned up.
685
686 =head1 SEE ALSO
687
688 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
689 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, schema.html from the base
690 documentation, config.html from the base documentation.
691
692 =cut
693
694 1;
695
696