communigate phase 3: RPOP/acct_snarf, RT#7515
[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 svc_mailinglist )],
37   'desc'    => 'Real-time export of accounts, domains, mail forwards and mailing lists to a CommuniGate Pro mail server',
38   'options' => \%options,
39   'notes'   => <<'END'
40 Real time export of accounts, domains, mail forwards and mailing lists 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
81     'PasswordRecovery' => ($svc_acct->password_recover ? 'YES':'NO'),
82
83     'RulesAllowed'     => $svc_acct->cgp_rulesallowed,
84     'RPOPAllowed'      =>($svc_acct->cgp_rpopallowed    ?'YES':'NO'),
85     'MailToAll'        =>($svc_acct->cgp_mailtoall      ?'YES':'NO'),
86     'AddMailTrailer'   =>($svc_acct->cgp_addmailtrailer ?'YES':'NO'),
87
88     'ArchiveMessagesAfter' => $svc_acct->cgp_archiveafter,
89
90     map { $quotas{$_} => $svc_acct->$_() }
91         grep $svc_acct->$_(), keys %quotas
92   );
93   #XXX phase 3: mailing lists
94
95   my @options = ( 'CreateAccount',
96     'accountName'    => $self->export_username($svc_acct),
97     'accountType'    => ( $svc_acct->cgp_type
98                           || $self->option('accountType') ), 
99     'settings'       => \%settings
100   );
101
102   push @options, 'externalFlag'   => $self->option('externalFlag')
103     if $self->option('externalFlag');
104
105   #let's do the create realtime too, for much the same reasons, and to avoid
106   #pain of trying to queue w/dep the prefs & aliases
107   eval { $self->communigate_pro_runcommand( @options ) };
108   return $@ if $@;
109
110   #preferences
111   my %prefs = ();
112   $prefs{'DeleteMode'} = $svc_acct->cgp_deletemode if $svc_acct->cgp_deletemode;
113   $prefs{'EmptyTrash'} = $svc_acct->cgp_emptytrash if $svc_acct->cgp_emptytrash;
114   $prefs{'Language'} = $svc_acct->cgp_language if $svc_acct->cgp_language;
115   $prefs{'TimeZone'} = $svc_acct->cgp_timezone if $svc_acct->cgp_timezone;
116   $prefs{'SkinName'} = $svc_acct->cgp_skinname if $svc_acct->cgp_skinname;
117   $prefs{'ProntoSkinName'} = $svc_acct->cgp_prontoskinname if $svc_acct->cgp_prontoskinname;
118   $prefs{'SendMDNMode'} = $svc_acct->cgp_sendmdnmode if $svc_acct->cgp_sendmdnmode;
119   if ( keys %prefs ) {
120     my $pref_err = $self->communigate_pro_queue( $svc_acct->svcnum,
121       'UpdateAccountPrefs',
122       $self->export_username($svc_acct),
123       %prefs,
124     );
125    warn "WARNING: error queueing UpdateAccountPrefs job: $pref_err"
126     if $pref_err;
127   }
128
129   #aliases
130   if ( $svc_acct->cgp_aliases ) {
131     my $alias_err = $self->communigate_pro_queue( $svc_acct->svcnum,
132       'SetAccountAliases',
133       $self->export_username($svc_acct),
134       [ split(/\s*[,\s]\s*/, $svc_acct->cgp_aliases) ],
135     );
136     warn "WARNING: error queueing SetAccountAliases job: $alias_err"
137       if $alias_err;
138   }
139
140   my $rule_error = $self->communigate_pro_queue(
141     $svc_acct->svcnum,
142     'SetAccountMailRules',
143     $self->export_username($svc_acct),
144     $svc_acct->cgp_rule_arrayref,
145   );
146   warn "WARNING: error queueing SetAccountMailRules job: $rule_error"
147     if $rule_error;
148
149   my $rpop_error = $self->communigate_pro_queue(
150     $svc_acct->svcnum,
151     'SetAccountRPOPs',
152     $self->export_username($svc_acct),
153     $svc_acct->cgp_rpop_hashref,
154   );
155   warn "WARNING: error queueing SetAccountMailRPOPs job: $rpop_error"
156     if $rpop_error;
157
158   '';
159
160 }
161
162 sub _export_insert_svc_domain {
163   my( $self, $svc_domain ) = (shift, shift);
164
165   my $create = $self->option('create_domain') || 'CreateDomain';
166
167   my %settings = (
168     'DomainAccessModes'    => [ split(' ', $svc_domain->cgp_accessmodes ) ],
169   );
170   $settings{'AccountsLimit'} = $svc_domain->max_accounts
171     if $svc_domain->max_accounts;
172   $settings{'AdminDomainName'} = $svc_domain->parent_svc_x->domain
173     if $svc_domain->parent_svcnum;
174   $settings{'TrailerText'} = $svc_domain->trailer
175     if $svc_domain->trailer;
176
177   my @options = ( $create, $svc_domain->domain, \%settings );
178
179   eval { $self->communigate_pro_runcommand( @options ) };
180   return $@ if $@;
181
182   #aliases
183   if ( $svc_domain->cgp_aliases ) {
184     my $alias_err = $self->communigate_pro_queue( $svc_domain->svcnum,
185       'SetDomainAliases',
186       $svc_domain->domain,
187       split(/\s*[,\s]\s*/, $svc_domain->cgp_aliases),
188     );
189     warn "WARNING: error queueing SetDomainAliases job: $alias_err"
190       if $alias_err;
191   }
192
193   #account defaults
194   my $def_err = $self->communigate_pro_queue( $svc_domain->svcnum,
195     'SetAccountDefaults',
196     $svc_domain->domain,
197     'PWDAllowed'     =>($svc_domain->acct_def_password_selfchange ? 'YES':'NO'),
198     'PasswordRecovery' => ($svc_domain->acct_def_password_recover ? 'YES':'NO'),
199     'AccessModes'      => $svc_domain->acct_def_cgp_accessmodes,
200     'MaxAccountSize'   => $svc_domain->acct_def_quota,
201     'MaxWebSize'       => $svc_domain->acct_def_file_quota,
202     'MaxWebFile'       => $svc_domain->acct_def_file_maxnum,
203     'MaxFileSize'      => $svc_domain->acct_def_file_maxsize,
204     'RulesAllowed'     => $svc_domain->acct_def_cgp_rulesallowed,
205     'RPOPAllowed'      =>($svc_domain->acct_def_cgp_rpopallowed    ?'YES':'NO'),
206     'MailToAll'        =>($svc_domain->acct_def_cgp_mailtoall      ?'YES':'NO'),
207     'AddMailTrailer'   =>($svc_domain->acct_def_cgp_addmailtrailer ?'YES':'NO'),
208     'ArchiveMessagesAfter' => $svc_domain->acct_def_cgp_archiveafter,
209   );
210   warn "WARNING: error queueing SetAccountDefaults job: $def_err"
211     if $def_err;
212
213   #account defaults prefs
214   my $pref_err = $self->communigate_pro_queue( $svc_domain->svcnum,
215     'SetAccountDefaultPrefs',
216     $svc_domain->domain,
217     'DeleteMode'     => $svc_domain->acct_def_cgp_deletemode,
218     'EmptyTrash'     => $svc_domain->acct_def_cgp_emptytrash,
219     'Language'       => $svc_domain->acct_def_cgp_language,
220     'TimeZone'       => $svc_domain->acct_def_cgp_timezone,
221     'SkinName'       => $svc_domain->acct_def_cgp_skinname,
222     'ProntoSkinName' => $svc_domain->acct_def_cgp_prontoskinname,
223     'SendMDNMode'    => $svc_domain->acct_def_cgp_sendmdnmode,
224   );
225   warn "WARNING: error queueing SetAccountDefaultPrefs job: $pref_err"
226     if $pref_err;
227
228   my $rule_error = $self->communigate_pro_queue(
229     $svc_domain->svcnum,
230     'SetDomainMailRules',
231     $svc_domain->domain,
232     $svc_domain->cgp_rule_arrayref,
233   );
234   warn "WARNING: error queueing SetDomainMailRules job: $rule_error"
235     if $rule_error;
236
237   '';
238
239 }
240
241 sub _export_insert_svc_forward {
242   my( $self, $svc_forward ) = (shift, shift);
243
244   my $src = $svc_forward->src || $svc_forward->srcsvc_acct->email;
245   my $dst = $svc_forward->dst || $svc_forward->dstsvc_acct->email;
246
247   #real-time here, presuming CGP does some dup detection?
248   eval { $self->communigate_pro_runcommand( 'CreateForwarder', $src, $dst); };
249   return $@ if $@;
250
251   '';
252 }
253
254 sub _export_insert_svc_mailinglist {
255   my( $self, $svc_mlist ) = (shift, shift);
256
257   my @members = map $_->email_address,
258                     $svc_mlist->mailinglist->mailinglistmember;
259
260   #real-time here, presuming CGP does some dup detection
261   eval { $self->communigate_pro_runcommand(
262            'CreateGroup',
263            $svc_mlist->username.'@'.$svc_mlist->domain,
264            { 'RealName'      => $svc_mlist->listname,
265              'SetReplyTo'    => ( $svc_mlist->reply_to         ? 'YES' : 'NO' ),
266              'RemoveAuthor'  => ( $svc_mlist->remove_from      ? 'YES' : 'NO' ),
267              'RejectAuto'    => ( $svc_mlist->reject_auto      ? 'YES' : 'NO' ),
268              'RemoveToAndCc' => ( $svc_mlist->remove_to_and_cc ? 'YES' : 'NO' ),
269              'Members'       => \@members,
270            }
271          );
272        };
273   return $@ if $@;
274
275   '';
276
277 }
278
279 sub _export_replace {
280   my( $self, $new, $old ) = (shift, shift, shift);
281
282   my $table = $new->table;
283   my $method = "_export_replace_$table";
284   $self->$method($new, $old, @_);
285 }
286
287 sub _export_replace_svc_acct {
288   my( $self, $new, $old ) = (shift, shift, shift);
289
290   #let's just do the rename part realtime rather than trying to queue
291   #w/dependencies.  we don't want FS winding up out-of-sync with the wrong
292   #username and a queued job anyway.  right??
293   if ( $self->export_username($old) ne $self->export_username($new) ) {
294     eval { $self->communigate_pro_runcommand(
295       'RenameAccount',
296       $self->export_username($old),
297       $self->export_username($new),
298     ) };
299     return $@ if $@;
300   }
301
302   if ( $new->_password ne $old->_password
303        && '*SUSPENDED* '.$old->_password ne $new->_password
304   ) {
305     $self->communigate_pro_queue( $new->svcnum, 'SetAccountPassword',
306                                   $self->export_username($new), $new->_password
307                                 );
308   }
309
310   my %settings = ();
311
312   $settings{'RealName'} = $new->finger
313     if $old->finger ne $new->finger;
314   $settings{$quotas{$_}} = $new->$_()
315     foreach grep $old->$_() ne $new->$_(), keys %quotas;
316   $settings{'accountType'} = $new->cgp_type
317     if $old->cgp_type ne $new->cgp_type;
318   $settings{'AccessModes'} = $new->cgp_accessmodes
319     if $old->cgp_accessmodes ne $new->cgp_accessmodes
320     || $old->cgp_type ne $new->cgp_type;
321
322   $settings{'PasswordRecovery'} = ( $new->password_recover ? 'YES':'NO' )
323     if $old->password_recover ne $new->password_recover;
324
325   $settings{'RulesAllowed'} = $new->cgp_rulesallowed
326     if $old->cgp_rulesallowed ne $new->cgp_rulesallowed;
327   $settings{'RPOPAllowed'} = ( $new->cgp_rpopallowed ? 'YES':'NO' )
328     if $old->cgp_rpopallowed ne $new->cgp_rpopallowed;
329   $settings{'MailToAll'} = ( $new->cgp_mailtoall ? 'YES':'NO' )
330     if $old->cgp_mailtoall ne $new->cgp_mailtoall;
331   $settings{'AddMailTrailer'} = ( $new->cgp_addmailtrailer ? 'YES':'NO' )
332     if $old->cgp_addmailtrailer ne $new->cgp_addmailtrailer;
333   $settings{'ArchiveMessagesAfter'} = $new->cgp_archiveafter
334     if $old->cgp_archiveafter ne $new->cgp_archiveafter;
335
336   #XXX phase 3: mailing lists
337
338   if ( keys %settings ) {
339     my $error = $self->communigate_pro_queue(
340       $new->svcnum,
341       'UpdateAccountSettings',
342       $self->export_username($new),
343       %settings,
344     );
345     return $error if $error;
346   }
347
348   #preferences
349   my %prefs = ();
350   $prefs{'DeleteMode'} = $new->cgp_deletemode
351     if $old->cgp_deletemode ne $new->cgp_deletemode;
352   $prefs{'EmptyTrash'} = $new->cgp_emptytrash
353     if $old->cgp_emptytrash ne $new->cgp_emptytrash;
354   $prefs{'Language'} = $new->cgp_language
355     if $old->cgp_language ne $new->cgp_language;
356   $prefs{'TimeZone'} = $new->cgp_timezone
357     if $old->cgp_timezone ne $new->cgp_timezone;
358   $prefs{'SkinName'} = $new->cgp_skinname
359     if $old->cgp_skinname ne $new->cgp_skinname;
360   $prefs{'ProntoSkinName'} = $new->cgp_prontoskinname
361     if $old->cgp_prontoskinname ne $new->cgp_prontoskinname;
362   $prefs{'SendMDNMode'} = $new->cgp_sendmdnmode
363     if $old->cgp_sendmdnmode ne $new->cgp_sendmdnmode;
364   if ( keys %prefs ) {
365     my $pref_err = $self->communigate_pro_queue( $new->svcnum,
366       'UpdateAccountPrefs',
367       $self->export_username($new),
368       %prefs,
369     );
370    warn "WARNING: error queueing UpdateAccountPrefs job: $pref_err"
371     if $pref_err;
372   }
373
374   if ( $old->cgp_aliases ne $new->cgp_aliases ) {
375     my $error = $self->communigate_pro_queue(
376       $new->svcnum,
377       'SetAccountAliases',
378       $self->export_username($new),
379       [ split(/\s*[,\s]\s*/, $new->cgp_aliases) ],
380     );
381     return $error if $error;
382   }
383
384   my $rule_error = $self->communigate_pro_queue(
385     $new->svcnum,
386     'SetAccountMailRules',
387     $self->export_username($new),
388     $new->cgp_rule_arrayref,
389   );
390   warn "WARNING: error queueing SetAccountMailRules job: $rule_error"
391     if $rule_error;
392
393   my $rpop_error = $self->communigate_pro_queue(
394     $new->svcnum,
395     'SetAccountRPOPs',
396     $self->export_username($new),
397     $new->cgp_rpop_hashref,
398   );
399   warn "WARNING: error queueing SetAccountMailRPOPs job: $rpop_error"
400     if $rpop_error;
401
402   '';
403
404 }
405
406 sub _export_replace_svc_domain {
407   my( $self, $new, $old ) = (shift, shift, shift);
408
409   #let's just do the rename part realtime rather than trying to queue
410   #w/dependencies.  we don't want FS winding up out-of-sync with the wrong
411   #username and a queued job anyway.  right??
412   if ( $old->domain ne $new->domain ) {
413     eval { $self->communigate_pro_runcommand(
414              'RenameDomain', $old->domain, $new->domain,
415          ) };
416     return $@ if $@;
417   }
418
419   my %settings = ();
420   $settings{'AccountsLimit'} = $new->max_accounts
421     if $old->max_accounts ne $new->max_accounts;
422   $settings{'TrailerText'} = $new->trailer
423     if $old->trailer ne $new->trailer;
424   $settings{'DomainAccessModes'} = $new->cgp_accessmodes
425     if $old->cgp_accessmodes ne $new->cgp_accessmodes;
426   $settings{'AdminDomainName'} =
427     $new->parent_svcnum ? $new->parent_svc_x->domain : ''
428       if $old->parent_svcnum != $new->parent_svcnum;
429
430   if ( keys %settings ) {
431     my $error = $self->communigate_pro_queue( $new->svcnum,
432       'UpdateDomainSettings',
433       $new->domain,
434       %settings,
435     );
436     return $error if $error;
437   }
438
439   if ( $old->cgp_aliases ne $new->cgp_aliases ) {
440     my $error = $self->communigate_pro_queue( $new->svcnum,
441       'SetDomainAliases',
442       $new->domain,
443       split(/\s*[,\s]\s*/, $new->cgp_aliases),
444     );
445     return $error if $error;
446   }
447
448   #below this identical to insert... any value to doing an Update here?
449   #not seeing any big one... i guess it would be nice to avoid the update
450   #when things haven't changed
451
452   #account defaults
453   my $def_err = $self->communigate_pro_queue( $new->svcnum,
454     'SetAccountDefaults',
455     $new->domain,
456     'PWDAllowed'       => ( $new->acct_def_password_selfchange ? 'YES' : 'NO' ),
457     'PasswordRecovery' => ( $new->acct_def_password_recover    ? 'YES' : 'NO' ),
458     'AccessModes'      => $new->acct_def_cgp_accessmodes,
459     'MaxAccountSize'   => $new->acct_def_quota,
460     'MaxWebSize'       => $new->acct_def_file_quota,
461     'MaxWebFile'       => $new->acct_def_file_maxnum,
462     'MaxFileSize'      => $new->acct_def_file_maxsize,
463     'RulesAllowed'     => $new->acct_def_cgp_rulesallowed,
464     'RPOPAllowed'      => ( $new->acct_def_cgp_rpopallowed    ? 'YES' : 'NO' ),
465     'MailToAll'        => ( $new->acct_def_cgp_mailtoall      ? 'YES' : 'NO' ),
466     'AddMailTrailer'   => ( $new->acct_def_cgp_addmailtrailer ? 'YES' : 'NO' ),
467     'ArchiveMessagesAfter' => $new->acct_def_cgp_archiveafter,
468   );
469   warn "WARNING: error queueing SetAccountDefaults job: $def_err"
470     if $def_err;
471
472   #account defaults prefs
473   my $pref_err = $self->communigate_pro_queue( $new->svcnum,
474     'SetAccountDefaultPrefs',
475     $new->domain,
476     'DeleteMode'     => $new->acct_def_cgp_deletemode,
477     'EmptyTrash'     => $new->acct_def_cgp_emptytrash,
478     'Language'       => $new->acct_def_cgp_language,
479     'TimeZone'       => $new->acct_def_cgp_timezone,
480     'SkinName'       => $new->acct_def_cgp_skinname,
481     'ProntoSkinName' => $new->acct_def_cgp_prontoskinname,
482     'SendMDNMode'    => $new->acct_def_cgp_sendmdnmode,
483   );
484   warn "WARNING: error queueing SetAccountDefaultPrefs job: $pref_err"
485     if $pref_err;
486
487   my $rule_error = $self->communigate_pro_queue(
488     $new->svcnum,
489     'SetDomainMailRules',
490     $new->domain,
491     $new->cgp_rule_arrayref,
492   );
493   warn "WARNING: error queueing SetDomainMailRules job: $rule_error"
494     if $rule_error;
495
496   '';
497 }
498
499 sub _export_replace_svc_forward {
500   my( $self, $new, $old ) = (shift, shift, shift);
501
502   my $osrc = $old->src || $old->srcsvc_acct->email;
503   my $nsrc = $new->src || $new->srcsvc_acct->email;
504   my $odst = $old->dst || $old->dstsvc_acct->email;
505   my $ndst = $new->dst || $new->dstsvc_acct->email;
506
507   if ( $odst ne $ndst ) {
508
509     #no change command, so delete and create (real-time)
510     eval { $self->communigate_pro_runcommand('DeleteForwarder', $osrc) };
511     return $@ if $@;
512     eval { $self->communigate_pro_runcommand('CreateForwarder', $nsrc, $ndst)};
513     return $@ if $@;
514
515   } elsif ( $osrc ne $nsrc ) {
516
517     #real-time here, presuming CGP does some dup detection?
518     eval { $self->communigate_pro_runcommand( 'RenameForwarder', $osrc, $nsrc)};
519     return $@ if $@;
520
521   } else {
522     warn "communigate replace called for svc_forward with no changes\n";#confess
523   }
524
525   '';
526 }
527
528 sub _export_replace_svc_mailinglist {
529   my( $self, $new, $old ) = (shift, shift, shift);
530
531   my $oldGroupName = $old->username.'@'.$old->domain;
532   my $newGroupName = $new->username.'@'.$new->domain;
533
534   if ( $oldGroupName ne $newGroupName ) {
535     eval { $self->communigate_pro_runcommand(
536              'RenameGroup', $oldGroupName, $newGroupName ); };
537     return $@ if $@;
538   }
539
540   my @members = map $_->email_address,
541                 $new->mailinglist->mailinglistmember;
542
543   #real-time here, presuming CGP does some dup detection
544   eval { $self->communigate_pro_runcommand(
545            'SetGroup', $newGroupName,
546            { 'RealName'      => $new->listname,
547              'SetReplyTo'    => ( $new->reply_to         ? 'YES' : 'NO' ),
548              'RemoveAuthor'  => ( $new->remove_from      ? 'YES' : 'NO' ),
549              'RejectAuto'    => ( $new->reject_auto      ? 'YES' : 'NO' ),
550              'RemoveToAndCc' => ( $new->remove_to_and_cc ? 'YES' : 'NO' ),
551              'Members'       => \@members,
552            }
553          );
554        };
555   return $@ if $@;
556
557   '';
558
559 }
560
561 sub _export_delete {
562   my( $self, $svc_x ) = (shift, shift);
563
564   my $table = $svc_x->table;
565   my $method = "_export_delete_$table";
566   $self->$method($svc_x, @_);
567 }
568
569 sub _export_delete_svc_acct {
570   my( $self, $svc_acct ) = (shift, shift);
571
572   $self->communigate_pro_queue( $svc_acct->svcnum, 'DeleteAccount',
573     $self->export_username($svc_acct),
574   );
575 }
576
577 sub _export_delete_svc_domain {
578   my( $self, $svc_domain ) = (shift, shift);
579
580   $self->communigate_pro_queue( $svc_domain->svcnum, 'DeleteDomain',
581     $svc_domain->domain,
582     #XXX turn on force option for domain deletion?
583   );
584 }
585
586 sub _export_delete_svc_forward {
587   my( $self, $svc_forward ) = (shift, shift);
588
589   $self->communigate_pro_queue( $svc_forward->svcnum, 'DeleteForwarder',
590     ($svc_forward->src || $svc_forward->srcsvc_acct->email),
591   );
592 }
593
594 sub _export_delete_svc_mailinglist {
595   my( $self, $svc_mailinglist ) = (shift, shift);
596
597   #real-time here, presuming CGP does some dup detection
598   eval { $self->communigate_pro_runcommand(
599            'DeleteGroup',
600            $svc_mailinglist->username.'@'.$svc_mailinglist->domain,
601          );
602        };
603   return $@ if $@;
604
605   '';
606
607 }
608
609 sub _export_suspend {
610   my( $self, $svc_x ) = (shift, shift);
611
612   my $table = $svc_x->table;
613   my $method = "_export_suspend_$table";
614   $self->$method($svc_x, @_);
615
616 }
617
618 sub _export_suspend_svc_acct {
619   my( $self, $svc_acct ) = (shift, shift);
620
621   #XXX is this the desired suspnsion action?
622
623    $self->communigate_pro_queue(
624     $svc_acct->svcnum,
625     'UpdateAccountSettings',
626     $self->export_username($svc_acct),
627     'AccessModes' => 'Mail',
628   );
629
630 }
631
632 sub _export_suspend_svc_domain {
633   my( $self, $svc_domain) = (shift, shift);
634
635   #XXX domain operations
636   '';
637
638 }
639
640 sub _export_unsuspend {
641   my( $self, $svc_x ) = (shift, shift);
642
643   my $table = $svc_x->table;
644   my $method = "_export_unsuspend_$table";
645   $self->$method($svc_x, @_);
646
647 }
648
649 sub _export_unsuspend_svc_acct {
650   my( $self, $svc_acct ) = (shift, shift);
651
652   $self->communigate_pro_queue(
653     $svc_acct->svcnum,
654     'UpdateAccountSettings',
655     $self->export_username($svc_acct),
656     'AccessModes' => ( $svc_acct->cgp_accessmodes
657                          || $self->option('AccessModes') ),
658   );
659
660 }
661
662 sub _export_unsuspend_svc_domain {
663   my( $self, $svc_domain) = (shift, shift);
664
665   #XXX domain operations
666   '';
667
668 }
669
670 sub export_mailinglistmember_insert {
671   my( $self, $svc_mailinglist, $mailinglistmember ) = (shift, shift, shift);
672   $svc_mailinglist->replace();
673 }
674
675 sub export_mailinglistmember_replace {
676   my( $self, $svc_mailinglist, $new, $old ) = (shift, shift, shift, shift);
677   die "no way to do this from the UI right now";
678 }
679
680 sub export_mailinglistmember_delete {
681   my( $self, $svc_mailinglist, $mailinglistmember ) = (shift, shift, shift);
682   $svc_mailinglist->replace();
683 }
684
685 sub export_getsettings {
686   my($self, $svc_x) = (shift, shift);
687
688   my $table = $svc_x->table;
689   my $method = "export_getsettings_$table";
690
691   $self->can($method) ? $self->$method($svc_x, @_) : '';
692
693 }
694
695 sub export_getsettings_svc_domain {
696   my($self, $svc_domain, $settingsref, $defaultref ) = @_;
697
698   my $settings = eval { $self->communigate_pro_runcommand(
699     'GetDomainSettings',
700     $svc_domain->domain
701   ) };
702   return $@ if $@;
703
704   my $effective_settings = eval { $self->communigate_pro_runcommand(
705     'GetDomainEffectiveSettings',
706     $svc_domain->domain
707   ) };
708   return $@ if $@;
709
710   my $acct_defaults = eval { $self->communigate_pro_runcommand(
711     'GetAccountDefaults',
712     $svc_domain->domain
713   ) };
714   return $@ if $@;
715
716   my $acct_defaultprefs = eval { $self->communigate_pro_runcommand(
717     'GetAccountDefaultPrefs',
718     $svc_domain->domain
719   ) };
720   return $@ if $@;
721
722   my $rules = eval { $self->communigate_pro_runcommand(
723     'GetDomainMailRules',
724     $svc_domain->domain
725   ) };
726   return $@ if $@;
727
728   #aliases too
729   my $aliases = eval { $self->communigate_pro_runcommand(
730     'GetDomainAliases',
731     $svc_domain->domain
732   ) };
733   return $@ if $@;
734
735   my %more = (
736     ( map { ("Acct. Default $_" => $acct_defaults->{$_}); }
737           keys(%$acct_defaults)
738     ),
739     ( map { ("Acct. Default $_" => $acct_defaultprefs->{$_}); } #diff label??
740           keys(%$acct_defaultprefs)
741     ),
742     ( map _rule2string($_), @$rules ),
743     'Aliases' => join(', ', @$aliases),
744   );
745
746   %$effective_settings = ( %$effective_settings, %more );
747   %$settings = ( %$settings, %more );
748
749   #false laziness w/below
750   
751   my %defaults = map { $_ => 1 }
752                    grep !exists(${$settings}{$_}), keys %$effective_settings;
753
754   foreach my $key ( grep ref($effective_settings->{$_}),
755                     keys %$effective_settings )
756   {
757     $effective_settings->{$key} = _pretty( $effective_settings->{$key} );
758   }
759
760   %{$settingsref} = %$effective_settings;
761   %{$defaultref} = %defaults;
762
763   '';
764 }
765
766 sub export_getsettings_svc_acct {
767   my($self, $svc_acct, $settingsref, $defaultref ) = @_;
768
769   my $settings = eval { $self->communigate_pro_runcommand(
770     'GetAccountSettings',
771     $svc_acct->email
772   ) };
773   return $@ if $@;
774
775   delete($settings->{'Password'});
776
777   my $effective_settings = eval { $self->communigate_pro_runcommand(
778     'GetAccountEffectiveSettings',
779     $svc_acct->email
780   ) };
781   return $@ if $@;
782
783   delete($effective_settings->{'Password'});
784
785   #prefs/effectiveprefs too
786
787   my $prefs = eval { $self->communigate_pro_runcommand(
788     'GetAccountPrefs',
789     $svc_acct->email
790   ) };
791   return $@ if $@;
792
793   my $effective_prefs = eval { $self->communigate_pro_runcommand(
794     'GetAccountEffectivePrefs',
795     $svc_acct->email
796   ) };
797   return $@ if $@;
798
799   %$effective_settings = ( %$effective_settings,
800                            map { ("Pref $_" => $effective_prefs->{$_}); }
801                                keys(%$effective_prefs)
802                          );
803   %$settings = ( %$settings,
804                  map { ("Pref $_" => $prefs->{$_}); }
805                      keys(%$prefs)
806                );
807
808   #mail rules
809   my $rules = eval { $self->communigate_pro_runcommand(
810     'GetAccountMailRules',
811     $svc_acct->email
812   ) };
813   return $@ if $@;
814
815   %$effective_settings = ( %$effective_settings,
816                            map _rule2string($_), @$rules
817                          );
818   %$settings = ( %$settings,
819                  map _rule2string($_), @$rules
820                );
821
822 #  #rpops too
823 #  my $rpops = eval { $self->communigate_pro_runcommand(
824 #    'GetAccountRPOPs',
825 #    $svc_acct->email
826 #  ) };
827 #  return $@ if $@;
828 #
829 #  %$effective_settings = ( %$effective_settings,
830 #                           map _rpop2string($_), %$rpops
831 #                         );
832 #  %$settings = ( %$settings,
833 #                 map _rpop2string($_), %rpops
834 #               );
835
836   #aliases too
837   my $aliases = eval { $self->communigate_pro_runcommand(
838     'GetAccountAliases',
839     $svc_acct->email
840   ) };
841   return $@ if $@;
842
843   $effective_settings->{'Aliases'} = join(', ', @$aliases);
844   $settings->{'Aliases'}           = join(', ', @$aliases);
845
846   #false laziness w/above
847
848   my %defaults = map { $_ => 1 }
849                    grep !exists(${$settings}{$_}), keys %$effective_settings;
850
851   foreach my $key ( grep ref($effective_settings->{$_}),
852                     keys %$effective_settings )
853   {
854     $effective_settings->{$key} = _pretty( $effective_settings->{$key} );
855   }
856
857   %{$settingsref} = %$effective_settings;
858   %{$defaultref} = %defaults;
859
860   '';
861
862 }
863
864 sub _pretty {
865   my $value = shift;
866   if ( ref($value) eq 'ARRAY' ) {
867     '['. join(' ', map { ref($_) ? _pretty($_) : $_ } @$value ). ']';
868   } elsif ( ref($value) eq 'HASH' ) {
869     '{'. join(', ',
870         map { my $v = $value->{$_};
871               "$_:". ( ref($v) ? _pretty($v) : $v );
872             }
873             keys %$value
874     ). '}';
875   } else {
876     warn "serializing ". ref($value). " for table display not yet handled";
877   }
878 }
879
880 sub export_getsettings_svc_forward {
881   my($self, $svc_forward, $settingsref, $defaultref ) = @_;
882
883   my $dest = eval { $self->communigate_pro_runcommand(
884     'GetForwarder',
885     ($svc_forward->src || $svc_forward->srcsvc_acct->email),
886   ) };
887   return $@ if $@;
888
889   my $settings = { 'Destination' => $dest };
890
891   %{$settingsref} = %$settings;
892   %{$defaultref} = ();
893
894   '';
895 }
896
897 sub _rule2string {
898   my $rule = shift;
899   my($priority, $name, $conditions, $actions, $comment) = @$rule;
900   $conditions = join(', ', map { my $a = $_; join(' ', @$a); } @$conditions);
901   $actions    = join(', ', map { my $a = $_; join(' ', @$a); } @$actions);
902   ("Mail rule $name" => "$priority IF $conditions THEN $actions ($comment)");
903 }
904
905 #sub _rpop2string {
906 #  my $rpop = shift;
907 #  my($priority, $name, $conditions, $actions, $comment) = @$rule;
908 #  $conditions = join(', ', map { my $a = $_; join(' ', @$a); } @$conditions);
909 #  $actions    = join(', ', map { my $a = $_; join(' ', @$a); } @$actions);
910 #  ("Mail rule $name" => "$priority IF $conditions THEN $actions ($comment)");
911 #}
912
913 sub export_getsettings_svc_mailinglist {
914   my($self, $svc_mailinglist, $settingsref, $defaultref ) = @_;
915
916   my $settings = eval { $self->communigate_pro_runcommand(
917     'GetGroup',
918     $svc_mailinglist->username.'@'.$svc_mailinglist->domain,
919   ) };
920   return $@ if $@;
921
922   $settings->{'Members'} = join(', ', @{ $settings->{'Members'} } );
923
924   %{$settingsref} = %$settings;
925
926   '';
927 }
928
929 sub communigate_pro_queue {
930   my( $self, $svcnum, $method ) = (shift, shift, shift);
931   my $jobnum = ''; #don't actually care
932   $self->communigate_pro_queue_dep( \$jobnum, $svcnum, $method, @_);
933 }
934
935 sub communigate_pro_queue_dep {
936   my( $self, $jobnumref, $svcnum, $method ) = splice(@_,0,4);
937
938   my %kludge_methods = (
939     #'CreateAccount'             => 'CreateAccount',
940     'UpdateAccountSettings'     => 'UpdateAccountSettings',
941     'UpdateAccountPrefs'        => 'cp_Scalar_Hash',
942     #'CreateDomain'              => 'cp_Scalar_Hash',
943     #'CreateSharedDomain'        => 'cp_Scalar_Hash',
944     'UpdateDomainSettings'      => 'cp_Scalar_settingsHash',
945     'SetDomainAliases'          => 'cp_Scalar_Array',
946     'SetAccountDefaults'        => 'cp_Scalar_settingsHash',
947     'UpdateAccountDefaults'     => 'cp_Scalar_settingsHash',
948     'SetAccountDefaultPrefs'    => 'cp_Scalar_settingsHash',
949     'UpdateAccountDefaultPrefs' => 'cp_Scalar_settingsHash',
950     'SetAccountRPOPs'           => 'cp_Scalar_Hash',
951   );
952   my $sub = exists($kludge_methods{$method})
953               ? $kludge_methods{$method}
954               : 'communigate_pro_command';
955
956   my $queue = new FS::queue {
957     'svcnum' => $svcnum,
958     'job'    => "FS::part_export::communigate_pro::$sub",
959   };
960   my $error = $queue->insert(
961     $self->machine,
962     $self->option('port'),
963     $self->option('login'),
964     $self->option('password'),
965     $method,
966     @_,
967   );
968   $$jobnumref = $queue->jobnum unless $error;
969
970   return $error;
971 }
972
973 sub communigate_pro_runcommand {
974   my( $self, $method ) = (shift, shift);
975
976   communigate_pro_command(
977     $self->machine,
978     $self->option('port'),
979     $self->option('login'),
980     $self->option('password'),
981     $method,
982     @_,
983   );
984
985 }
986
987 #XXX one sub per arg prototype is lame.  more magic?  i suppose queue needs
988 # to store data strctures properly instead of just an arg list.  right.
989
990 sub cp_Scalar_Hash {
991   my( $machine, $port, $login, $password, $method, $scalar, %hash ) = @_;
992   my @args = ( $scalar, \%hash );
993   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
994 }
995
996 sub cp_Scalar_Array {
997   my( $machine, $port, $login, $password, $method, $scalar, @array ) = @_;
998   my @args = ( $scalar, \@array );
999   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
1000 }
1001
1002 #sub cp_Hash {
1003 #  my( $machine, $port, $login, $password, $method, %hash ) = @_;
1004 #  my @args = ( \%hash );
1005 #  communigate_pro_command( $machine, $port, $login, $password, $method, @args );
1006 #}
1007
1008 sub cp_Scalar_settingsHash {
1009   my( $machine, $port, $login, $password, $method, $domain, %settings ) = @_;
1010   for (qw( AccessModes DomainAccessModes )) {
1011     $settings{$_} = [split(' ',$settings{$_})] if $settings{$_};
1012   }
1013   my @args = ( 'domain' => $domain, 'settings' => \%settings );
1014   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
1015 }
1016
1017 #sub CreateAccount {
1018 #  my( $machine, $port, $login, $password, $method, %args ) = @_;
1019 #  my $accountName  = delete $args{'accountName'};
1020 #  my $accountType  = delete $args{'accountType'};
1021 #  my $externalFlag = delete $args{'externalFlag'};
1022 #  $args{'AccessModes'} = [ split(' ', $args{'AccessModes'}) ];
1023 #  my @args = ( accountName  => $accountName,
1024 #               accountType  => $accountType,
1025 #               settings     => \%args,
1026 #             );
1027 #               #externalFlag => $externalFlag,
1028 #  push @args, externalFlag => $externalFlag if $externalFlag;
1029 #
1030 #  communigate_pro_command( $machine, $port, $login, $password, $method, @args );
1031 #
1032 #}
1033
1034 sub UpdateAccountSettings {
1035   my( $machine, $port, $login, $password, $method, $accountName, %args ) = @_;
1036   $args{'AccessModes'} = [ split(' ', $args{'AccessModes'}) ];
1037   my @args = ( $accountName, \%args );
1038   communigate_pro_command( $machine, $port, $login, $password, $method, @args );
1039 }
1040
1041 sub communigate_pro_command { #subroutine, not method
1042   my( $machine, $port, $login, $password, $method, @args ) = @_;
1043
1044   eval "use CGP::CLI";
1045   die $@ if $@;
1046
1047   my $cli = new CGP::CLI( {
1048     'PeerAddr' => $machine,
1049     'PeerPort' => $port,
1050     'login'    => $login,
1051     'password' => $password,
1052   } ) or die "Can't login to CGPro: $CGP::ERR_STRING\n";
1053
1054   #warn "$method ". Dumper(@args) if $DEBUG;
1055
1056   my $return = $cli->$method(@args)
1057     or die "Communigate Pro error: ". $cli->getErrMessage. "\n";
1058
1059   $cli->Logout; # or die "Can't logout of CGPro: $CGP::ERR_STRING\n";
1060
1061   $return;
1062
1063 }
1064
1065 1;
1066