/
Socket.php
4813 lines (4214 loc) · 168 KB
/
Socket.php
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
/**
* Originally based on code from:
* - auth.php (1.49)
* - imap_general.php (1.212)
* - imap_messages.php (revision 13038)
* - strings.php (1.184.2.35)
* from the Squirrelmail project.
* Copyright (c) 1999-2007 The SquirrelMail Project Team
*
* Copyright 2005-2014 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @category Horde
* @copyright 1999-2007 The SquirrelMail Project Team
* @copyright 2005-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Imap_Client
*/
/**
* An interface to an IMAP4rev1 server (RFC 3501) using built-in PHP features.
*
* Implements the following IMAP-related RFCs (see
* http://www.iana.org/assignments/imap4-capabilities):
* <pre>
* - RFC 2086/4314: ACL
* - RFC 2087: QUOTA
* - RFC 2088: LITERAL+
* - RFC 2195: AUTH=CRAM-MD5
* - RFC 2221: LOGIN-REFERRALS
* - RFC 2342: NAMESPACE
* - RFC 2595/4616: TLS & AUTH=PLAIN
* - RFC 2831: DIGEST-MD5 authentication mechanism (obsoleted by RFC 6331)
* - RFC 2971: ID
* - RFC 3348: CHILDREN
* - RFC 3501: IMAP4rev1 specification
* - RFC 3502: MULTIAPPEND
* - RFC 3516: BINARY
* - RFC 3691: UNSELECT
* - RFC 4315: UIDPLUS
* - RFC 4422: SASL Authentication (for DIGEST-MD5)
* - RFC 4466: Collected extensions (updates RFCs 2088, 3501, 3502, 3516)
* - RFC 4469/5550: CATENATE
* - RFC 4551: CONDSTORE
* - RFC 4731: ESEARCH
* - RFC 4959: SASL-IR
* - RFC 5032: WITHIN
* - RFC 5161: ENABLE
* - RFC 5162: QRESYNC
* - RFC 5182: SEARCHRES
* - RFC 5255: LANGUAGE/I18NLEVEL
* - RFC 5256: THREAD/SORT
* - RFC 5258: LIST-EXTENDED
* - RFC 5267: ESORT; PARTIAL search return option
* - RFC 5464: METADATA
* - RFC 5530: IMAP Response Codes
* - RFC 5819: LIST-STATUS
* - RFC 5957: SORT=DISPLAY
* - RFC 6154: SPECIAL-USE/CREATE-SPECIAL-USE
* - RFC 6203: SEARCH=FUZZY
* - RFC 6851: MOVE
* - RFC 6858: DOWNGRADED response code
* </pre>
*
* Implements the following non-RFC extensions:
* <pre>
* - draft-ietf-morg-inthread-01: THREAD=REFS
* - draft-daboo-imap-annotatemore-07: ANNOTATEMORE
* - draft-daboo-imap-annotatemore-08: ANNOTATEMORE2
* - XIMAPPROXY
* Requires imapproxy v1.2.7-rc1 or later
* See https://squirrelmail.svn.sourceforge.net/svnroot/squirrelmail/trunk/imap_proxy/README
* - AUTH=XOAUTH2
* https://developers.google.com/gmail/xoauth2_protocol
* </pre>
*
* TODO (or not necessary?):
* <pre>
* - RFC 2177: IDLE
* Probably not necessary due to the limited connection time of each
* HTTP/PHP request
* - RFC 2193: MAILBOX-REFERRALS
* - RFC 4467/5092/5524/5550/5593: URLAUTH, URLAUTH=BINARY, URL-PARTIAL
* - RFC 4978: COMPRESS=DEFLATE
* See: http://bugs.php.net/bug.php?id=48725
* - RFC 5257: ANNOTATE (Experimental)
* - RFC 5259: CONVERT
* - RFC 5267: CONTEXT=SEARCH; CONTEXT=SORT
* - RFC 5465: NOTIFY
* - RFC 5466: FILTERS
* - RFC 6237: MULTISEARCH (Experimental)
* - RFC 6855: UTF8
* </pre>
*
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @copyright 1999-2007 The SquirrelMail Project Team
* @copyright 2005-2014 Horde LLC
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Imap_Client
*/
class Horde_Imap_Client_Socket extends Horde_Imap_Client_Base
{
/**
* Cache names used exclusively within this class.
*/
const CACHE_FLAGS = 'HICflags';
/**
* Queued commands to send to the server.
*
* @var array
*/
protected $_cmdQueue = array();
/**
* The default ports to use for a connection.
*
* @var array
*/
protected $_defaultPorts = array(143, 993);
/**
* Mapping of status fields to IMAP names.
*
* @var array
*/
protected $_statusFields = array(
'messages' => Horde_Imap_Client::STATUS_MESSAGES,
'recent' => Horde_Imap_Client::STATUS_RECENT,
'uidnext' => Horde_Imap_Client::STATUS_UIDNEXT,
'uidvalidity' => Horde_Imap_Client::STATUS_UIDVALIDITY,
'unseen' => Horde_Imap_Client::STATUS_UNSEEN,
'firstunseen' => Horde_Imap_Client::STATUS_FIRSTUNSEEN,
'flags' => Horde_Imap_Client::STATUS_FLAGS,
'permflags' => Horde_Imap_Client::STATUS_PERMFLAGS,
'uidnotsticky' => Horde_Imap_Client::STATUS_UIDNOTSTICKY,
'highestmodseq' => Horde_Imap_Client::STATUS_HIGHESTMODSEQ
);
/**
* The unique tag to use when making an IMAP query.
*
* @var integer
*/
protected $_tag = 0;
/**
* @param array $params A hash containing configuration parameters.
* Additional parameters to base driver:
* - debug_literal: (boolean) If true, will output the raw text of
* literal responses to the debug stream. Otherwise,
* outputs a summary of the literal response.
* - envelope_addrs: (integer) The maximum number of address entries to
* read for FETCH ENVELOPE address fields.
* DEFAULT: 1000
* - envelope_string: (integer) The maximum length of string fields
* returned by the FETCH ENVELOPE command.
* DEFAULT: 2048
* - xoauth2_token: (mixed) If set, will authenticate via the XOAUTH2
* mechanism (if available) with this token. Either a
* string (since 2.13.0) or a
* Horde_Imap_Client_Base_Password object (since
* 2.14.0).
*/
public function __construct(array $params = array())
{
parent::__construct(array_merge(array(
'debug_literal' => false,
'envelope_addrs' => 1000,
'envelope_string' => 2048
), $params));
}
/**
*/
public function getParam($key)
{
switch ($key) {
case 'xoauth2_token':
if (isset($this->_params[$key]) &&
($this->_params[$key] instanceof Horde_Imap_Client_Base_Password)) {
return $this->_params[$key]->getPassword();
}
break;
}
return parent::getParam($key);
}
/**
*/
protected function _capability()
{
// Need to use connect call here or else we run into loop issues
// because _connect() can call capability() internally.
$this->_connect();
// It is possible the server provided capability information on
// connect, so check for it now.
if (!isset($this->_init['capability'])) {
$this->_sendCmd($this->_command('CAPABILITY'));
}
}
/**
* Parse a CAPABILITY Response (RFC 3501 [7.2.1]).
*
* @param Horde_Imap_Client_Interaction_Pipeline $pipeline Pipeline
* object.
* @param array $data An array of CAPABILITY strings.
*/
protected function _parseCapability(
Horde_Imap_Client_Interaction_Pipeline $pipeline,
$data
)
{
if (!empty($this->_temp['no_cap'])) {
return;
}
$pipeline->data['capability_set'] = true;
$c = array();
foreach ($data as $val) {
$cap_list = explode('=', $val);
$cap_list[0] = strtoupper($cap_list[0]);
if (isset($cap_list[1])) {
if (!isset($c[$cap_list[0]]) || !is_array($c[$cap_list[0]])) {
$c[$cap_list[0]] = array();
}
$c[$cap_list[0]][] = $cap_list[1];
} elseif (!isset($c[$cap_list[0]])) {
$c[$cap_list[0]] = true;
}
}
$this->_setInit('capability', $c);
}
/**
* Unsets a capability.
*
* @param string $cap Capability to unset.
*/
protected function _unsetCapability($cap)
{
$cap_list = $this->capability();
unset($cap_list[$cap]);
$this->_setInit('capability', $cap_list);
}
/**
*/
protected function _noop()
{
// NOOP doesn't return any specific response
$this->_sendCmd($this->_command('NOOP'));
}
/**
*/
protected function _getNamespaces()
{
$data = $this->queryCapability('NAMESPACE')
? $this->_sendCmd($this->_command('NAMESPACE'))->data
: array();
return isset($data['namespace'])
? $data['namespace']
: array();
}
/**
* Parse a NAMESPACE response (RFC 2342 [5] & RFC 5255 [3.4]).
*
* @param Horde_Imap_Client_Interaction_Pipeline $pipeline Pipeline
* object.
* @param Horde_Imap_Client_Tokenize $data The NAMESPACE data.
*/
protected function _parseNamespace(
Horde_Imap_Client_Interaction_Pipeline $pipeline,
Horde_Imap_Client_Tokenize $data
)
{
$namespace_array = array(
Horde_Imap_Client::NS_PERSONAL,
Horde_Imap_Client::NS_OTHER,
Horde_Imap_Client::NS_SHARED
);
$c = array();
// Per RFC 2342, response from NAMESPACE command is:
// (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
foreach ($namespace_array as $val) {
$entry = $data->next();
if (is_null($entry)) {
continue;
}
while ($data->next() !== false) {
$ob = Horde_Imap_Client_Mailbox::get($data->next(), true);
$c[strval($ob)] = array(
'delimiter' => $data->next(),
'hidden' => false,
'name' => strval($ob),
'translation' => '',
'type' => $val
);
// RFC 4466: NAMESPACE extensions
while (($ext = $data->next()) !== false) {
switch (strtoupper($ext)) {
case 'TRANSLATION':
// RFC 5255 [3.4] - TRANSLATION extension
$data->next();
$c[strval($ob)]['translation'] = $data->next();
$data->next();
break;
}
}
}
}
$pipeline->data['namespace'] = $c;
}
/**
*/
public function alerts()
{
$alerts = empty($this->_temp['alerts'])
? array()
: $this->_temp['alerts'];
$this->_temp['alerts'] = array();
return $alerts;
}
/**
*/
protected function _login()
{
$secure = $this->getParam('secure');
if (!empty($this->_temp['preauth'])) {
unset($this->_temp['preauth']);
/* Don't allow PREAUTH if we are requring secure access, since
* PREAUTH cannot provide secure access. */
if (!$this->isSecureConnection() && ($secure !== false)) {
$this->logout();
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Could not open secure TLS connection to the IMAP server."),
Horde_Imap_Client_Exception::LOGIN_TLSFAILURE
);
}
return $this->_loginTasks();
}
/* Blank passwords are not allowed, so no need to even try
* authentication to determine this. */
if (is_null($this->getParam('password'))) {
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("No password provided."),
Horde_Imap_Client_Exception::LOGIN_AUTHENTICATIONFAILED
);
}
$this->_connect();
$first_login = empty($this->_init['authmethod']);
// Switch to secure channel if using TLS.
if (!$this->isSecureConnection() &&
(($secure === 'tls') ||
(($secure === true) && $this->queryCapability('LOGINDISABLED')))) {
if ($first_login && !$this->queryCapability('STARTTLS')) {
/* We should never hit this - STARTTLS is required pursuant to
* RFC 3501 [6.2.1]. */
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Server does not support TLS connections."),
Horde_Imap_Client_Exception::LOGIN_TLSFAILURE
);
}
// Switch over to a TLS connection.
// STARTTLS returns no untagged response.
$this->_sendCmd($this->_command('STARTTLS'));
if (!$this->_connection->startTls()) {
$this->logout();
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Could not open secure TLS connection to the IMAP server."),
Horde_Imap_Client_Exception::LOGIN_TLSFAILURE
);
}
$this->_debug->info('Successfully completed TLS negotiation.');
$this->setParam('secure', 'tls');
$secure = 'tls';
if ($first_login) {
// Expire cached CAPABILITY information (RFC 3501 [6.2.1])
$this->_setInit('capability');
// Reset language (RFC 5255 [3.1])
$this->_setInit('lang');
}
// Set language if using imapproxy
if (!empty($this->_init['imapproxy'])) {
$this->setLanguage();
}
}
/* If we reached this point and don't have a secure connection, then
* a secure connections is not available. */
if (($secure === true) && !$this->isSecureConnection()) {
$this->setParam('secure', false);
$secure = false;
}
if ($first_login) {
// Add authentication methods.
$auth_mech = array();
$auth = ($auth = $this->queryCapability('AUTH'))
? array_flip($auth)
: array();
// XOAUTH2
if (isset($auth['XOAUTH2']) && $this->getParam('xoauth2_token')) {
$auth_mech[] = 'XOAUTH2';
}
unset($auth['XOAUTH2']);
/* 'PLAIN' authentication always exists if under TLS (RFC
* 3501 [7.2.1]; RFC 2595). Use it over all other authentication
* methods, although we need to do sanity checking since broken
* IMAP servers may not support as required - fallback to
* LOGIN instead. */
if ($secure) {
if (isset($auth['PLAIN'])) {
$auth_mech[] = 'PLAIN';
unset($auth['PLAIN']);
} else {
$auth_mech[] = 'LOGIN';
}
}
// Prefer CRAM-MD5 over DIGEST-MD5, as the latter has been
// obsoleted (RFC 6331).
if (isset($auth['CRAM-MD5'])) {
$auth_mech[] = 'CRAM-MD5';
} elseif (isset($auth['DIGEST-MD5'])) {
$auth_mech[] = 'DIGEST-MD5';
}
unset($auth['CRAM-MD5'], $auth['DIGEST-MD5']);
// Fall back to 'LOGIN' if available.
$auth_mech = array_merge($auth_mech, array_keys($auth));
if (!$secure && !$this->queryCapability('LOGINDISABLED')) {
$auth_mech[] = 'LOGIN';
}
if (empty($auth_mech)) {
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("No supported IMAP authentication method could be found."),
Horde_Imap_Client_Exception::LOGIN_NOAUTHMETHOD
);
}
} else {
$auth_mech = array($this->_init['authmethod']);
}
$login_err = null;
foreach ($auth_mech as $method) {
try {
$resp = $this->_tryLogin($method);
$data = $resp->data;
$this->_setInit('authmethod', $method);
unset($this->_temp['referralcount']);
} catch (Horde_Imap_Client_Exception_ServerResponse $e) {
$data = $e->resp_data;
if (isset($data['loginerr'])) {
$login_err = $data['loginerr'];
}
$resp = false;
} catch (Horde_Imap_Client_Exception $e) {
$resp = false;
}
// Check for login referral (RFC 2221) response - can happen for
// an OK, NO, or BYE response.
if (isset($data['referral'])) {
foreach (array('hostspec', 'port', 'username') as $val) {
if (!is_null($data['referral']->$val)) {
$this->setParam($val, $data['referral']->$val);
}
}
if (!is_null($data['referral']->auth)) {
$this->_setInit('authmethod', $data['referral']->auth);
}
if (!isset($this->_temp['referralcount'])) {
$this->_temp['referralcount'] = 0;
}
// RFC 2221 [3] - Don't follow more than 10 levels of referral
// without consulting the user.
if (++$this->_temp['referralcount'] < 10) {
$this->logout();
$this->_setInit('capability');
$this->_setInit('namespace', array());
return $this->login();
}
unset($this->_temp['referralcount']);
}
if ($resp) {
return $this->_loginTasks($first_login, $resp->data);
}
}
/* Try again from scratch if authentication failed in an established,
* previously-authenticated object. */
if (!empty($this->_init['authmethod'])) {
$this->_setInit();
unset($this->_temp['no_cap']);
try {
return $this->_login();
} catch (Horde_Imap_Client_Exception $e) {}
}
/* Default to AUTHENTICATIONFAILED error (see RFC 5530[3]). */
if (is_null($login_err)) {
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Mail server denied authentication."),
Horde_Imap_Client_Exception::LOGIN_AUTHENTICATIONFAILED
);
}
throw $login_err;
}
/**
* Connects to the IMAP server.
*
* @throws Horde_Imap_Client_Exception
*/
protected function _connect()
{
if (!is_null($this->_connection)) {
return;
}
try {
$this->_connection = new Horde_Imap_Client_Socket_Connection_Socket(
$this->getParam('hostspec'),
$this->getParam('port'),
$this->getParam('timeout'),
$this->getParam('secure'),
array(
'debug' => $this->_debug,
'debugliteral' => $this->getParam('debug_literal')
)
);
} catch (Horde\Socket\Client\Exception $e) {
$e2 = new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Error connecting to mail server."),
Horde_Imap_Client_Exception::SERVER_CONNECT
);
$e2->details = $e->details;
throw $e2;
}
// If we already have capability information, don't re-set with
// (possibly) limited information sent in the initial banner.
if (isset($this->_init['capability'])) {
$this->_temp['no_cap'] = true;
}
/* Get greeting information (untagged response). */
try {
$this->_getLine($this->_pipeline());
} catch (Horde_Imap_Client_Exception_ServerResponse $e) {
if ($e->status === Horde_Imap_Client_Interaction_Server::BYE) {
/* Server is explicitly rejecting our connection (RFC 3501
* [7.1.5]). */
$e->setMessage(Horde_Imap_Client_Translation::r("Server rejected connection."));
$e->setCode(Horde_Imap_Client_Exception::SERVER_CONNECT);
}
throw $e;
}
// Check for IMAP4rev1 support
if (!$this->queryCapability('IMAP4REV1')) {
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("The mail server does not support IMAP4rev1 (RFC 3501)."),
Horde_Imap_Client_Exception::SERVER_CONNECT
);
}
// Set language if NOT using imapproxy
if (empty($this->_init['imapproxy'])) {
if ($this->queryCapability('XIMAPPROXY')) {
$this->_setInit('imapproxy', true);
} else {
$this->setLanguage();
}
}
// If pre-authenticated, we need to do all login tasks now.
if (!empty($this->_temp['preauth'])) {
$this->login();
}
}
/**
* Authenticate to the IMAP server.
*
* @param string $method IMAP login method.
*
* @return Horde_Imap_Client_Interaction_Pipeline Pipeline object.
*
* @throws Horde_Imap_Client_Exception
*/
protected function _tryLogin($method)
{
$username = $this->getParam('username');
$password = $this->getParam('password');
$authenticate_cmd = false;
switch ($method) {
case 'CRAM-MD5':
case 'CRAM-SHA1':
case 'CRAM-SHA256':
// RFC 2195: CRAM-MD5
// CRAM-SHA1 & CRAM-SHA256 supported by Courier SASL library
// Need $args because PHP 5.3 doesn't allow access to $this in
// anonymous functions.
$args = array(
$username,
strtolower(substr($method, 5)),
$password
);
$cmd = $this->_command('AUTHENTICATE')->add(array(
$method,
new Horde_Imap_Client_Interaction_Command_Continuation(function($ob) use ($args) {
return new Horde_Imap_Client_Data_Format_List(
base64_encode($args[0] . ' ' . hash_hmac($args[1], base64_decode($ob->token->current()), $args[2], false))
);
})
));
$cmd->debug = sprintf('[AUTHENTICATE %s Command - username: %s]', $method, $username);
break;
case 'DIGEST-MD5':
// RFC 2831/4422; obsoleted by RFC 6331
// Need $args because PHP 5.3 doesn't allow access to $this in
// anonymous functions.
$args = array(
$username,
$password,
$this->getParam('hostspec')
);
$cmd = $this->_command('AUTHENTICATE')->add(array(
$method,
new Horde_Imap_Client_Interaction_Command_Continuation(function($ob) use ($args) {
return new Horde_Imap_Client_Data_Format_List(
base64_encode(new Horde_Imap_Client_Auth_DigestMD5(
$args[0],
$args[1],
base64_decode($ob->token->current()),
$args[2],
'imap'
))
);
}),
new Horde_Imap_Client_Interaction_Command_Continuation(function($ob) {
if (strpos(base64_decode($ob->token->current()), 'rspauth=') === false) {
throw new Horde_Imap_Client_Exception(
Horde_Imap_Client_Translation::r("Unexpected response from server when authenticating."),
Horde_Imap_Client_Exception::SERVER_CONNECT
);
}
return new Horde_Imap_Client_Data_Format_List();
})
));
$cmd->debug = sprintf('[AUTHENTICATE DIGEST-MD5 Command - username: %s]', $username);
break;
case 'LOGIN':
$cmd = $this->_command('LOGIN')->add(array(
new Horde_Imap_Client_Data_Format_Astring($username),
new Horde_Imap_Client_Data_Format_Astring($password)
));
$cmd->debug = sprintf('[LOGIN Command - username: %s]', $username);
break;
case 'PLAIN':
// RFC 2595/4616 - PLAIN SASL mechanism
$auth = base64_encode(implode("\0", array(
$username,
$username,
$password
)));
$authenticate_cmd = true;
break;
case 'XOAUTH2':
// Google XOAUTH2
$auth = $this->getParam('xoauth2_token');
$authenticate_cmd = true;
break;
default:
throw new Horde_Imap_Client_Exception(
sprintf(Horde_Imap_Client_Translation::r("Unknown authentication method: %s"), $method),
Horde_Imap_Client_Exception::SERVER_CONNECT
);
}
if ($authenticate_cmd) {
$cmd = $this->_command('AUTHENTICATE')->add($method);
if ($this->queryCapability('SASL-IR')) {
// IMAP Extension for SASL Initial Client Response (RFC 4959)
$cmd->add($auth);
$cmd->debug = sprintf('[SASL-IR AUTHENTICATE Command - method: %s, username: %s]', $method, $username);
} else {
$cmd->add(new Horde_Imap_Client_Interaction_Command_Continuation(function($ob) use ($auth) {
return new Horde_Imap_Client_Data_Format_List($auth);
}));
$cmd->debug = sprintf('[AUTHENTICATE Command - method: %s, username: %s]', $method, $username);
}
/* This is an optional command continuation. E.g. XOAUTH2 will
* return error information in continuation response. */
$error_continuation = new Horde_Imap_Client_Interaction_Command_Continuation(function($ob) {
return new Horde_Imap_Client_Data_Format_List();
});
$error_continuation->optional = true;
$cmd->add($error_continuation);
}
return $this->_sendCmd($this->_pipeline($cmd));
}
/**
* Perform login tasks.
*
* @param boolean $firstlogin Is this the first login?
* @param array $resp The data response from the login command.
* May include:
* - capability_set: (boolean) True if CAPABILITY was set after login.
* - proxyreuse: (boolean) True if re-used connection via imapproxy.
*
* @return boolean True if global login tasks should be performed.
*/
protected function _loginTasks($firstlogin = true, array $resp = array())
{
/* If reusing an imapproxy connection, no need to do any of these
* login tasks again. */
if (!$firstlogin && !empty($resp['proxyreuse'])) {
if (isset($this->_init['enabled'])) {
$this->_temp['enabled'] = $this->_init['enabled'];
}
// If we have not yet set the language, set it now.
if (!isset($this->_init['lang'])) {
$this->_temp['lang_queue'] = true;
$this->setLanguage();
unset($this->_temp['lang_queue']);
}
return false;
}
/* If we logged in for first time, and server did not return
* capability information, we need to mark for retrieval. */
if ($firstlogin && empty($resp['capability_set'])) {
$this->_setInit('capability');
}
$this->_temp['lang_queue'] = true;
$this->setLanguage();
unset($this->_temp['lang_queue']);
/* Only active QRESYNC/CONDSTORE if caching is enabled. */
if ($this->_initCache()) {
if ($this->queryCapability('QRESYNC')) {
$this->_enable(array('QRESYNC'));
} elseif ($this->queryCapability('CONDSTORE')) {
$this->_enable(array('CONDSTORE'));
}
}
return true;
}
/**
*/
protected function _logout()
{
if (empty($this->_temp['logout'])) {
/* If using imapproxy, force sending these commands, since they
* may not be sent again if they are (likely) initialization
* commands. */
if (!empty($this->_cmdQueue) &&
!empty($this->_init['imapproxy'])) {
$this->_sendCmd($this->_pipeline());
}
$this->_temp['logout'] = true;
try {
$this->_sendCmd($this->_command('LOGOUT'));
} catch (Horde_Imap_Client_Exception_ServerResponse $e) {
// Ignore server errors
}
unset($this->_temp['logout']);
}
}
/**
*/
protected function _sendID($info)
{
$cmd = $this->_command('ID');
if (empty($info)) {
$cmd->add(new Horde_Imap_Client_Data_Format_Nil());
} else {
$tmp = new Horde_Imap_Client_Data_Format_List();
foreach ($info as $key => $val) {
$tmp->add(array(
new Horde_Imap_Client_Data_Format_String(strtolower($key)),
new Horde_Imap_Client_Data_Format_Nstring($val)
));
}
$cmd->add($tmp);
}
$this->_temp['id'] = $this->_sendCmd($cmd)->data['id'];
}
/**
* Parse an ID response (RFC 2971 [3.2]).
*
* @param Horde_Imap_Client_Interaction_Pipeline $pipeline Pipeline
* object.
* @param Horde_Imap_Client_Tokenize $data The server response.
*/
protected function _parseID(
Horde_Imap_Client_Interaction_Pipeline $pipeline,
Horde_Imap_Client_Tokenize $data
)
{
$ids = array();
if (!is_null($data->next())) {
while (($curr = $data->next()) !== false) {
if (!is_null($id = $data->next())) {
$ids[$curr] = $id;
}
}
}
$pipeline->data['id'] = $ids;
}
/**
*/
protected function _getID()
{
if (!isset($this->_temp['id'])) {
$this->sendID();
}
return $this->_temp['id'];
}
/**
*/
protected function _setLanguage($langs)
{
$cmd = $this->_command('LANGUAGE');
foreach ($langs as $lang) {
$cmd->add(new Horde_Imap_Client_Data_Format_Astring($lang));
}
if (!empty($this->_temp['lang_queue'])) {
$this->_cmdQueue[] = $cmd;
return array();
}
try {
$this->_sendCmd($cmd);
} catch (Horde_Imap_Client_Exception $e) {
$this->_setInit('lang', false);
return null;
}
return $this->_init['lang'];
}
/**
*/
protected function _getLanguage($list)
{
if (!$list) {
return empty($this->_init['lang'])
? null
: $this->_init['lang'];
}
if (!isset($this->_init['langavail'])) {
try {
$this->_sendCmd($this->_command('LANGUAGE'));
} catch (Horde_Imap_Client_Exception $e) {
$this->_setInit('langavail', array());
}
}
return $this->_init['langavail'];
}
/**
* Parse a LANGUAGE response (RFC 5255 [3.3]).
*
* @param Horde_Imap_Client_Tokenize $data The server response.
*/
protected function _parseLanguage(Horde_Imap_Client_Tokenize $data)
{
$lang_list = $data->flushIterator();
if (count($lang_list) === 1) {
// This is the language that was set.
$this->_setInit('lang', reset($lang_list));
} else {
// These are the languages that are available.
$this->_setInit('langavail', $lang_list);
}
}
/**
* Enable an IMAP extension (see RFC 5161).
*
* @param array $exts The extensions to enable.
*
* @throws Horde_Imap_Client_Exception
*/
protected function _enable($exts)
{
if ($this->queryCapability('ENABLE')) {
// Only enable non-enabled extensions.
$exts = array_diff($exts, array_keys($this->_temp['enabled']));
if (!empty($exts)) {
$this->_cmdQueue[] = $this->_command('ENABLE')->add($exts);
$this->_enabled($exts, 1);
}
}
}
/**
* Parse an ENABLED response (RFC 5161 [3.2]).
*
* @param Horde_Imap_Client_Tokenize $data The server response.
*/
protected function _parseEnabled(Horde_Imap_Client_Tokenize $data)
{
$this->_enabled($data->flushIterator(), 2);
}
/**
*/
protected function _enabled($exts, $status)
{
parent::_enabled($exts, $status);
if (($status == 2) && !empty($this->_init['imapproxy'])) {
$this->_setInit('enabled', $this->_temp['enabled']);
}