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