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