communigate (phase 2): Account Preferences (& Domain::Account Defaults:Preferences...
[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                             disable_inventory => 1,
148                             disable_select    => 1,
149                                },
150       'acct_def_password_recover'    => { label => 'Acct. default Password recovery',
151                                  type  => 'checkbox',
152                             disable_inventory => 1,
153                             disable_select    => 1,
154                                },
155       'acct_def_cgp_deletemode' => { 
156                             label => 'Acct. default Communigate message delete method',
157                             type  => 'select',
158                             select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
159                             disable_inventory => 1,
160                             disable_select    => 1,
161                           },
162       'acct_def_cgp_emptytrash' => { 
163                             label => 'Acct. default Communigate on logout remove trash',
164                             type  => 'text',
165                             disable_inventory => 1,
166                             disable_select    => 1,
167                           },
168       'acct_def_quota'     => { 
169                        label => 'Acct. default Quota', #Mail storage limit
170                        type => 'text',
171                        disable_inventory => 1,
172                        disable_select => 1,
173                      },
174       'acct_def_file_quota'=> { 
175                        label => 'Acct. default File storage limit',
176                        type => 'text',
177                        disable_inventory => 1,
178                        disable_select => 1,
179                      },
180       'acct_def_file_maxnum'=> { 
181                        label => 'Acct. default Number of files limit',
182                        type => 'text',
183                        disable_inventory => 1,
184                        disable_select => 1,
185                      },
186       'acct_def_file_maxsize'=> { 
187                        label => 'Acct. default File size limit',
188                        type => 'text',
189                        disable_inventory => 1,
190                        disable_select => 1,
191                      },
192       'acct_def_cgp_rulesallowed'   => {
193         label       => 'Acct. default Allowed mail rules',
194         type        => 'select',
195         select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
196         disable_inventory => 1,
197         disable_select    => 1,
198       },
199       'acct_def_cgp_rpopallowed'    => {
200         label => 'Acct. default RPOP modifications',
201         type  => 'checkbox',
202       },
203       'acct_def_cgp_mailtoall'      => {
204         label => 'Acct. default Accepts mail to "all"',
205         type  => 'checkbox',
206       },
207       'acct_def_cgp_addmailtrailer' => {
208         label => 'Acct. default Add trailer to sent mail',
209         type  => 'checkbox',
210       },
211       'trailer' => {
212         label => 'Mail trailer',
213         type  => 'textarea',
214       },
215       'acct_def_cgp_language' => {
216                             label => 'Acct. default language',
217                             type  => 'select',
218                             select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
219                             disable_inventory => 1,
220                             disable_select    => 1,
221                         },
222       'acct_def_cgp_timezone' => {
223                             label => 'Acct. default time zone',
224                             type  => 'select',
225                             select_list => [ '',
226                                              'HostOS',
227                                              '(+0100) Algeria/Congo',
228                                              '(+0200) Egypt/South Africa',
229                                              '(+0300) Saudi Arabia',
230                                              '(+0400) Oman',
231                                              '(+0500) Pakistan',
232                                              '(+0600) Bangladesh',
233                                              '(+0700) Thailand/Vietnam',
234                                              '(+0800) China/Malaysia',
235                                              '(+0900) Japan/Korea',
236                                              '(+1000) Queensland',
237                                              '(+1100) Micronesia',
238                                              '(+1200) Fiji',
239                                              '(+1300) Tonga/Kiribati',
240                                              '(+1400) Christmas Islands',
241                                              '(-0100) Azores/Cape Verde',
242                                              '(-0200) Fernando de Noronha',
243                                              '(-0300) Argentina/Uruguay',
244                                              '(-0400) Venezuela/Guyana',
245                                              '(-0500) Haiti/Peru',
246                                              '(-0600) Central America',
247                                              '(-0700) Arisona',
248                                              '(-0800) Adamstown',
249                                              '(-0900) Marquesas Islands',
250                                              '(-1000) Hawaii/Tahiti',
251                                              '(-1100) Samoa',
252                                              'Asia/Afghanistan',
253                                              'Asia/India',
254                                              'Asia/Iran',
255                                              'Asia/Iraq',
256                                              'Asia/Israel',
257                                              'Asia/Jordan',
258                                              'Asia/Lebanon',
259                                              'Asia/Syria',
260                                              'Australia/Adelaide',
261                                              'Australia/East',
262                                              'Australia/NorthernTerritory',
263                                              'Europe/Central',
264                                              'Europe/Eastern',
265                                              'Europe/Moscow',
266                                              'Europe/Western',
267                                              'GMT (+0000)',
268                                              'Newfoundland',
269                                              'NewZealand/Auckland',
270                                              'NorthAmerica/Alaska',
271                                              'NorthAmerica/Atlantic',
272                                              'NorthAmerica/Central',
273                                              'NorthAmerica/Eastern',
274                                              'NorthAmerica/Mountain',
275                                              'NorthAmerica/Pacific',
276                                              'Russia/Ekaterinburg',
277                                              'Russia/Irkutsk',
278                                              'Russia/Kamchatka',
279                                              'Russia/Krasnoyarsk',
280                                              'Russia/Magadan',
281                                              'Russia/Novosibirsk',
282                                              'Russia/Vladivostok',
283                                              'Russia/Yakutsk',
284                                              'SouthAmerica/Brasil',
285                                              'SouthAmerica/Chile',
286                                              'SouthAmerica/Paraguay',
287                                            ],
288                             disable_inventory => 1,
289                             disable_select    => 1,
290                         },
291       'acct_def_cgp_skinname' => {
292                             label => 'Acct. default layout',
293                             type  => 'select',
294                             select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
295                             disable_inventory => 1,
296                             disable_select    => 1,
297                         },
298       'acct_def_cgp_prontoskinname' => {
299                             label => 'Acct. default Pronto style',
300                             type  => 'select',
301                             select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
302                             disable_inventory => 1,
303                             disable_select    => 1,
304                         },
305       'acct_def_cgp_sendmdnmode' => {
306         label => 'Acct. default send read receipts',
307         type  => 'select',
308         select_list => [ '', 'Never', 'Manually', 'Automatically' ],
309         disable_inventory => 1,
310         disable_select    => 1,
311       },
312     },
313   };
314 }
315
316 sub table { 'svc_domain'; }
317
318 sub search_sql {
319   my($class, $string) = @_;
320   $class->search_sql_field('domain', $string);
321 }
322
323
324 =item label
325
326 Returns the domain.
327
328 =cut
329
330 sub label {
331   my $self = shift;
332   $self->domain;
333 }
334
335 =item insert [ , OPTION => VALUE ... ]
336
337 Adds this domain to the database.  If there is an error, returns the error,
338 otherwise returns false.
339
340 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
341 defined.  An FS::cust_svc record will be created and inserted.
342
343 The additional field I<action> should be set to I<N> for new domains, I<M>
344 for transfers, or I<I> for no action (registered elsewhere).
345
346 A registration or transfer email will be submitted unless
347 $FS::svc_domain::whois_hack is true.
348
349 The additional field I<email> can be used to manually set the admin contact
350 email address on this email.  Otherwise, the svc_acct records for this package 
351 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
352 in the same package, it is automatically used.  Otherwise an error is returned.
353
354 If any I<soamachine> configuration file exists, an SOA record is added to
355 the domain_record table (see <FS::domain_record>).
356
357 If any records are defined in the I<defaultrecords> configuration file,
358 appropriate records are added to the domain_record table (see
359 L<FS::domain_record>).
360
361 Currently available options are: I<depend_jobnum>
362
363 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
364 jobnums), all provisioning jobs will have a dependancy on the supplied
365 jobnum(s) (they will not run until the specific job(s) complete(s)).
366
367 =cut
368
369 sub insert {
370   my $self = shift;
371   my $error;
372
373   local $SIG{HUP} = 'IGNORE';
374   local $SIG{INT} = 'IGNORE';
375   local $SIG{QUIT} = 'IGNORE';
376   local $SIG{TERM} = 'IGNORE';
377   local $SIG{TSTP} = 'IGNORE';
378   local $SIG{PIPE} = 'IGNORE';
379
380   my $oldAutoCommit = $FS::UID::AutoCommit;
381   local $FS::UID::AutoCommit = 0;
382   my $dbh = dbh;
383
384   $error = $self->SUPER::insert(@_);
385   if ( $error ) {
386     $dbh->rollback if $oldAutoCommit;
387     return $error;
388   }
389
390   if ( $soamachine ) {
391     my $soa = new FS::domain_record {
392       'svcnum'  => $self->svcnum,
393       'reczone' => '@',
394       'recaf'   => 'IN',
395       'rectype' => 'SOA',
396       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
397                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
398     };
399     $error = $soa->insert;
400     if ( $error ) {
401       $dbh->rollback if $oldAutoCommit;
402       return "couldn't insert SOA record for new domain: $error";
403     }
404
405     foreach my $record ( @defaultrecords ) {
406       my($zone,$af,$type,$data) = split(/\s+/,$record,4);
407       my $domain_record = new FS::domain_record {
408         'svcnum'  => $self->svcnum,
409         'reczone' => $zone,
410         'recaf'   => $af,
411         'rectype' => $type,
412         'recdata' => $data,
413       };
414       my $error = $domain_record->insert;
415       if ( $error ) {
416         $dbh->rollback if $oldAutoCommit;
417         return "couldn't insert record for new domain: $error";
418       }
419     }
420
421   }
422
423   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
424
425   ''; #no error
426 }
427
428 =item delete
429
430 Deletes this domain from the database.  If there is an error, returns the
431 error, otherwise returns false.
432
433 The corresponding FS::cust_svc record will be deleted as well.
434
435 =cut
436
437 sub delete {
438   my $self = shift;
439
440   return "Can't delete a domain which has accounts!"
441     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
442
443   #return "Can't delete a domain with (domain_record) zone entries!"
444   #  if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
445
446   local $SIG{HUP} = 'IGNORE';
447   local $SIG{INT} = 'IGNORE';
448   local $SIG{QUIT} = 'IGNORE';
449   local $SIG{TERM} = 'IGNORE';
450   local $SIG{TSTP} = 'IGNORE';
451   local $SIG{PIPE} = 'IGNORE';
452
453   my $oldAutoCommit = $FS::UID::AutoCommit;
454   local $FS::UID::AutoCommit = 0;
455   my $dbh = dbh;
456
457   foreach my $domain_record ( reverse $self->domain_record ) {
458     my $error = $domain_record->delete;
459     if ( $error ) {
460       $dbh->rollback if $oldAutoCommit;
461       return "can't delete DNS entry: ".
462              join(' ', map $domain_record->$_(),
463                            qw( reczone recaf rectype recdata )
464                  ).
465              ":$error";
466     }
467   }
468
469   my $error = $self->SUPER::delete(@_);
470   if ( $error ) {
471     $dbh->rollback if $oldAutoCommit;
472     return $error;
473   }
474
475   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
476 }
477
478 =item replace OLD_RECORD
479
480 Replaces OLD_RECORD with this one in the database.  If there is an error,
481 returns the error, otherwise returns false.
482
483 =cut
484
485 sub replace {
486   my $new = shift;
487
488   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
489               ? shift
490               : $new->replace_old;
491
492   return "Can't change domain - reorder."
493     if $old->getfield('domain') ne $new->getfield('domain')
494     && ! $conf->exists('svc_domain-edit_domain'); 
495
496   # Better to do it here than to force the caller to remember that svc_domain is weird.
497   $new->setfield(action => 'I');
498   my $error = $new->SUPER::replace($old, @_);
499   return $error if $error;
500 }
501
502 =item suspend
503
504 Just returns false (no error) for now.
505
506 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
507
508 =item unsuspend
509
510 Just returns false (no error) for now.
511
512 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
513
514 =item cancel
515
516 Just returns false (no error) for now.
517
518 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
519
520 =item check
521
522 Checks all fields to make sure this is a valid domain.  If there is an error,
523 returns the error, otherwise returns false.  Called by the insert and replace
524 methods.
525
526 Sets any fixed values; see L<FS::part_svc>.
527
528 =cut
529
530 sub check {
531   my $self = shift;
532
533   my $x = $self->setfixed;
534   return $x unless ref($x);
535   #my $part_svc = $x;
536
537   my $error = $self->ut_numbern('svcnum')
538               || $self->ut_numbern('catchall')
539               || $self->ut_numbern('max_accounts')
540               || $self->ut_anything('trailer') #well
541               || $self->ut_textn('cgp_aliases') #well
542               || $self->ut_enum('acct_def_password_selfchange', [ '', 'Y' ])
543               || $self->ut_enum('acct_def_password_recover',    [ '', 'Y' ])
544               || $self->ut_textn('acct_def_cgp_accessmodes')
545               || $self->ut_alphan('acct_def_quota')
546               || $self->ut_alphan('acct_def_file_quota')
547               || $self->ut_alphan('acct_def_maxnum')
548               || $self->ut_alphan('acct_def_maxsize')
549               #settings
550               || $self->ut_alphasn('acct_def_cgp_rulesallowed')
551               || $self->ut_enum('acct_def_cgp_rpopallowed', [ '', 'Y' ])
552               || $self->ut_enum('acct_def_cgp_mailtoall', [ '', 'Y' ])
553               || $self->ut_enum('acct_def_cgp_addmailtrailer', [ '', 'Y' ])
554               #XXX archive messages
555               #preferences
556               || $self->ut_alphasn('acct_def_cgp_deletemode')
557               || $self->ut_alphan('acct_def_cgp_emptytrash')
558               || $self->ut_alphan('acct_def_cgp_language')
559               || $self->ut_textn('acct_def_cgp_timezone')
560               || $self->ut_textn('acct_def_cgp_skinname')
561               || $self->ut_textn('acct_def_cgp_prontoskinname')
562               || $self->ut_alphan('acct_def_cgp_sendmdnmode')
563               #mail
564               #XXX rules, archive rule, spam foldering rule(s)
565   ;
566   return $error if $error;
567
568   #hmm
569   my $pkgnum;
570   if ( $self->svcnum ) {
571     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
572     $pkgnum = $cust_svc->pkgnum;
573   } else {
574     $pkgnum = $self->pkgnum;
575   }
576
577   my($recref) = $self->hashref;
578
579   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
580   if ( $recref->{domain} =~ /^([\w\-]{1,63})\.(com|net|org|edu|tv|info|biz)$/ ) {
581     $recref->{domain} = "$1.$2";
582     $recref->{suffix} ||= $2;
583   # hmmmmmmmm.
584   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)\.(\w+)$/ ) {
585     $recref->{domain} = "$1.$2";
586     # need to match a list of suffixes - no guarantee they're top-level..
587     # http://wiki.mozilla.org/TLD_List
588     # but this will have to do for now...
589     $recref->{suffix} ||= $2;
590   } else {
591     return "Illegal domain ". $recref->{domain}.
592            " (or unknown registry - try \$whois_hack)";
593   }
594
595   $self->suffix =~ /(^|\.)(\w+)$/
596     or return "can't parse suffix for TLD: ". $self->suffix;
597   my $tld = $2;
598   return "No such TLD: .$tld" unless tld_exists($tld);
599
600   if ( $recref->{catchall} ne '' ) {
601     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
602     return "Unknown catchall" unless $svc_acct;
603   }
604
605   $self->ut_alphan('suffix')
606     or $self->ut_foreign_keyn('registrarnum', 'registrar', 'registrarnum')
607     or $self->ut_textn('registrarkey')
608     or $self->ut_numbern('setup_date')
609     or $self->ut_numbern('renewal_interval')
610     or $self->ut_numbern('expiration_date')
611     or $self->SUPER::check;
612
613 }
614
615 sub _check_duplicate {
616   my $self = shift;
617
618   $self->lock_table;
619
620   if ( qsearchs( 'svc_domain', { 'domain' => $self->domain } ) ) {
621     return "Domain in use (here)";
622   } else {
623     return '';
624   }
625 }
626
627 =item domain_record
628
629 =cut
630
631 sub domain_record {
632   my $self = shift;
633
634   my %order = (
635     'SOA'   => 1,
636     'NS'    => 2,
637     'MX'    => 3,
638     'CNAME' => 4,
639     'A'     => 5,
640     'TXT'   => 6,
641     'PTR'   => 7,
642   );
643
644   my %sort = (
645     #'SOA'   => sub { $_[0]->recdata cmp $_[1]->recdata }, #sure hope not though
646 #    'SOA'   => sub { 0; },
647 #    'NS'    => sub { 0; },
648     'MX'    => sub { my( $a_weight, $a_name ) = split(/\s+/, $_[0]->recdata);
649                      my( $b_weight, $b_name ) = split(/\s+/, $_[1]->recdata);
650                      $a_weight <=> $b_weight or $a_name cmp $b_name;
651                    },
652     'CNAME' => sub { $_[0]->reczone cmp $_[1]->reczone },
653     'A'     => sub { $_[0]->reczone cmp $_[1]->reczone },
654
655 #    'TXT'   => sub { 0; },
656     'PTR'   => sub { $_[0]->reczone <=> $_[1]->reczone },
657   );
658
659   map { $_ } #return $self->num_domain_record( PARAMS ) unless wantarray;
660   sort {    $order{$a->rectype} <=> $order{$b->rectype}
661          or &{ $sort{$a->rectype} || sub { 0; } }($a, $b)
662        }
663        qsearch('domain_record', { svcnum => $self->svcnum } );
664
665 }
666
667 sub catchall_svc_acct {
668   my $self = shift;
669   if ( $self->catchall ) {
670     qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } );
671   } else {
672     '';
673   }
674 }
675
676 =item whois
677
678 # Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
679 # undef if the domain is not found in whois.
680
681 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
682
683 =cut
684
685 sub whois {
686   #$whois_hack or new Net::Whois::Domain $_[0]->domain;
687   #$whois_hack or die "whois_hack not set...\n";
688 }
689
690 =back
691
692 =head1 BUGS
693
694 Delete doesn't send a registration template.
695
696 All registries should be supported.
697
698 Should change action to a real field.
699
700 The $recref stuff in sub check should be cleaned up.
701
702 =head1 SEE ALSO
703
704 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
705 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, schema.html from the base
706 documentation, config.html from the base documentation.
707
708 =cut
709
710 1;
711
712