communigate: domain aliases, enabled services, RT#7083
[freeside.git] / FS / FS / part_export / communigate_pro.pm
1 package FS::part_export::communigate_pro;
2
3 use strict;
4 use vars qw(@ISA %info %options %quotas $DEBUG);
5 use Data::Dumper;
6 use Tie::IxHash;
7 use FS::part_export;
8 use FS::queue;
9
10 @ISA = qw(FS::part_export);
11
12 $DEBUG = 1;
13
14 tie %options, 'Tie::IxHash',
15   'port'          => { label   =>'Port number', default=>'106', },
16   'login'         => { label   =>'The administrator account name.  The name can contain a domain part.', },
17   'password'      => { label   =>'The administrator account password.', },
18   'accountType'   => { label   => 'Type for newly-created accounts (default when not specified in service)',
19                        type    => 'select',
20                        options => [qw(MultiMailbox TextMailbox MailDirMailbox AGrade BGrade CGrade)],
21                        default => 'MultiMailbox',
22                      },
23   'externalFlag'  => { label   => 'Create accounts with an external (visible for legacy mailers) INBOX.',
24                        type    => 'checkbox',
25                      },
26   'AccessModes'   => { label   => 'Access modes (default when not specified in service)',
27                        default => 'Mail POP IMAP PWD WebMail WebSite',
28                      },
29   'create_domain' => { label   => 'Domain creation API call',
30                        type    => 'select',
31                        options => [qw( CreateDomain CreateSharedDomain )],
32                      }
33 ;
34
35 %info = (
36   'svc'     => [qw( svc_acct svc_domain svc_forward )],
37   'desc'    => 'Real-time export of accounts and domains to a CommuniGate Pro mail server',
38   'options' => \%options,
39   'notes'   => <<'END'
40 Real time export of accounts and domains to a
41 <a href="http://www.stalker.com/CommuniGatePro/">CommuniGate Pro</a>
42 mail server.  The
43 <a href="http://www.stalker.com/CGPerl/">CommuniGate Pro Perl Interface</a>
44 must be installed as CGP::CLI.
45 END
46 );
47
48 %quotas = (
49   'quota'        => 'MaxAccountSize',
50   'file_quota'   => 'MaxWebSize',
51   'file_maxnum'  => 'MaxWebFiles',
52   'file_maxsize' => 'MaxFileSize',
53 );
54
55 sub rebless { shift; }
56
57 sub export_username {
58   my($self, $svc_acct) = (shift, shift);
59   $svc_acct->email;
60 }
61
62 sub _export_insert {
63   my( $self, $svc_x ) = (shift, shift);
64
65   my $table = $svc_x->table;
66   my $method = "_export_insert_$table";
67   $self->$method($svc_x, @_);
68 }
69
70 sub _export_insert_svc_acct {
71   my( $self, $svc_acct ) = (shift, shift);
72
73   my %settings = (
74     'AccessModes'    => [ split(' ', ( $svc_acct->cgp_accessmodes
75                                        || $self->option('AccessModes') )
76                                )
77                         ],
78     'RealName'       => $svc_acct->finger,
79     'Password'       => $svc_acct->_password,
80     map { $quotas{$_} => $svc_acct->$_() }
81         grep $svc_acct->$_(), keys %quotas
82   );
83   #phase 2: pwdallowed, passwordrecovery, allowed mail rules,
84   # RPOP modifications, accepts mail to all, add trailer to sent mail
85   #phase 3: archive messages, mailing lists
86
87   my @options = ( 'CreateAccount',
88     'accountName'    => $self->export_username($svc_acct),
89     'accountType'    => ( $svc_acct->cgp_type
90                           || $self->option('accountType') ), 
91     'settings'       => \%settings
92   );
93
94   push @options, 'externalFlag'   => $self->option('externalFlag')
95     if $self->option('externalFlag');
96
97   #let's do the create realtime too, for much the same reasons, and to avoid
98   #pain of trying to queue w/dep the prefs & aliases
99   eval { $self->communigate_pro_runcommand( @options ) };
100   return $@ if $@;
101
102   #preferences
103   my %prefs = ();
104   $prefs{'DeleteMode'} = $svc_acct->cgp_deletemode if $svc_acct->cgp_deletemode;
105   $prefs{'EmptyTrash'} = $svc_acct->cgp_emptytrash if $svc_acct->cgp_emptytrash;
106   #phase 2: language, time zone, layout, pronto style, send read receipts
107   if ( keys %prefs ) {
108     my $pref_err = $self->communigate_pro_queue( $svc_acct->svcnum,
109       'UpdateAccountPrefs',
110       $self->export_username($svc_acct),
111       %prefs,
112     );
113    warn "WARNING: error queueing UpdateAccountPrefs job: $pref_err"
114     if $pref_err;
115   }
116
117   #aliases
118   if ( $svc_acct->cgp_aliases ) {
119     my $alias_err = $self->communigate_pro_queue( $svc_acct->svcnum,
120       'SetAccountAliases',
121       $self->export_username($svc_acct),
122       [ split(/\s*[,\s]\s*/, $svc_acct->cgp_aliases) ],
123     );
124     warn "WARNING: error queueing SetAccountAliases job: $alias_err"
125       if $alias_err;
126   }
127
128   '';
129
130 }
131
132 sub _export_insert_svc_domain {
133   my( $self, $svc_domain ) = (shift, shift);
134
135   my $create = $self->option('create_domain') || 'CreateDomain';
136
137   my %settings = (
138     'DomainAccessModes'    => [ split(' ', $svc_domain->cgp_accessmodes ) ],
139   );
140   $settings{'AccountsLimit'} = $svc_domain->max_accounts
141     if $svc_domain->max_accounts;
142
143   my @options = ( $create, $svc_domain->domain, \%settings );
144
145   eval { $self->communigate_pro_runcommand( @options ) };
146   return $@ if $@;
147
148   #aliases
149   if ( $svc_domain->cgp_aliases ) {
150     my $alias_err = $self->communigate_pro_queue( $svc_domain->svcnum,
151       'SetDomainAliases',
152       $svc_domain->domain,
153       split(/\s*[,\s]\s*/, $svc_domain->cgp_aliases),
154     );
155     warn "WARNING: error queueing SetDomainAliases job: $alias_err"
156       if $alias_err;
157   }
158
159   #account defaults
160
161   #account defaults prefs
162
163   '';
164
165 }
166
167 sub _export_insert_svc_forward {
168   my( $self, $svc_forward ) = (shift, shift);
169
170   my $src = $svc_forward->src || $svc_forward->srcsvc_acct->email;
171   my $dst = $svc_forward->dst || $svc_forward->dstsvc_acct->email;
172
173   #real-time here, presuming CGP does some dup detection?
174   eval { $self->communigate_pro_runcommand( 'CreateForwarder', $src, $dst); };
175   return $@ if $@;
176
177   '';
178 }
179
180 sub _export_replace {
181   my( $self, $new, $old ) = (shift, shift, shift);
182
183   my $table = $new->table;
184   my $method = "_export_replace_$table";
185   $self->$method($new, $old, @_);
186 }
187
188 sub _export_replace_svc_acct {
189   my( $self, $new, $old ) = (shift, shift, shift);
190
191   #let's just do the rename part realtime rather than trying to queue
192   #w/dependencies.  we don't want FS winding up out-of-sync with the wrong
193   #username and a queued job anyway.  right??
194   if ( $self->export_username($old) ne $self->export_username($new) ) {
195     eval { $self->communigate_pro_runcommand(
196       'RenameAccount',
197       $self->export_username($old),
198       $self->export_username($new),
199     ) };
200     return $@ if $@;
201   }
202
203   if ( $new->_password ne $old->_password
204        && '*SUSPENDED* '.$old->_password ne $new->_password
205   ) {
206     $self->communigate_pro_queue( $new->svcnum, 'SetAccountPassword',
207                                   $self->export_username($new), $new->_password
208                                 );
209   }
210
211   my %settings = ();
212
213   $settings{'RealName'} = $new->finger
214     if $old->finger ne $new->finger;
215   $settings{$quotas{$_}} = $new->$_()
216     foreach grep $old->$_() ne $new->$_(), keys %quotas;
217   $settings{'accountType'} = $new->cgp_type
218     if $old->cgp_type ne $new->cgp_type;
219   $settings{'AccessModes'} = $new->cgp_accessmodes
220     if $old->cgp_accessmodes ne $new->cgp_accessmodes
221     || $old->cgp_type ne $new->cgp_type;
222
223   #phase 2: pwdallowed, passwordrecovery, allowed mail rules,
224   # RPOP modifications, accepts mail to all, add trailer to sent mail
225   #phase 3: archive messages, mailing lists
226
227   if ( keys %settings ) {
228     my $error = $self->communigate_pro_queue(
229       $new->svcnum,
230       'UpdateAccountSettings',
231       $self->export_username($new),
232       %settings,
233     );
234     return $error if $error;
235   }
236
237   #preferences
238   my %prefs = ();
239   $prefs{'DeleteMode'} = $new->cgp_deletemode
240     if $old->cgp_deletemode ne $new->cgp_deletemode;
241   $prefs{'EmptyTrash'} = $new->cgp_emptytrash
242     if $old->cgp_emptytrash ne $new->cgp_emptytrash;
243   #phase 2: language, time zone, layout, pronto style, send read receipts
244   if ( keys %prefs ) {
245     my $pref_err = $self->communigate_pro_queue( $new->svcnum,
246       'UpdateAccountPrefs',
247       $self->export_username($new),
248       %prefs,
249     );
250    warn "WARNING: error queueing UpdateAccountPrefs job: $pref_err"
251     if $pref_err;
252   }
253
254   if ( $old->cgp_aliases ne $new->cgp_aliases ) {
255     my $error = $self->communigate_pro_queue(
256       $new->svcnum,
257       'SetAccountAliases',
258       $self->export_username($new),
259       [ split(/\s*[,\s]\s*/, $new->cgp_aliases) ],
260     );
261     return $error if $error;
262   }
263
264   '';
265
266 }
267
268 sub _export_replace_svc_domain {
269   my( $self, $new, $old ) = (shift, shift, shift);
270
271   if ( $old->domain ne $new->domain ) {
272     my $error = $self->communigate_pro_queue( $new->svcnum, 'RenameDomain',
273       $old->domain, $new->domain,
274     );
275     return $error if $error;
276   }
277   my %settings = ();
278   $settings{'AccountsLimit'} = $new->max_accounts
279     if $old->max_accounts ne $new->max_accounts;
280   $settings{'DomainAccessModes'} = $new->cgp_accessmodes
281     if $old->cgp_accessmodes ne $new->cgp_accessmodes;
282
283   if ( keys %settings ) {
284     my $error = $self->communigate_pro_queue( $new->svcnum,
285       'UpdateDomainSettings',
286       $new->domain,
287       %settings,
288     );
289     return $error if $error;
290   }
291
292   if ( $old->cgp_aliases ne $new->cgp_aliases ) {
293     my $error = $self->communigate_pro_queue( $new->svcnum,
294       'SetDomainAliases',
295       $new->domain,
296       split(/\s*[,\s]\s*/, $new->cgp_aliases),
297     );
298     return $error if $error;
299   }
300
301   #other kinds of changes?
302
303   '';
304 }
305
306 sub _export_replace_svc_forward {
307   my( $self, $new, $old ) = (shift, shift, shift);
308
309   my $osrc = $old->src || $old->srcsvc_acct->email;
310   my $nsrc = $new->src || $new->srcsvc_acct->email;
311   my $odst = $old->dst || $old->dstsvc_acct->email;
312   my $ndst = $new->dst || $new->dstsvc_acct->email;
313
314   if ( $odst ne $ndst ) {
315
316     #no change command, so delete and create (real-time)
317     eval { $self->communigate_pro_runcommand('DeleteForwarder', $osrc) };
318     return $@ if $@;
319     eval { $self->communigate_pro_runcommand('CreateForwarder', $nsrc, $ndst)};
320     return $@ if $@;
321
322   } elsif ( $osrc ne $nsrc ) {
323
324     #real-time here, presuming CGP does some dup detection?
325     eval { $self->communigate_pro_runcommand( 'RenameForwarder', $osrc, $nsrc)};
326     return $@ if $@;
327
328   } else {
329     warn "communigate replace called for svc_forward with no changes\n";#confess
330   }
331
332   '';
333 }
334
335 sub _export_delete {
336   my( $self, $svc_x ) = (shift, shift);
337
338   my $table = $svc_x->table;
339   my $method = "_export_delete_$table";
340   $self->$method($svc_x, @_);
341 }
342
343 sub _export_delete_svc_acct {
344   my( $self, $svc_acct ) = (shift, shift);
345
346   $self->communigate_pro_queue( $svc_acct->svcnum, 'DeleteAccount',
347     $self->export_username($svc_acct),
348   );
349 }
350
351 sub _export_delete_svc_domain {
352   my( $self, $svc_domain ) = (shift, shift);
353
354   $self->communigate_pro_queue( $svc_domain->svcnum, 'DeleteDomain',
355     $svc_domain->domain,
356     #XXX turn on force option for domain deletion?
357   );
358 }
359
360 sub _export_delete_svc_forward {
361   my( $self, $svc_forward ) = (shift, shift);
362
363   $self->communigate_pro_queue( $svc_forward->svcnum, 'DeleteForwarder',
364     ($svc_forward->src || $svc_forward->srcsvc_acct->email),
365   );
366 }
367
368 sub _export_suspend {
369   my( $self, $svc_x ) = (shift, shift);
370
371   my $table = $svc_x->table;
372   my $method = "_export_suspend_$table";
373   $self->$method($svc_x, @_);
374
375 }
376
377 sub _export_suspend_svc_acct {
378   my( $self, $svc_acct ) = (shift, shift);
379
380   #XXX is this the desired suspnsion action?
381
382    $self->communigate_pro_queue(
383     $svc_acct->svcnum,
384     'UpdateAccountSettings',
385     $self->export_username($svc_acct),
386     'AccessModes' => 'Mail',
387   );
388
389 }
390
391 sub _export_suspend_svc_domain {
392   my( $self, $svc_domain) = (shift, shift);
393
394   #XXX domain operations
395   '';
396
397 }
398
399 sub _export_unsuspend {
400   my( $self, $svc_x ) = (shift, shift);
401
402   my $table = $svc_x->table;
403   my $method = "_export_unsuspend_$table";
404   $self->$method($svc_x, @_);
405
406 }
407
408 sub _export_unsuspend_svc_acct {
409   my( $self, $svc_acct ) = (shift, shift);
410
411   $self->communigate_pro_queue(
412     $svc_acct->svcnum,
413     'UpdateAccountSettings',
414     $self->export_username($svc_acct),
415     'AccessModes' => ( $svc_acct->cgp_accessmodes
416                          || $self->option('AccessModes') ),
417   );
418
419 }
420
421 sub _export_unsuspend_svc_domain {
422   my( $self, $svc_domain) = (shift, shift);
423
424   #XXX domain operations
425   '';
426
427 }
428
429
430 sub export_getsettings {
431   my($self, $svc_x) = (shift, shift);
432
433   my $table = $svc_x->table;
434   my $method = "export_getsettings_$table";
435
436   $self->can($method) ? $self->$method($svc_x, @_) : '';
437
438 }
439
440 sub export_getsettings_svc_domain {
441   my($self, $svc_domain, $settingsref, $defaultref ) = @_;
442
443   my $settings = eval { $self->communigate_pro_runcommand(
444     'GetDomainSettings',
445     $svc_domain->domain
446   ) };
447   return $@ if $@;
448
449   my $effective_settings = eval { $self->communigate_pro_runcommand(
450     'GetDomainEffectiveSettings',
451     $svc_domain->domain
452   ) };
453   return $@ if $@;
454
455   my $acct_defaults = eval { $self->communigate_pro_runcommand(
456     'GetAccountDefaults',
457     $svc_domain->domain
458   ) };
459   return $@ if $@;
460
461   #warn Dumper($acct_defaults);
462
463   %$effective_settings = ( %$effective_settings,
464                            map { ("Acct. Default $_" => $acct_defaults->{$_}); }
465                                keys(%$acct_defaults)
466                          );
467
468   #aliases too
469   my $aliases = eval { $self->communigate_pro_runcommand(
470     'GetDomainAliases',
471     $svc_domain->domain
472   ) };
473   return $@ if $@;
474
475   $effective_settings->{'Aliases'} = join(', ', @$aliases);
476   $settings->{'Aliases'}           = join(', ', @$aliases);
477
478
479   #false laziness w/below
480   
481   my %defaults = map { $_ => 1 }
482                    grep !exists(${$settings}{$_}), keys %$effective_settings;
483
484   foreach my $key ( grep ref($effective_settings->{$_}),
485                     keys %$effective_settings )
486   {
487     my $value = $effective_settings->{$key};
488     if ( ref($value) eq 'ARRAY' ) {
489       $effective_settings->{$key} = join(' ', @$value);
490     } else {
491       #XXX
492       warn "serializing ". ref($value). " for table display not yet handled";
493     }
494   }
495
496   %{$settingsref} = %$effective_settings;
497   %{$defaultref} = %defaults;
498
499   '';
500 }
501
502 sub export_getsettings_svc_acct {
503   my($self, $svc_acct, $settingsref, $defaultref ) = @_;
504
505   my $settings = eval { $self->communigate_pro_runcommand(
506     'GetAccountSettings',
507     $svc_acct->email
508   ) };
509   return $@ if $@;
510
511   delete($settings->{'Password'});
512
513   my $effective_settings = eval { $self->communigate_pro_runcommand(
514     'GetAccountEffectiveSettings',
515     $svc_acct->email
516   ) };
517   return $@ if $@;
518
519   delete($effective_settings->{'Password'});
520
521   #prefs/effectiveprefs too
522
523   my $prefs = eval { $self->communigate_pro_runcommand(
524     'GetAccountPrefs',
525     $svc_acct->email
526   ) };
527   return $@ if $@;
528
529   my $effective_prefs = eval { $self->communigate_pro_runcommand(
530     'GetAccountEffectivePrefs',
531     $svc_acct->email
532   ) };
533   return $@ if $@;
534
535   %$effective_settings = ( %$effective_settings,
536                            map { ("Pref $_" => $effective_prefs->{$_}); }
537                                keys(%$effective_prefs)
538                          );
539   %$settings = ( %$settings,
540                  map { ("Pref $_" => $prefs->{$_}); }
541                      keys(%$prefs)
542                );
543
544   #aliases too
545
546   my $aliases = eval { $self->communigate_pro_runcommand(
547     'GetAccountAliases',
548     $svc_acct->email
549   ) };
550   return $@ if $@;
551
552   $effective_settings->{'Aliases'} = join(', ', @$aliases);
553   $settings->{'Aliases'}           = join(', ', @$aliases);
554
555   #false laziness w/above
556
557   my %defaults = map { $_ => 1 }
558                    grep !exists(${$settings}{$_}), keys %$effective_settings;
559
560   foreach my $key ( grep ref($effective_settings->{$_}),
561                     keys %$effective_settings )
562   {
563     my $value = $effective_settings->{$key};
564     if ( ref($value) eq 'ARRAY' ) {
565       $effective_settings->{$key} = join(' ', @$value);
566     } else {
567       #XXX
568       warn "serializing ". ref($value). " for table display not yet handled";
569     }
570   }
571
572   %{$settingsref} = %$effective_settings;
573   %{$defaultref} = %defaults;
574
575   '';
576
577 }
578
579 sub communigate_pro_queue {
580   my( $self, $svcnum, $method ) = (shift, shift, shift);
581   my $jobnum = ''; #don't actually care
582   $self->communigate_pro_queue_dep( \$jobnum, $svcnum, $method, @_);
583 }
584
585 sub communigate_pro_queue_dep {
586   my( $self, $jobnumref, $svcnum, $method ) = splice(@_,0,4);
587
588   my %kludge_methods = (
589     #'CreateAccount'         => 'CreateAccount',
590     'UpdateAccountSettings' => 'UpdateAccountSettings',
591     'UpdateAccountPrefs'    => 'cp_Scalar_Hash',
592     #'CreateDomain'          => 'cp_Scalar_Hash',
593     #'CreateSharedDomain'    => 'cp_Scalar_Hash',
594     'UpdateDomainSettings'  => 'UpdateDomainSettings',
595     'SetDomainAliases'      => 'cp_Scalar_Array',
596   );
597   my $sub = exists($kludge_methods{$method})
598               ? $kludge_methods{$method}
599               : 'communigate_pro_command';
600
601   my $queue = new FS::queue {
602     'svcnum' => $svcnum,
603     'job'    => "FS::part_export::communigate_pro::$sub",
604   };
605   my $error = $queue->insert(
606     $self->machine,
607     $self->option('port'),
608     $self->option('login'),
609     $self->option('password'),
610     $method,
611     @_,
612   );
613   $$jobnumref = $queue->jobnum unless $error;
614
615   return $error;
616 }
617
618 sub communigate_pro_runcommand {
619   my( $self, $method ) = (shift, shift);
620
621   communigate_pro_command(
622     $self->machine,
623     $self->option('port'),
624     $self->option('login'),
625     $self->option('password'),
626     $method,
627     @_,
628   );
629
630 }
631
632 #XXX one sub per arg prototype is lame.  more magic?  i suppose queue needs
633 # to store data strctures properly instead of just an arg list.  right.
634
635 sub cp_Scalar_Hash {
636   my( $machine, $port, $login, $password, $method, $scalar, %hash ) = @_;
637   my @args = ( $scalar, \%hash );
638   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
639 }
640
641 sub cp_Scalar_Array {
642   my( $machine, $port, $login, $password, $method, $scalar, @array ) = @_;
643   my @args = ( $scalar, \@array );
644   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
645 }
646
647 #sub cp_Hash {
648 #  my( $machine, $port, $login, $password, $method, %hash ) = @_;
649 #  my @args = ( \%hash );
650 #  communigate_pro_command( $machine, $port, $login, $password, $method, @args );
651 #}
652
653 sub UpdateDomainSettings {
654   my( $machine, $port, $login, $password, $method, $domain, %settings ) = @_;
655   $settings{'DomainAccessModes'} = [split(' ',$settings{'DomainAccessModes'})];
656   my @args = ( 'domain' => $domain, 'settings' => \%settings );
657   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
658 }
659
660 #sub CreateAccount {
661 #  my( $machine, $port, $login, $password, $method, %args ) = @_;
662 #  my $accountName  = delete $args{'accountName'};
663 #  my $accountType  = delete $args{'accountType'};
664 #  my $externalFlag = delete $args{'externalFlag'};
665 #  $args{'AccessModes'} = [ split(' ', $args{'AccessModes'}) ];
666 #  my @args = ( accountName  => $accountName,
667 #               accountType  => $accountType,
668 #               settings     => \%args,
669 #             );
670 #               #externalFlag => $externalFlag,
671 #  push @args, externalFlag => $externalFlag if $externalFlag;
672 #
673 #  communigate_pro_command( $machine, $port, $login, $password, $method, @args );
674 #
675 #}
676
677 sub UpdateAccountSettings {
678   my( $machine, $port, $login, $password, $method, $accountName, %args ) = @_;
679   $args{'AccessModes'} = [ split(' ', $args{'AccessModes'}) ];
680   my @args = ( $accountName, \%args );
681   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
682 }
683
684 sub communigate_pro_command { #subroutine, not method
685   my( $machine, $port, $login, $password, $method, @args ) = @_;
686
687   eval "use CGP::CLI";
688
689   my $cli = new CGP::CLI( {
690     'PeerAddr' => $machine,
691     'PeerPort' => $port,
692     'login'    => $login,
693     'password' => $password,
694   } ) or die "Can't login to CGPro: $CGP::ERR_STRING\n";
695
696   #warn "$method ". Dumper(@args) if $DEBUG;
697
698   my $return = $cli->$method(@args)
699     or die "Communigate Pro error: ". $cli->getErrMessage. "\n";
700
701   $cli->Logout; # or die "Can't logout of CGPro: $CGP::ERR_STRING\n";
702
703   $return;
704
705 }
706
707 1;
708