fix delete method for new databases
[freeside.git] / FS / FS / svc_domain.pm
1 package FS::svc_domain;
2
3 use strict;
4 use vars qw( @ISA $whois_hack $conf $smtpmachine
5   $tech_contact $from $to @nameservers @nameserver_ips @template
6   @mxmachines @nsmachines $soadefaultttl $soaemail $soaexpire $soamachine
7   $soarefresh $soaretry $qshellmachine $nossh_hack
8 );
9 use Carp;
10 use Mail::Internet;
11 use Mail::Header;
12 use Date::Format;
13 use Net::Whois 1.0;
14 use Net::SSH qw(ssh);
15 use FS::Record qw(fields qsearch qsearchs dbh);
16 use FS::Conf;
17 use FS::svc_Common;
18 use FS::cust_svc;
19 use FS::svc_acct;
20 use FS::cust_pkg;
21 use FS::cust_main;
22 use FS::domain_record;
23
24 @ISA = qw( 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   $smtpmachine = $conf->config('smtpmachine');
31
32   my($internic)="/registries/internic";
33   $tech_contact = $conf->config("$internic/tech_contact");
34   $from = $conf->config("$internic/from");
35   $to = $conf->config("$internic/to");
36   my(@ns) = $conf->config("$internic/nameservers");
37   @nameservers=map {
38     /^\s*\d+\.\d+\.\d+\.\d+\s+([^\s]+)\s*$/
39       or die "Illegal line in $internic/nameservers";
40     $1;
41   } @ns;
42   @nameserver_ips=map {
43     /^\s*(\d+\.\d+\.\d+\.\d+)\s+([^\s]+)\s*$/
44       or die "Illegal line in $internic/nameservers!";
45     $1;
46   } @ns;
47   @template = map { $_. "\n" } $conf->config("$internic/template");
48
49   @mxmachines    = $conf->config('mxmachines');
50   @nsmachines    = $conf->config('nsmachines');
51   $soadefaultttl = $conf->config('soadefaultttl');
52   $soaemail      = $conf->config('soaemail');
53   $soaexpire     = $conf->config('soaexpire');
54   $soamachine    = $conf->config('soamachine');
55   $soarefresh    = $conf->config('soarefresh');
56   $soaretry      = $conf->config('soaretry');
57
58   $qshellmachine = $conf->exists('qmailmachines')
59                    ? $conf->config('shellmachine')
60                    : '';
61 };
62
63 =head1 NAME
64
65 FS::svc_domain - Object methods for svc_domain records
66
67 =head1 SYNOPSIS
68
69   use FS::svc_domain;
70
71   $record = new FS::svc_domain \%hash;
72   $record = new FS::svc_domain { 'column' => 'value' };
73
74   $error = $record->insert;
75
76   $error = $new_record->replace($old_record);
77
78   $error = $record->delete;
79
80   $error = $record->check;
81
82   $error = $record->suspend;
83
84   $error = $record->unsuspend;
85
86   $error = $record->cancel;
87
88 =head1 DESCRIPTION
89
90 An FS::svc_domain object represents a domain.  FS::svc_domain inherits from
91 FS::svc_Common.  The following fields are currently supported:
92
93 =over 4
94
95 =item svcnum - primary key (assigned automatically for new accounts)
96
97 =item domain
98
99 =item catchall - optional svcnum of an svc_acct record, designating an email catchall account.
100
101 =back
102
103 =head1 METHODS
104
105 =over 4
106
107 =item new HASHREF
108
109 Creates a new domain.  To add the domain to the database, see L<"insert">.
110
111 =cut
112
113 sub table { 'svc_domain'; }
114
115 =item insert
116
117 Adds this domain to the database.  If there is an error, returns the error,
118 otherwise returns false.
119
120 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
121 defined.  An FS::cust_svc record will be created and inserted.
122
123 The additional field I<action> should be set to I<N> for new domains or I<M>
124 for transfers.
125
126 A registration or transfer email will be submitted unless
127 $FS::svc_domain::whois_hack is true.
128
129 The additional field I<email> can be used to manually set the admin contact
130 email address on this email.  Otherwise, the svc_acct records for this package 
131 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
132 in the same package, it is automatically used.  Otherwise an error is returned.
133
134 If any I<soamachine> configuration file exists, an SOA record is added to
135 the domain_record table (see <FS::domain_record>).
136
137 If any machines are defined in the I<nsmachines> configuration file, NS
138 records are added to the domain_record table (see L<FS::domain_record>).
139
140 If any machines are defined in the I<mxmachines> configuration file, MX
141 records are added to the domain_record table (see L<FS::domain_record>).
142
143 If a machine is defined in the I<shellmachine> configuration value, the
144 I<qmailmachines> configuration file exists, and the I<catchall> field points
145 to an an account with a home directory (see L<FS::svc_acct>), the command:
146
147   [ -e $dir/.qmail-$qdomain-defualt ] || {
148     touch $dir/.qmail-$qdomain-default;
149     chown $uid:$gid $dir/.qmail-$qdomain-default;
150   }
151
152 is executed on shellmachine via ssh (see L<dot-qmail/"EXTENSION ADDRESSES">).
153 This behaviour can be supressed by setting $FS::svc_domain::nossh_hack true.
154
155 a machine is defined
156 in the 
157
158 =cut
159
160 sub insert {
161   my $self = shift;
162   my $error;
163
164   local $SIG{HUP} = 'IGNORE';
165   local $SIG{INT} = 'IGNORE';
166   local $SIG{QUIT} = 'IGNORE';
167   local $SIG{TERM} = 'IGNORE';
168   local $SIG{TSTP} = 'IGNORE';
169   local $SIG{PIPE} = 'IGNORE';
170
171   my $oldAutoCommit = $FS::UID::AutoCommit;
172   local $FS::UID::AutoCommit = 0;
173   my $dbh = dbh;
174
175   $error = $self->check;
176   return $error if $error;
177
178   return "Domain in use (here)"
179     if qsearchs( 'svc_domain', { 'domain' => $self->domain } );
180
181   my $whois = $self->whois;
182   if ( $self->action eq "N" && ! $whois_hack && $whois ) {
183     $dbh->rollback if $oldAutoCommit;
184     return "Domain in use (see whois)";
185   }
186   if ( $self->action eq "M" && ! $whois ) {
187     $dbh->rollback if $oldAutoCommit;
188     return "Domain not found (see whois)";
189   }
190
191   $error = $self->SUPER::insert;
192   if ( $error ) {
193     $dbh->rollback if $oldAutoCommit;
194     return $error;
195   }
196
197   $self->submit_internic unless $whois_hack;
198
199   if ( $soamachine ) {
200     my $soa = new FS::domain_record {
201       'svcnum'  => $self->svcnum,
202       'reczone' => '@',
203       'recaf'   => 'IN',
204       'rectype' => 'SOA',
205       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
206                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
207     };
208     $error = $soa->insert;
209     if ( $error ) {
210       $dbh->rollback if $oldAutoCommit;
211       return "couldn't insert SOA record for new domain: $error";
212     }
213
214     foreach my $nsmachine ( @nsmachines ) {
215       my $ns = new FS::domain_record {
216         'svcnum'  => $self->svcnum,
217         'reczone' => '@',
218         'recaf'   => 'IN',
219         'rectype' => 'NS',
220         'recdata' => $nsmachine,
221       };
222       my $error = $ns->insert;
223       if ( $error ) {
224         $dbh->rollback if $oldAutoCommit;
225         return "couldn't insert NS record for new domain: $error";
226       }
227     }
228
229     foreach my $mxmachine ( @mxmachines ) {
230       my $mx = new FS::domain_record {
231         'svcnum'  => $self->svcnum,
232         'reczone' => '@',
233         'recaf'   => 'IN',
234         'rectype' => 'MX',
235         'recdata' => $mxmachine,
236       };
237       my $error = $mx->insert;
238       if ( $error ) {
239         $dbh->rollback if $oldAutoCommit;
240         return "couldn't insert MX record for new domain: $error";
241       }
242     }
243
244   }
245
246   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
247
248   if ( $qshellmachine && $self->catchall && ! $nossh_hack ) {
249     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } )
250       or warn "WARNING: inserted unknown catchall: ". $self->catchall;
251     if ( $svc_acct && $svc_acct->dir ) {
252       my $qdomain = $self->domain;
253       $qdomain =~ s/\./:/g; #see manpage for 'dot-qmail': EXTENSION ADDRESSES
254       my ( $uid, $gid, $dir ) = (
255         $svc_acct->uid,
256         $svc_acct->gid,
257         $svc_acct->dir,
258       );
259       ssh("root\@$qshellmachine", "[ -e $dir/.qmail-$qdomain-default ] || { touch $dir/.qmail-$qdomain-default; chown $uid:$gid $dir/.qmail-$qdomain-default; }");
260     }
261   }
262
263   ''; #no error
264 }
265
266 =item delete
267
268 Deletes this domain from the database.  If there is an error, returns the
269 error, otherwise returns false.
270
271 The corresponding FS::cust_svc record will be deleted as well.
272
273 =cut
274
275 sub delete {
276   my $self = shift;
277
278   return "Can't delete a domain which has accounts!"
279     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
280
281   return "Can't delete a domain with (svc_acct_sm) mail aliases!"
282     if defined( $FS::Record::dbdef->table('svc_acct_sm') )
283        && qsearch('svc_acct_sm', { 'domsvc' => $self->svcnum } );
284
285   return "Can't delete a domain with (domain_record) zone entries!"
286     if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
287
288   $self->SUPER::delete;
289 }
290
291 =item replace OLD_RECORD
292
293 Replaces OLD_RECORD with this one in the database.  If there is an error,
294 returns the error, otherwise returns false.
295
296 =cut
297
298 sub replace {
299   my ( $new, $old ) = ( shift, shift );
300   my $error;
301
302   return "Can't change domain - reorder."
303     if $old->getfield('domain') ne $new->getfield('domain'); 
304
305   $new->SUPER::replace($old);
306
307 }
308
309 =item suspend
310
311 Just returns false (no error) for now.
312
313 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
314
315 =item unsuspend
316
317 Just returns false (no error) for now.
318
319 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
320
321 =item cancel
322
323 Just returns false (no error) for now.
324
325 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
326
327 =item check
328
329 Checks all fields to make sure this is a valid domain.  If there is an error,
330 returns the error, otherwise returns false.  Called by the insert and replace
331 methods.
332
333 Sets any fixed values; see L<FS::part_svc>.
334
335 =cut
336
337 sub check {
338   my $self = shift;
339
340   my $x = $self->setfixed;
341   return $x unless ref($x);
342   #my $part_svc = $x;
343
344   my $error = $self->ut_numbern('svcnum')
345               || $self->ut_numbern('catchall')
346   ;
347   return $error if $error;
348
349   #hmm
350   my $pkgnum;
351   if ( $self->svcnum ) {
352     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
353     $pkgnum = $cust_svc->pkgnum;
354   } else {
355     $pkgnum = $self->pkgnum;
356   }
357
358   my($recref) = $self->hashref;
359
360   unless ( $whois_hack ) {
361     unless ( $self->email ) { #find out an email address
362       my @svc_acct;
363       foreach ( qsearch( 'cust_svc', { 'pkgnum' => $pkgnum } ) ) {
364         my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $_->svcnum } );
365         push @svc_acct, $svc_acct if $svc_acct;
366       }
367
368       if ( scalar(@svc_acct) == 0 ) {
369         return "Must order an account in package ". $pkgnum. " first";
370       } elsif ( scalar(@svc_acct) > 1 ) {
371         return "More than one account in package ". $pkgnum. ": specify admin contact email";
372       } else {
373         $self->email($svc_acct[0]->email );
374       }
375     }
376   }
377
378   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
379   if ( $recref->{domain} =~ /^([\w\-]{1,22})\.(com|net|org|edu)$/ ) {
380     $recref->{domain} = "$1.$2";
381   # hmmmmmmmm.
382   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)$/ ) {
383     $recref->{domain} = $1;
384   } else {
385     return "Illegal domain ". $recref->{domain}.
386            " (or unknown registry - try \$whois_hack)";
387   }
388
389   $recref->{action} =~ /^(M|N)$/ or return "Illegal action";
390   $recref->{action} = $1;
391
392   my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
393   return "Unknown catchall" unless $svc_acct || ! $recref->{catchall};
394
395   $self->ut_textn('purpose');
396
397 }
398
399 =item whois
400
401 Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
402 undef if the domain is not found in whois.
403
404 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
405
406 =cut
407
408 sub whois {
409   $whois_hack or new Net::Whois::Domain $_[0]->domain;
410 }
411
412 =item _whois
413
414 Depriciated.
415
416 =cut
417
418 sub _whois {
419   die "_whois depriciated";
420 }
421
422 =item submit_internic
423
424 Submits a registration email for this domain.
425
426 =cut
427
428 sub submit_internic {
429   my $self = shift;
430
431   my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
432   return unless $cust_pkg;
433   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $cust_pkg->custnum } );
434   return unless $cust_main;
435
436   my %subs = (
437     'action'       => $self->action,
438     'purpose'      => $self->purpose,
439     'domain'       => $self->domain,
440     'company'      => $cust_main->company 
441                         || $cust_main->getfield('first'). ' '.
442                            $cust_main->getfield('last')
443                       ,
444     'city'         => $cust_main->city,
445     'state'        => $cust_main->state,
446     'zip'          => $cust_main->zip,
447     'country'      => $cust_main->country,
448     'last'         => $cust_main->getfield('last'),
449     'first'        => $cust_main->getfield('first'),
450     'daytime'      => $cust_main->daytime,
451     'fax'          => $cust_main->fax,
452     'email'        => $self->email,
453     'tech_contact' => $tech_contact,
454     'primary'      => shift @nameservers,
455     'primary_ip'   => shift @nameserver_ips,
456   );
457
458   #yuck
459   my @xtemplate = @template;
460   my @body;
461   my $line;
462   OLOOP: while ( defined( $line = shift @xtemplate ) ) {
463
464     if ( $line =~ /^###LOOP###$/ ) {
465       my(@buffer);
466       LOADBUF: while ( defined( $line = shift @xtemplate ) ) {
467         last LOADBUF if ( $line =~ /^###ENDLOOP###$/ );
468         push @buffer, $line;
469       }
470       my %lubs = (
471         'address'      => $cust_main->address2 
472                             ? [ $cust_main->address1, $cust_main->address2 ]
473                             : [ $cust_main->address1 ]
474                           ,
475         'secondary'    => [ @nameservers ],
476         'secondary_ip' => [ @nameserver_ips ],
477       );
478       LOOP: while (1) {
479         my @xbuffer = @buffer;
480         SUBLOOP: while ( defined( $line = shift @xbuffer ) ) {
481           if ( $line =~ /###(\w+)###/ ) {
482             #last LOOP unless my($lub)=shift@{$lubs{$1}};
483             next OLOOP unless my $lub = shift @{$lubs{$1}};
484             $line =~ s/###(\w+)###/$lub/e;
485             redo SUBLOOP;
486           } else {
487             push @body, $line;
488           }
489         } #SUBLOOP
490       } #LOOP
491
492     }
493
494     if ( $line =~ /###(\w+)###/ ) {
495       #$line =~ s/###(\w+)###/$subs{$1}/eg;
496       $line =~ s/###(\w+)###/$subs{$1}/e;
497       redo OLOOP;
498     } else {
499       push @body, $line;
500     }
501
502   } #OLOOP
503
504   my $subject;
505   if ( $self->action eq "M" ) {
506     $subject = "MODIFY DOMAIN ". $self->domain;
507   } elsif ( $self->action eq "N" ) { 
508     $subject = "NEW DOMAIN ". $self->domain;
509   } else {
510     croak "submit_internic called with action ". $self->action;
511   }
512
513   $ENV{SMTPHOSTS} = $smtpmachine;
514   $ENV{MAILADDRESS} = $from;
515   my $header = Mail::Header->new( [
516     "From: $from",
517     "To: $to",
518     "Sender: $from",
519     "Reply-To: $from",
520     "Date: ". time2str("%a, %d %b %Y %X %z", time),
521     "Subject: $subject",
522   ] );
523
524   my($msg)=Mail::Internet->new(
525     'Header' => $header,
526     'Body' => \@body,
527   );
528
529   $msg->smtpsend or die "Can't send registration email"; #die? warn?
530
531 }
532
533 =back
534
535 =head1 VERSION
536
537 $Id: svc_domain.pm,v 1.21 2001-10-22 12:22:03 ivan Exp $
538
539 =head1 BUGS
540
541 All BIND/DNS fields should be included (and exported).
542
543 Delete doesn't send a registration template.
544
545 All registries should be supported.
546
547 Should change action to a real field.
548
549 The $recref stuff in sub check should be cleaned up.
550
551 =head1 SEE ALSO
552
553 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
554 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, L<ssh>,
555 L<dot-qmail>, schema.html from the base documentation, config.html from the
556 base documentation.
557
558 =cut
559
560 1;
561
562