-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathclass.admin_mail.inc.php
More file actions
1846 lines (1740 loc) · 67.3 KB
/
class.admin_mail.inc.php
File metadata and controls
1846 lines (1740 loc) · 67.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* EGroupware EMailAdmin: Wizard to create mail accounts
*
* @link http://www.egroupware.org
* @package emailadmin
* @author Ralf Becker <rb@egroupware.org>
* @copyright (c) 2013-18 by Ralf Becker <rb@egroupware.org>
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
*/
use EGroupware\Api;
use EGroupware\Api\Framework;
use EGroupware\Api\Acl;
use EGroupware\Api\Etemplate;
use EGroupware\Api\Mail;
use EGroupware\Api\Auth\OpenIDConnectClient;
use Jumbojett\OpenIDConnectClientException;
/**
* Wizard to create mail accounts
*
* Wizard uses follow heuristic to search for IMAP accounts:
* 1. query Mozilla ISPDB for domain from email (perfering SSL over STARTTLS over insecure connection)
* 2. guessing and verifying in DNS server-names based on domain from email:
* - (imap|smtp).$domain, mail.$domain
* - MX is *.mail.protection.outlook.com use (outlook|smtp).office365.com
* - MX for $domain
* - replace host in MX with (imap|smtp) or mail
*/
class admin_mail
{
/**
* Enable logging of IMAP communication to given path, eg. /tmp/autoconfig.log
*/
const DEBUG_LOG = null; //'/var/lib/egroupware/imap.log';
/**
* Connection timeout in seconds used in autoconfig, can and should be really short!
*/
const TIMEOUT = 3;
/**
* Prefix for callback names
*
* Used as static::APP_CLASS in etemplate::exec(), to allow mail app extending this class.
*/
const APP_CLASS = 'admin.admin_mail.';
/**
* 0: No SSL
*/
const SSL_NONE = Mail\Account::SSL_NONE;
/**
* 1: STARTTLS on regular tcp connection/port
*/
const SSL_STARTTLS = Mail\Account::SSL_STARTTLS;
/**
* 3: SSL (inferior to TLS!)
*/
const SSL_SSL = Mail\Account::SSL_SSL;
/**
* 2: require TLS version 1+, no SSL version 2 or 3
*/
const SSL_TLS = Mail\Account::SSL_TLS;
/**
* 8: if set, verify certifcate (currently not implemented in Horde_Imap_Client!)
*/
const SSL_VERIFY = Mail\Account::SSL_VERIFY;
/**
* Log exception including trace to error-log, instead of just displaying the message.
*
* @var boolean
*/
public static $debug = false;
/**
* Methods callable via menuaction
*
* @var array
*/
public $public_functions = array(
'add' => true,
'edit' => true,
'ajax_activeAccounts' => true
);
/**
* Supported ssl types including none
*
* @var array
*/
public static $ssl_types = array(
self::SSL_TLS => 'TLS', // SSL with minimum TLS (no SSL v.2 or v.3), requires Horde_Imap_Client-2.16.0/Horde_Socket_Client-1.1.0
self::SSL_SSL => 'SSL',
self::SSL_STARTTLS => 'STARTTLS',
'no' => 'no',
);
/**
* Convert ssl-type to Horde secure parameter
*
* @var array
*/
public static $ssl2secure = array(
'SSL' => 'ssl',
'STARTTLS' => 'tls',
'TLS' => 'tlsv1', // SSL with minimum TLS (no SSL v.2 or v.3), requires Horde_Imap_Client-2.16.0/Horde_Socket_Client-1.1.0
);
/**
* Convert ssl-type to eMailAdmin acc_(imap|sieve|smtp)_ssl integer value
*
* @var array
*/
public static $ssl2type = array(
'TLS' => self::SSL_TLS,
'SSL' => self::SSL_SSL,
'STARTTLS' => self::SSL_STARTTLS,
'no' => self::SSL_NONE,
);
/**
* Available IMAP login types
*
* @var array
*/
public static $login_types = array(
'' => 'Username specified below for all',
'standard' => 'username from account',
'vmailmgr' => 'username@domainname',
//'admin' => 'Username/Password defined by admin',
'uidNumber' => 'UserId@domain eg. u1234@domain',
'email' => 'EMail-address from account',
'domain/username' => 'Exchange: domain/username',
);
/**
* Options for further identities
*
* @var array
*/
public static $further_identities = array(
0 => 'Forbid users to create identities',
1 => 'Allow users to create further identities',
2 => 'Allow users to create identities for aliases',
);
/**
* List of domains know to not support Sieve
*
* Used to switch Sieve off by default, thought users can always try switching it on.
* Testing not existing Sieve with google takes a long time, as ports are open,
* but not answering ...
*
* @var array
*/
public static $no_sieve_blacklist = array('gmail.com', 'googlemail.com', 'outlook.office365.com');
/**
* Is current use a mail administrator / has run rights for EMailAdmin
*
* @var boolean
*/
protected $is_admin = false;
/**
* Constructor
*/
public function __construct()
{
$this->is_admin = isset($GLOBALS['egw_info']['user']['apps']['admin']);
// for some reason most translation for account-wizard are in mail
Api\Translation::add_app('mail');
// Horde use locale for translation of error messages
Api\Preferences::setlocale(LC_MESSAGES);
}
/**
* Step 1: IMAP account
*
* @param array $content
* @param string $msg
*/
public function add(array $content=array(), $msg='', $msg_type='success')
{
$tpl = new Etemplate('admin.mailwizard');
if (empty($content['account_id']))
{
$content['account_id'] = $GLOBALS['egw_info']['user']['account_id'];
}
// add some defaults if not already set (+= does not overwrite existing values!)
$content += array(
'ident_realname' => $GLOBALS['egw']->accounts->id2name($content['account_id'], 'account_fullname'),
'ident_email' => $GLOBALS['egw']->accounts->id2name($content['account_id'], 'account_email'),
'acc_imap_port' => 993,
'manual_class' => 'emailadmin_manual',
);
Framework::message($msg ? $msg : (string)$_GET['msg'], $msg_type);
if (!empty($content['acc_imap_host']) || !empty($content['acc_imap_username']))
{
$readonlys['button[manual]'] = true;
unset($content['manual_class']);
}
$tpl->exec(static::APP_CLASS.'autoconfig', $content, array(
'acc_imap_ssl' => self::$ssl_types,
), $readonlys, $content, 2);
}
/**
* Try to autoconfig an account
*
* @param array $content
*/
public function autoconfig(array $content)
{
// user pressed [Skip IMAP] --> jump to SMTP config
if (!empty($content['button']) && key($content['button']) === 'skip_imap')
{
unset($content['button']);
if (!isset($content['acc_smtp_host'])) $content['acc_smtp_host'] = ''; // do manual mode right away
return $this->smtp($content, lang('Skipping IMAP configuration!'));
}
$tpl = new Etemplate('admin.mailwizard');
$sel_options = $readonlys = $hosts = [];
$connected = $content['connected'] ?? null;
if (empty($content['acc_imap_username']))
{
$content['acc_imap_username'] = $content['ident_email'];
}
// supported oauth provider or mail-server of them for custom domains
if (($oauth = OpenIDConnectClient::providerByDomain($content['acc_imap_username'], $content['acc_imap_host'])))
{
$content['output'] .= lang('Using IMAP:%1, SMTP:%2, OAUTH:%3:', $oauth['imap'], $oauth['smtp'], $oauth['provider'])."\n";
$hosts[$oauth['imap']] = true;
$content += self::oauth2content($oauth);
}
elseif (!empty($content['acc_imap_host']))
{
$hosts = array($content['acc_imap_host'] => true);
if ($content['acc_imap_port'] > 0 && !in_array($content['acc_imap_port'], array(143,993)))
{
$ssl_type = (string)array_search($content['acc_imap_ssl'], self::$ssl2type);
if ($ssl_type === '') $ssl_type = 'insecure';
$hosts[$content['acc_imap_host']] = array(
$ssl_type => $content['acc_imap_port'],
);
}
}
elseif (($ispdb = self::mozilla_ispdb($content['ident_email'])) && count($ispdb['imap']))
{
$content['ispdb'] = $ispdb;
$content['output'] .= lang('Using data from Mozilla ISPDB for provider %1', $ispdb['displayName'])."\n";
$hosts = array();
foreach($ispdb['imap'] as $server)
{
if (!isset($hosts[$server['hostname']]))
{
$hosts[$server['hostname']] = array('username' => $server['username']);
}
if (strtoupper($server['socketType']) == 'SSL') // try TLS first
{
$hosts[$server['hostname']]['TLS'] = $server['port'];
}
$hosts[$server['hostname']][strtoupper($server['socketType'])] = $server['port'];
// make sure we prefer SSL over STARTTLS over insecure
if (count($hosts[$server['hostname']]) > 2)
{
$hosts[$server['hostname']] = self::fix_ssl_order($hosts[$server['hostname']]);
}
}
}
else
{
$hosts = $this->guess_hosts($content['ident_email'], 'imap');
}
// check if support OAuth for that domain or we have a password
if (empty($oauth) && empty($content['acc_oauth_provider_url']) && empty($content['acc_imap_password']))
{
Etemplate::set_validation_error('acc_imap_password', lang('Field must not be empty!'));
$connected = false;
}
// iterate over all hosts and try to connect
foreach(!isset($connected) ? $hosts : [] as $host => $data)
{
// check if we support OAuth for the (manual) configured mail-server
if (empty($content['acc_oauth_provider_url']) && ($oauth = OpenIDConnectClient::providerByDomain($content['acc_imap_username'], $host)))
{
$content += self::oauth2content($oauth);
}
$content['acc_imap_host'] = $host;
// by default we check SSL, STARTTLS and at last an insecure connection
if (!is_array($data)) $data = array('TLS' => 993, 'SSL' => 993, 'STARTTLS' => 143, 'insecure' => 143);
foreach($data as $ssl => $port)
{
if ($ssl === 'username') continue;
$content['acc_imap_ssl'] = (int)self::$ssl2type[$ssl];
$e = null;
try {
$content['output'] .= "\n".Api\DateTime::to('now', 'H:i:s').": Trying $ssl connection to $host:$port ...\n";
$content['acc_imap_port'] = $port;
$imap = self::imap_client($content, self::TIMEOUT);
//$content['output'] .= array2string($imap->capability());
$imap->login();
$content['output'] .= "\n".lang('Successful connected to %1 server%2.', 'IMAP', ' '.lang('and logged in'))."\n";
if (!$imap->isSecureConnection())
{
$content['output'] .= lang('Connection is NOT secure! Everyone can read eg. your credentials.')."\n";
$content['acc_imap_ssl'] = 'no';
}
//$content['output'] .= "\n\n".array2string($imap->capability());
$content['connected'] = $connected = true;
break 2;
}
catch(Horde_Imap_Client_Exception $e)
{
switch($e->getCode())
{
case Horde_Imap_Client_Exception::LOGIN_AUTHENTICATIONFAILED:
$content['output'] .= "\n".$e->getMessage()."\n";
break 3; // no need to try other SSL or non-SSL connections, if auth failed
case Horde_Imap_Client_Exception::SERVER_CONNECT:
$content['output'] .= "\n".$e->getMessage()."\n";
if ($ssl == 'STARTTLS') break 2; // no need to try insecure connection on same port
break;
default:
$content['output'] .= "\n".get_class($e).': '.$e->getMessage().' ('.$e->getCode().')'."\n";
//$content['output'] .= $e->getTraceAsString()."\n";
}
if (self::$debug) _egw_log_exception($e);
}
catch(Exception $e) {
$content['output'] .= "\n".get_class($e).': '.$e->getMessage().' ('.$e->getCode().')'."\n";
//$content['output'] .= $e->getTraceAsString()."\n";
if (self::$debug) _egw_log_exception($e);
}
}
}
if ($connected) // continue with next wizard step: define folders
{
unset($content['button']);
return $this->folder($content, lang('Successful connected to %1 server%2.', 'IMAP', ' '.lang('and logged in')).
($imap->isSecureConnection() ? '' : "\n".lang('Connection is NOT secure! Everyone can read eg. your credentials.')));
}
// add validation error, if we can identify a field
if (!$connected && $e instanceof Horde_Imap_Client_Exception)
{
switch($e->getCode())
{
case Horde_Imap_Client_Exception::LOGIN_AUTHENTICATIONFAILED:
Etemplate::set_validation_error('acc_imap_username', lang($e->getMessage()));
Etemplate::set_validation_error('acc_imap_password', lang($e->getMessage()));
break;
case Horde_Imap_Client_Exception::SERVER_CONNECT:
Etemplate::set_validation_error('acc_imap_host', lang($e->getMessage()));
break;
}
}
$readonlys['button[manual]'] = true;
unset($content['manual_class'], $content['button']);
$sel_options['acc_imap_ssl'] = self::$ssl_types;
$tpl->exec(static::APP_CLASS.'autoconfig', $content, $sel_options, $readonlys,
array_diff_key($content, ['output'=>true]), 2);
}
/**
* Convert OAuth provider data to our content-names
*
* @param array $oauth
* @return array
*/
protected static function oauth2content(array $oauth)
{
return [
'acc_smpt_host' => $oauth['smtp'],
'acc_sieve_enabled' => false,
'acc_oauth_provider_url' => $oauth['provider'],
'acc_oauth_client_id' => $oauth['client'],
'acc_oauth_client_secret' => $oauth['secret'],
'acc_oauth_scopes' => $oauth['scopes'],
OpenIDConnectClient::ADD_CLIENT_TO_WELL_KNOWN => $oauth[OpenIDConnectClient::ADD_CLIENT_TO_WELL_KNOWN] ?? null,
OpenIDConnectClient::ADD_AUTH_PARAM => $oauth[OpenIDConnectClient::ADD_AUTH_PARAM] ?? null,
];
}
/**
* Step 2: Folder - let user select trash, sent, drafs and template folder
*
* @param ?array $content
* @param string $msg =''
* @param Horde_Imap_Client_Socket $imap =null
*/
public function folder(?array $content, $msg='', ?Horde_Imap_Client_Socket $imap=null)
{
if (!empty($content['button']))
{
$button = key($content['button']);
unset($content['button']);
switch($button)
{
case 'back':
return $this->add($content);
case 'continue':
return $this->sieve($content);
}
}
$content['msg'] = $msg;
if (!isset($imap)) $imap = self::imap_client ($content);
try {
//_debug_array($content);
$sel_options['acc_folder_sent'] = $sel_options['acc_folder_trash'] =
$sel_options['acc_folder_draft'] = $sel_options['acc_folder_template'] =
$sel_options['acc_folder_junk'] = $sel_options['acc_folder_archive'] =
$sel_options['acc_folder_ham'] = self::mailboxes($imap, $content);
}
catch(Exception $e) {
$content['msg'] = $e->getMessage();
if (self::$debug) _egw_log_exception($e);
}
$tpl = new Etemplate('admin.mailwizard.folder');
$tpl->exec(static::APP_CLASS.'folder', $content, $sel_options, array(), $content, 2);
}
/**
* Query mailboxes and (optional) detect special folders
*
* @param Horde_Imap_Client_Socket $imap
* @param array &$content=null on return values for acc_folder_(sent|trash|draft|template)
* @return array with folders as key AND value
* @throws Horde_Imap_Client_Exception
*/
public static function mailboxes(Horde_Imap_Client_Socket $imap, array &$content=null)
{
// query all subscribed mailboxes
$mailboxes = $imap->listMailboxes('*', Horde_Imap_Client::MBOX_SUBSCRIBED, array(
'special_use' => true,
'attributes' => true, // otherwise special_use is only queried, but not returned ;-)
'delimiter' => true,
));
//_debug_array($mailboxes);
// list mailboxes by special-use attributes
$folders = $attributes = $all = array();
foreach($mailboxes as $mailbox => $data)
{
foreach($data['attributes'] as $attribute)
{
$attributes[$attribute][] = $mailbox;
}
$folders[$mailbox] = $mailbox.': '.implode(', ', $data['attributes']);
}
// pre-select send, trash, ... folder for user, by checking special-use attributes or common name(s)
foreach(array(
'acc_folder_sent' => array('\\sent', 'sent'),
'acc_folder_trash' => array('\\trash', 'trash'),
'acc_folder_draft' => array('\\drafts', 'drafts'),
'acc_folder_template' => array('', 'templates'),
'acc_folder_junk' => array('\\junk', 'junk', 'spam'),
'acc_folder_ham' => array('', 'ham'),
'acc_folder_archive' => array('', 'archive'),
) as $name => $common_names)
{
unset($content[$name]);
// first check special-use attributes
if (($special_use = array_shift($common_names)))
{
foreach((array)$attributes[$special_use] as $mailbox)
{
if (empty($content[$name]) || is_string($mailbox) && strlen($mailbox) < strlen($content[$name]))
{
$content[$name] = $mailbox;
}
}
}
// no special use folder found, try common names
if (empty($content[$name]))
{
foreach($mailboxes as $mailbox => $data)
{
$delimiter = !empty($data['delimiter']) ? $data['delimiter'] : '.';
$name_parts = explode($delimiter, strtolower($mailbox));
if (array_intersect($name_parts, $common_names) &&
(empty($content[$name]) || is_string($mailbox) && strlen($mailbox) < strlen($content[$name]) && substr($content[$name], 0, 6) != 'INBOX'.$delimiter))
{
//error_log(__METHOD__."() $mailbox --> ".substr($name, 11).' folder');
$content[$name] = $mailbox;
}
//else error_log(__METHOD__."() $mailbox does NOT match array_intersect(".array2string($name_parts).', '.array2string($common_names).')='.array2string(array_intersect($name_parts, $common_names)));
}
}
$folders[(string)$content[$name]] .= ' --> '.substr($name, 11).' folder';
}
// uncomment for infos about selection process
//$content['folder_output'] = implode("\n", $folders);
return array_combine(array_keys($mailboxes), array_keys($mailboxes));
}
/**
* Step 3: Sieve
*
* @param array $content
* @param string $msg =''
*/
public function sieve(array $content, $msg='')
{
static $sieve_ssl2port = array(
self::SSL_TLS => 5190,
self::SSL_SSL => 5190,
self::SSL_STARTTLS => array(4190, 2000),
self::SSL_NONE => array(4190, 2000),
);
$content['msg'] = $msg;
if (!empty($content['button']))
{
$button = key($content['button']);
unset($content['button']);
switch($button)
{
case 'back':
return $this->folder($content);
case 'continue':
if (!$content['acc_sieve_enabled'])
{
return $this->smtp($content);
}
break;
}
}
// first try: hide manual config
if (!isset($content['acc_sieve_enabled']))
{
list(, $domain) = explode('@', $content['acc_imap_username']);
$content['acc_sieve_enabled'] = (int)!in_array($domain, self::$no_sieve_blacklist);
$content['manual_class'] = 'emailadmin_manual';
}
else
{
unset($content['manual_class']);
$readonlys['button[manual]'] = true;
}
// set default ssl and port
if (!isset($content['acc_sieve_ssl'])) $content['acc_sieve_ssl'] = key(self::$ssl_types);
if (empty($content['acc_sieve_port'])) $content['acc_sieve_port'] = $sieve_ssl2port[$content['acc_sieve_ssl']];
// check smtp connection
if ($button == 'continue')
{
$content['sieve_connected'] = false;
$content['sieve_output'] = '';
unset($content['manual_class']);
if (empty($content['acc_sieve_host']))
{
$content['acc_sieve_host'] = $content['acc_imap_host'];
}
// if use set non-standard port, use it
if (!in_array($content['acc_sieve_port'], (array)$sieve_ssl2port[$content['acc_sieve_ssl']]))
{
$data = array($content['acc_sieve_ssl'] => $content['acc_sieve_port']);
}
else // otherwise try all standard ports
{
$data = $sieve_ssl2port;
}
foreach($data as $ssl => $ports)
{
foreach((array)$ports as $port)
{
$content['acc_sieve_ssl'] = $ssl;
$ssl_label = self::$ssl_types[$ssl];
$e = null;
try {
$content['sieve_output'] .= "\n".Api\DateTime::to('now', 'H:i:s').": Trying $ssl_label connection to $content[acc_sieve_host]:$port ...\n";
$content['acc_sieve_port'] = $port;
$sieve = new Horde\ManageSieve(array(
'host' => $content['acc_sieve_host'],
'port' => $content['acc_sieve_port'],
'secure' => self::$ssl2secure[(string)array_search($content['acc_sieve_ssl'], self::$ssl2type)],
'timeout' => self::TIMEOUT,
'logger' => self::DEBUG_LOG ? new admin_mail_logger(self::DEBUG_LOG) : null,
));
// connect to sieve server
$sieve->connect();
$content['sieve_output'] .= "\n".lang('Successful connected to %1 server%2.', 'Sieve','');
// and log in
$sieve->login($content['acc_imap_username'], $content['acc_imap_password']);
$content['sieve_output'] .= ' '.lang('and logged in')."\n";
$content['sieve_connected'] = true;
unset($content['button']);
return $this->smtp($content, lang('Successful connected to %1 server%2.', 'Sieve',
' '.lang('and logged in')));
}
catch(Horde\ManageSieve\Exception\ConnectionFailed $e) {
$content['sieve_output'] .= "\n".$e->getMessage().' '.$e->details."\n";
}
catch(Exception $e) {
$content['sieve_output'] .= "\n".get_class($e).': '.$e->getMessage().
($e->details ? ' '.$e->details : '').' ('.$e->getCode().')'."\n";
$content['sieve_output'] .= $e->getTraceAsString()."\n";
if (self::$debug) _egw_log_exception($e);
}
}
}
// not connected, and default ssl/port --> reset again to secure settings
if ($data == $sieve_ssl2port)
{
$content['acc_sieve_ssl'] = key(self::$ssl_types);
$content['acc_sieve_port'] = $sieve_ssl2port[$content['acc_sieve_ssl']];
}
}
// add validation error, if we can identify a field
if (!$content['sieve_connected'] && $e instanceof Exception)
{
switch($e->getCode())
{
case 61: // connection refused
case 60: // connection timed out (imap.googlemail.com returns that for none-ssl/4190/2000)
case 65: // no route ot host (imap.googlemail.com returns that for ssl/5190)
Etemplate::set_validation_error('acc_sieve_host', lang($e->getMessage()));
Etemplate::set_validation_error('acc_sieve_port', lang($e->getMessage()));
break;
}
$content['msg'] = lang('No sieve support detected, either fix configuration manually or leave it switched off.');
$content['acc_sieve_enabled'] = 0;
}
$sel_options['acc_sieve_ssl'] = self::$ssl_types;
$tpl = new Etemplate('admin.mailwizard.sieve');
$tpl->exec(static::APP_CLASS.'sieve', $content, $sel_options, $readonlys, $content, 2);
}
/**
* Step 4: SMTP
*
* @param array $content
* @param string $msg =''
*/
public function smtp(array $content, $msg='')
{
static $smtp_ssl2port = array(
self::SSL_NONE => 25,
self::SSL_SSL => 465,
self::SSL_TLS => 465,
self::SSL_STARTTLS => 587,
);
$content['msg'] = $msg;
if (!empty($content['button']))
{
$button = key($content['button']);
unset($content['button']);
switch($button)
{
case 'back':
return $this->sieve($content);
}
}
// first try: hide manual config
if (!isset($content['acc_smtp_host']))
{
$content['manual_class'] = 'emailadmin_manual';
}
else
{
unset($content['manual_class']);
$readonlys['button[manual]'] = true;
}
// copy username/password from imap
if (!isset($content['acc_smtp_username'])) $content['acc_smtp_username'] = $content['acc_imap_username'];
if (!isset($content['acc_smtp_password'])) $content['acc_smtp_password'] = $content['acc_imap_password'];
// set default ssl
if (!isset($content['acc_smtp_ssl'])) $content['acc_smtp_ssl'] = key(self::$ssl_types);
if (empty($content['acc_smtp_port'])) $content['acc_smtp_port'] = $smtp_ssl2port[$content['acc_smtp_ssl']];
// check smtp connection
if ($button == 'continue')
{
$content['smtp_connected'] = false;
$content['smtp_output'] = '';
unset($content['manual_class']);
if (!empty($content['acc_smtp_host']))
{
$hosts = array($content['acc_smtp_host'] => true);
if ((string)$content['acc_smtp_ssl'] !== (string)self::SSL_TLS || $content['acc_smtp_port'] != $smtp_ssl2port[$content['acc_smtp_ssl']])
{
$ssl_type = (string)array_search($content['acc_smtp_ssl'], self::$ssl2type);
$hosts[$content['acc_smtp_host']] = array(
$ssl_type => $content['acc_smtp_port'],
);
}
}
elseif($content['ispdb'] && !empty($content['ispdb']['smtp']))
{
$content['smtp_output'] .= lang('Using data from Mozilla ISPDB for provider %1', $content['ispdb']['displayName'])."\n";
$hosts = array();
foreach($content['ispdb']['smtp'] as $server)
{
if (!isset($hosts[$server['hostname']]))
{
$hosts[$server['hostname']] = array('username' => $server['username']);
}
if (strtoupper($server['socketType']) == 'SSL') // try TLS first
{
$hosts[$server['hostname']]['TLS'] = $server['port'];
}
$hosts[$server['hostname']][strtoupper($server['socketType'])] = $server['port'];
// make sure we prefer SSL over STARTTLS over insecure
if (count($hosts[$server['hostname']]) > 2)
{
$hosts[$server['hostname']] = self::fix_ssl_order($hosts[$server['hostname']]);
}
}
}
else
{
$hosts = $this->guess_hosts($content['ident_email'], 'smtp');
}
foreach($hosts as $host => $data)
{
$content['acc_smtp_host'] = $host;
if (!is_array($data))
{
$data = array('TLS' => 465, 'SSL' => 465, 'STARTTLS' => 587, '' => 25);
}
foreach($data as $ssl => $port)
{
if ($ssl === 'username') continue;
$content['acc_smtp_ssl'] = (int)self::$ssl2type[$ssl];
$e = null;
try {
$content['smtp_output'] .= "\n".Api\DateTime::to('now', 'H:i:s').": Trying $ssl connection to $host:$port ...\n";
$content['acc_smtp_port'] = $port;
$params = [
'username' => $content['acc_smtp_username'],
'password' => $content['acc_smtp_password'],
'host' => $content['acc_smtp_host'],
'port' => $content['acc_smtp_port'],
'secure' => self::$ssl2secure[(string)array_search($content['acc_smtp_ssl'], self::$ssl2type)],
'timeout' => self::TIMEOUT,
'debug' => self::DEBUG_LOG,
];
if (!empty($content['acc_oauth_provider_url']))
{
$params['xoauth2_token'] = self::oauthToken($content, true);
}
$mail = new Horde_Mail_Transport_Smtphorde($params);
// create smtp connection and authenticate, if credentials given
$smtp = $mail->getSMTPObject();
$content['smtp_output'] .= "\n".lang('Successful connected to %1 server%2.', 'SMTP',
(!empty($content['acc_smtp_username']) ? ' '.lang('and logged in') : ''))."\n";
if (!$smtp->isSecureConnection())
{
if (!empty($content['acc_smtp_username']))
{
$content['smtp_output'] .= lang('Connection is NOT secure! Everyone can read eg. your credentials.')."\n";
}
$content['acc_smtp_ssl'] = 'no';
}
// Horde_Smtp always try to use STARTTLS, adjust our ssl-parameter if successful
elseif (!($content['acc_smtp_ssl'] > self::SSL_NONE))
{
//error_log(__METHOD__."() new Horde_Mail_Transport_Smtphorde(".array2string($params).")->getSMTPObject()->isSecureConnection()=".array2string($smtp->isSecureConnection()));
$content['acc_smtp_ssl'] = self::SSL_STARTTLS;
}
// try sending a mail to a different domain, if not authenticated, to see if that's required
if (empty($content['acc_smtp_username']))
{
$smtp->send($content['ident_email'], 'noreply@example.com', '');
$content['smtp_output'] .= "\n".lang('Relay access checked')."\n";
}
$content['smtp_connected'] = true;
unset($content['button']);
return $this->edit($content, lang('Successful connected to %1 server%2.', 'SMTP',
empty($content['acc_smtp_username']) ? ' - '.lang('Relay access checked') : ' '.lang('and logged in')));
}
// unfortunately LOGIN_AUTHENTICATIONFAILED and SERVER_CONNECT are thrown as Horde_Mail_Exception
// while others are thrown as Horde_Smtp_Exception --> using common base Horde_Exception_Wrapped
catch(Horde_Exception_Wrapped $e)
{
switch($e->getCode())
{
case Horde_Smtp_Exception::LOGIN_AUTHENTICATIONFAILED:
case Horde_Smtp_Exception::LOGIN_REQUIREAUTHENTICATION:
case Horde_Smtp_Exception::UNSPECIFIED:
$content['smtp_output'] .= "\n".$e->getMessage()."\n";
break;
case Horde_Smtp_Exception::SERVER_CONNECT:
$content['smtp_output'] .= "\n".$e->getMessage()."\n";
break;
default:
$content['smtp_output'] .= "\n".$e->getMessage().' ('.$e->getCode().')'."\n";
break;
}
if (self::$debug) _egw_log_exception($e);
}
catch(Horde_Smtp_Exception $e)
{
// prever $e->details over $e->getMessage() as it contains original message from SMTP server (eg. relay access denied)
$content['smtp_output'] .= "\n".(empty($e->details) ? $e->getMessage().' ('.$e->getCode().')' : $e->details)."\n";
//$content['smtp_output'] .= $e->getTraceAsString()."\n";
if (self::$debug) _egw_log_exception($e);
}
catch(Exception $e) {
$content['smtp_output'] .= "\n".get_class($e).': '.$e->getMessage().' ('.$e->getCode().')'."\n";
//$content['smtp_output'] .= $e->getTraceAsString()."\n";
if (self::$debug) _egw_log_exception($e);
}
}
}
}
// add validation error, if we can identify a field
if (!$content['smtp_connected'] && $e instanceof Horde_Exception_Wrapped)
{
switch($e->getCode())
{
case Horde_Smtp_Exception::LOGIN_AUTHENTICATIONFAILED:
case Horde_Smtp_Exception::LOGIN_REQUIREAUTHENTICATION:
case Horde_Smtp_Exception::UNSPECIFIED:
Etemplate::set_validation_error('acc_smtp_username', lang($e->getMessage()));
Etemplate::set_validation_error('acc_smtp_password', lang($e->getMessage()));
break;
case Horde_Smtp_Exception::SERVER_CONNECT:
Etemplate::set_validation_error('acc_smtp_host', lang($e->getMessage()));
Etemplate::set_validation_error('acc_smtp_port', lang($e->getMessage()));
break;
}
}
$sel_options['acc_smtp_ssl'] = self::$ssl_types;
$tpl = new Etemplate('admin.mailwizard.smtp');
$tpl->exec(static::APP_CLASS.'smtp', $content, $sel_options, $readonlys, $content, 2);
}
/**
* Edit mail account(s)
*
* Gets either called with GET parameter:
*
* a) account_id from admin >> Manage users to edit / add mail accounts for a user
* --> shows selectbox to switch between different mail accounts of user and "create new account"
*
* b) via mail_wizard proxy class by regular mail user to edit (acc_id GET parameter) or create new mail account
*
* @param ?array $content =null
* @param string $msg =''
* @param string $msg_type ='success'
*/
public function edit(?array $content=null, $msg='', $msg_type='success')
{
// app is trying to tell something, while redirecting to wizard
if (empty($content) && $_GET['acc_id'] && empty($msg) && !empty( $_GET['msg']))
{
if (stripos($_GET['msg'],'fatal error:')!==false || $_GET['msg_type'] == 'error') $msg_type = 'error';
}
if ($content['acc_id'] || (isset($_GET['acc_id']) && (int)$_GET['acc_id'] > 0) ) Mail::unsetCachedObjects($content['acc_id']?$content['acc_id']:$_GET['acc_id']);
$tpl = new Etemplate('admin.mailaccount');
if (!is_array($content) || !empty($content['acc_id']) && isset($content['old_acc_id']) && $content['acc_id'] != $content['old_acc_id'])
{
if (!is_array($content)) $content = array();
if ($this->is_admin && isset($_GET['account_id']))
{
$content['called_for'] = (int)$_GET['account_id'];
$content['accounts'] = iterator_to_array(Mail\Account::search($content['called_for']));
if (!empty($content['accounts']))
{
$content['acc_id'] = key($content['accounts']);
//error_log(__METHOD__.__LINE__.'.'.array2string($content['acc_id']));
// test if the "to be selected" account is imap or not
if (is_array($content['accounts']) && count($content['accounts'])>1 && Mail\Account::is_multiple($content['acc_id']))
{
try {
$account = Mail\Account::read($content['acc_id'], $content['called_for']);
//try to select the first account that is of type imap
if (!$account->is_imap())
{
$content['acc_id'] = key($content['accounts']);
//error_log(__METHOD__.__LINE__.'.'.array2string($content['acc_id']));
}
}
catch(Api\Exception\NotFound $e) {
if (self::$debug) _egw_log_exception($e);
}
}
}
if (!$content['accounts']) // no email account, call wizard
{
return $this->add(array('account_id' => (int)$_GET['account_id']));
}
$content['accounts']['new'] = lang('Create new account');
}
if (isset($_GET['acc_id']) && (int)$_GET['acc_id'] > 0)
{
$content['acc_id'] = (int)$_GET['acc_id'];
}
// clear current account-data, as account has changed and we going to read selected one
$content = array_intersect_key($content, array_flip(array('called_for', 'accounts', 'acc_id', 'tabs')));
if ($content['acc_id'] === 'new')
{
$content['account_id'] = $content['called_for'];
$content['old_acc_id'] = $content['acc_id']; // to not call add/wizard, if we return from to
unset($content['tabs']);
return $this->add($content);
}
elseif ($content['acc_id'] > 0)
{
try {
$account = Mail\Account::read($content['acc_id'], $this->is_admin && !empty($content['called_for']) ?
$content['called_for'] : $GLOBALS['egw_info']['user']['account_id']);
$account->getUserData(); // quota, aliases, forwards etc.
$content += $account->params;
foreach(['acc_imap_password', 'acc_smtp_password'] as $n)
{
if (isset($content['acc_oauth_username']) && $content[$n] === Mail\Credentials::UNAVAILABLE)
{
unset($content[$n]);
}
}
$content['notify_use_default'] = !$content['notify_account_id'];
self::fix_account_id_0($content['account_id']);
// read identities (of current user) and mark std identity
$content['identities'] = iterator_to_array(Mail\Account::identities($account, true, 'name', $content['called_for']));
$content['std_ident_id'] = $content['ident_id'];
$content['identities'][$content['std_ident_id']] = lang('Standard identity');
// change self::SSL_NONE (=0) to "no" used in sel_options
foreach(array('imap','smtp','sieve') as $type)
{
if (!$content['acc_'.$type.'_ssl']) $content['acc_'.$type.'_ssl'] = 'no';
}
}
catch(Api\Exception\NotFound $e) {
if (self::$debug) _egw_log_exception($e);
Framework::window_close(lang('Account not found!'));
}
catch(Exception $e) {
if (self::$debug) _egw_log_exception($e);
Framework::window_close($e->getMessage().' ('.get_class($e).': '.$e->getCode().')');
}
}
}
// some defaults for new accounts
if (!isset($content['account_id']) || empty($content['acc_id']) || $content['acc_id'] === 'new')
{
if (!isset($content['account_id'])) $content['account_id'] = array($GLOBALS['egw_info']['user']['account_id']);
$content['acc_user_editable'] = $content['acc_further_identities'] = true;
$readonlys['ident_id'] = true; // need to create standard identity first
}
if (empty($content['acc_name']))
{
$content['acc_name'] = $content['ident_email'];
}
// disable some stuff for non-emailadmins (all values are preserved!)
if (!$this->is_admin)
{
$readonlys = array(
'account_id' => true, 'button[multiple]' => true, 'acc_user_editable' => true,
'acc_further_identities' => true,
'acc_imap_type' => true, 'acc_imap_logintype' => true, 'acc_domain' => true,
'acc_imap_admin_username' => true, 'acc_imap_admin_password' => true, 'acc_imap_admin_use_without_pw' => true,
'acc_smtp_type' => true, 'acc_smtp_auth_session' => true,
);
}
// ensure correct values for single user mail accounts (we only hide them client-side)
if (!($is_multiple = Mail\Account::is_multiple($content)))
{
$content['acc_imap_type'] = 'EGroupware\\Api\\Mail\\Imap';
unset($content['acc_imap_login_type']);
$content['acc_smtp_type'] = 'EGroupware\\Api\\Mail\\Smtp';
unset($content['acc_smtp_auth_session']);
unset($content['notify_use_default']);
}
// copy ident_email_alias selectbox back to regular name
elseif (isset($content['ident_email_alias']) && !empty ($content['ident_email_alias']))
{
$content['ident_email'] = $content['ident_email_alias'];
}
$edit_access = Mail\Account::check_access(Acl::EDIT, $content);