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