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