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