forked from Webklex/php-imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImapProtocol.php
1378 lines (1248 loc) · 44.9 KB
/
ImapProtocol.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
/*
* File: ImapProtocol.php
* Category: Protocol
* Author: M.Goldenbaum
* Created: 16.09.20 18:27
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PHPIMAP\Connection\Protocols;
use Exception;
use Throwable;
use Webklex\PHPIMAP\Config;
use Webklex\PHPIMAP\Exceptions\AuthFailedException;
use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
use Webklex\PHPIMAP\Exceptions\ImapBadRequestException;
use Webklex\PHPIMAP\Exceptions\ImapServerErrorException;
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
use Webklex\PHPIMAP\Exceptions\ResponseException;
use Webklex\PHPIMAP\Exceptions\RuntimeException;
use Webklex\PHPIMAP\Header;
use Webklex\PHPIMAP\IMAP;
/**
* Class ImapProtocol
*
* @package Webklex\PHPIMAP\Connection\Protocols
*
* @reference https://www.rfc-editor.org/rfc/rfc2087.txt
*/
class ImapProtocol extends Protocol {
/**
* Request noun
* @var int
*/
protected int $noun = 0;
/**
* Imap constructor.
* @param Config $config
* @param bool $cert_validation set to false to skip SSL certificate validation
* @param mixed $encryption Connection encryption method
*/
public function __construct(Config $config, bool $cert_validation = true, mixed $encryption = false) {
$this->config = $config;
$this->setCertValidation($cert_validation);
$this->encryption = $encryption;
}
/**
* Handle the class destruction / tear down
*/
public function __destruct() {
$this->logout();
}
/**
* Open connection to IMAP server
* @param string $host hostname or IP address of IMAP server
* @param int|null $port of IMAP server, default is 143 and 993 for ssl
*
* @throws ConnectionFailedException
*/
public function connect(string $host, ?int $port = null): bool {
$transport = 'tcp';
$encryption = '';
if ($this->encryption) {
$encryption = strtolower($this->encryption);
if (in_array($encryption, ['ssl', 'tls'])) {
$transport = $encryption;
$port = $port === null ? 993 : $port;
}
}
$port = $port === null ? 143 : $port;
try {
$response = new Response(0, $this->debug);
$this->stream = $this->createStream($transport, $host, $port, $this->connection_timeout);
if (!$this->stream || !$this->assumedNextLine($response, '* OK')) {
throw new ConnectionFailedException('connection refused');
}
if ($encryption == 'starttls') {
$this->enableStartTls();
}
} catch (Exception $e) {
throw new ConnectionFailedException('connection failed', 0, $e);
}
return true;
}
/**
* Check if the current session is connected
*
* @return bool
* @throws ImapBadRequestException
*/
public function connected(): bool {
if ((bool)$this->stream) {
try {
$this->requestAndResponse('NOOP');
return true;
} catch (ImapServerErrorException|RuntimeException) {
return false;
}
}
return false;
}
/**
* Enable tls on the current connection
*
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
protected function enableStartTls(): void {
$response = $this->requestAndResponse('STARTTLS');
$result = $response->successful() && stream_socket_enable_crypto($this->stream, true, $this->getCryptoMethod());
if (!$result) {
throw new ConnectionFailedException('failed to enable TLS');
}
}
/**
* Get the next line from stream
*
* @return string next line
* @throws RuntimeException
*/
public function nextLine(Response $response): string {
$line = "";
while (($next_char = fread($this->stream, 1)) !== false && !in_array($next_char, ["", "\n"])) {
$line .= $next_char;
}
if ($line === "" && ($next_char === false || $next_char === "")) {
throw new RuntimeException('empty response');
}
$line .= "\n";
$response->addResponse($line);
if ($this->debug) echo "<< " . $line;
return $line;
}
/**
* Get the next line and check if it starts with a given string
* @param Response $response
* @param string $start
*
* @return bool
* @throws RuntimeException
*/
protected function assumedNextLine(Response $response, string $start): bool {
return str_starts_with($this->nextLine($response), $start);
}
/**
* Get the next line and split the tag
* @param string|null $tag reference tag
*
* @return string next line
* @throws RuntimeException
*/
protected function nextTaggedLine(Response $response, ?string &$tag): string {
$line = $this->nextLine($response);
if (str_contains($line, ' ')) {
list($tag, $line) = explode(' ', $line, 2);
}
return $line ?? '';
}
/**
* Get the next line and check if it contains a given string and split the tag
* @param Response $response
* @param string $start
* @param $tag
*
* @return bool
* @throws RuntimeException
*/
protected function assumedNextTaggedLine(Response $response, string $start, &$tag): bool {
return str_contains($this->nextTaggedLine($response, $tag), $start);
}
/**
* Split a given line in values. A value is literal of any form or a list
* @param Response $response
* @param string $line
*
* @return array
* @throws RuntimeException
*/
protected function decodeLine(Response $response, string $line): array {
$tokens = [];
$stack = [];
// replace any trailing <NL> including spaces with a single space
$line = rtrim($line) . ' ';
while (($pos = strpos($line, ' ')) !== false) {
$token = substr($line, 0, $pos);
if (!strlen($token)) {
$line = substr($line, $pos + 1);
continue;
}
while ($token[0] == '(') {
$stack[] = $tokens;
$tokens = [];
$token = substr($token, 1);
}
if ($token[0] == '"') {
if (preg_match('%^\(*\"((.|\\\|\")*?)\"( |$)%', $line, $matches)) {
$tokens[] = $matches[1];
$line = substr($line, strlen($matches[0]));
continue;
}
}
if ($token[0] == '{') {
$endPos = strpos($token, '}');
$chars = substr($token, 1, $endPos - 1);
if (is_numeric($chars)) {
$token = '';
while (strlen($token) < $chars) {
$token .= $this->nextLine($response);
}
$line = '';
if (strlen($token) > $chars) {
$line = substr($token, $chars);
$token = substr($token, 0, $chars);
} else {
$line .= $this->nextLine($response);
}
$tokens[] = $token;
$line = trim($line) . ' ';
continue;
}
}
if ($stack && $token[strlen($token) - 1] == ')') {
// closing braces are not separated by spaces, so we need to count them
$braces = strlen($token);
$token = rtrim($token, ')');
// only count braces if more than one
$braces -= strlen($token) + 1;
// only add if token had more than just closing braces
if (rtrim($token) != '') {
$tokens[] = rtrim($token);
}
$token = $tokens;
$tokens = array_pop($stack);
// special handling if more than one closing brace
while ($braces-- > 0) {
$tokens[] = $token;
$token = $tokens;
$tokens = array_pop($stack);
}
}
$tokens[] = $token;
$line = substr($line, $pos + 1);
}
// maybe the server forgot to send some closing braces
while ($stack) {
$child = $tokens;
$tokens = array_pop($stack);
$tokens[] = $child;
}
return $tokens;
}
/**
* Read abd decode a response "line"
* @param Response $response
* @param array|string $tokens to decode
* @param string $wantedTag targeted tag
* @param bool $dontParse if true only the unparsed line is returned in $tokens
*
* @return bool
* @throws RuntimeException
*/
public function readLine(Response $response, array|string &$tokens = [], string $wantedTag = '*', bool $dontParse = false): bool {
$line = $this->nextTaggedLine($response, $tag); // get next tag
if (!$dontParse) {
$tokens = $this->decodeLine($response, $line);
} else {
$tokens = $line;
}
// if tag is wanted tag we might be at the end of a multiline response
return $tag == $wantedTag;
}
/**
* Read all lines of response until given tag is found
* @param Response $response
* @param string $tag request tag
* @param bool $dontParse if true every line is returned unparsed instead of the decoded tokens
*
* @return array
*
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
public function readResponse(Response $response, string $tag, bool $dontParse = false): array {
$lines = [];
$tokens = ""; // define $tokens variable before first use
do {
$readAll = $this->readLine($response, $tokens, $tag, $dontParse);
$lines[] = $tokens;
} while (!$readAll);
$original = $tokens;
if ($dontParse) {
// First two chars are still needed for the response code
$tokens = [trim(substr($tokens, 0, 3))];
}
$original = is_array($original) ? $original : [$original];
// last line has response code
if ($tokens[0] == 'OK') {
return $lines ?: [true];
} elseif ($tokens[0] == 'NO' || $tokens[0] == 'BAD' || $tokens[0] == 'BYE') {
throw new ImapServerErrorException($this->stringifyArray($original));
}
throw new ImapBadRequestException($this->stringifyArray($original));
}
/**
* Convert an array to a string
* @param array $arr array to stringify
*
* @return string stringified array
*/
private function stringifyArray(array $arr): string {
$string = "";
foreach ($arr as $value) {
if (is_array($value)) {
$string .= "(" . $this->stringifyArray($value) . ")";
} else {
$string .= $value . " ";
}
}
return $string;
}
/**
* Send a new request
* @param string $command
* @param array $tokens additional parameters to command, use escapeString() to prepare
* @param string|null $tag provide a tag otherwise an autogenerated is returned
*
* @return Response
* @throws RuntimeException
*/
public function sendRequest(string $command, array $tokens = [], ?string &$tag = null): Response {
if (!$tag) {
$this->noun++;
$tag = 'TAG' . $this->noun;
}
$line = $tag . ' ' . $command;
$response = new Response($this->noun, $this->debug);
foreach ($tokens as $token) {
if (is_array($token)) {
$this->write($response, $line . ' ' . $token[0]);
if (!$this->assumedNextLine($response, '+ ')) {
throw new RuntimeException('failed to send literal string');
}
$line = $token[1];
} else {
$line .= ' ' . $token;
}
}
$this->write($response, $line);
return $response;
}
/**
* Write data to the current stream
* @param Response $response
* @param string $data
*
* @return void
* @throws RuntimeException
*/
public function write(Response $response, string $data): void {
$command = $data . "\r\n";
if ($this->debug) echo ">> " . $command . "\n";
$response->addCommand($command);
if (fwrite($this->stream, $command) === false) {
throw new RuntimeException('failed to write - connection closed?');
}
}
/**
* Send a request and get response at once
*
* @param string $command
* @param array $tokens parameters as in sendRequest()
* @param bool $dontParse if true unparsed lines are returned instead of tokens
*
* @return Response response as in readResponse()
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
public function requestAndResponse(string $command, array $tokens = [], bool $dontParse = false): Response {
$response = $this->sendRequest($command, $tokens, $tag);
$response->setResult($this->readResponse($response, $tag, $dontParse));
return $response;
}
/**
* Escape one or more literals i.e. for sendRequest
* @param array|string $string the literal/-s
*
* @return string|array escape literals, literals with newline ar returned
* as array('{size}', 'string');
*/
public function escapeString(array|string $string): array|string {
if (func_num_args() < 2) {
if (str_contains($string, "\n")) {
return ['{' . strlen($string) . '}', $string];
} else {
return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $string) . '"';
}
}
$result = [];
foreach (func_get_args() as $string) {
$result[] = $this->escapeString($string);
}
return $result;
}
/**
* Escape a list with literals or lists
* @param array $list list with literals or lists as PHP array
*
* @return string escaped list for imap
*/
public function escapeList(array $list): string {
$result = [];
foreach ($list as $v) {
if (!is_array($v)) {
$result[] = $v;
continue;
}
$result[] = $this->escapeList($v);
}
return '(' . implode(' ', $result) . ')';
}
/**
* Login to a new session.
*
* @param string $user username
* @param string $password password
*
* @return Response
* @throws AuthFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
*/
public function login(string $user, string $password): Response {
try {
$command = 'LOGIN';
$params = $this->escapeString($user, $password);
return $this->requestAndResponse($command, $params, true);
} catch (RuntimeException $e) {
throw new AuthFailedException("failed to authenticate", 0, $e);
}
}
/**
* Authenticate your current IMAP session.
* @param string $user username
* @param string $token access token
*
* @return Response
* @throws AuthFailedException
*/
public function authenticate(string $user, string $token): Response {
try {
$authenticateParams = ['XOAUTH2', base64_encode("user=$user\1auth=Bearer $token\1\1")];
$response = $this->sendRequest('AUTHENTICATE', $authenticateParams);
while (true) {
$tokens = "";
$is_plus = $this->readLine($response, $tokens, '+', true);
if ($is_plus) {
// try to log the challenge somewhere where it can be found
error_log("got an extra server challenge: $tokens");
// respond with an empty response.
$response->stack($this->sendRequest(''));
} else {
if (preg_match('/^NO /i', $tokens) ||
preg_match('/^BAD /i', $tokens)) {
error_log("got failure response: $tokens");
return $response->addError("got failure response: $tokens");
} else if (preg_match("/^OK /i", $tokens)) {
return $response->setResult(is_array($tokens) ? $tokens : [$tokens]);
}
}
}
} catch (RuntimeException $e) {
throw new AuthFailedException("failed to authenticate", 0, $e);
}
}
/**
* Logout of imap server
*
* @return Response
*/
public function logout(): Response {
if (!$this->stream) {
$this->reset();
return new Response(0, $this->debug);
} elseif ($this->meta()["timed_out"]) {
$this->reset();
return new Response(0, $this->debug);
}
$result = null;
try {
$result = $this->requestAndResponse('LOGOUT', [], true);
fclose($this->stream);
} catch (Throwable) {
}
$this->reset();
return $result ?? new Response(0, $this->debug);
}
/**
* Reset the current stream and uid cache
*
* @return void
*/
public function reset(): void {
$this->stream = null;
$this->uid_cache = [];
}
/**
* Get an array of available capabilities
*
* @return Response list of capabilities
*
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws ResponseException
*/
public function getCapabilities(): Response {
$response = $this->requestAndResponse('CAPABILITY');
if (!$response->getResponse()) return $response;
return $response->setResult($response->validatedData()[0]);
}
/**
* Examine and select have the same response.
* @param string $command can be 'EXAMINE' or 'SELECT'
* @param string $folder target folder
*
* @return Response
* @throws RuntimeException
*/
public function examineOrSelect(string $command = 'EXAMINE', string $folder = 'INBOX'): Response {
$response = $this->sendRequest($command, [$this->escapeString($folder)], $tag);
$result = [];
$tokens = []; // define $tokens variable before first use
while (!$this->readLine($response, $tokens, $tag)) {
if ($tokens[0] == 'FLAGS') {
array_shift($tokens);
$result['flags'] = $tokens;
continue;
}
switch ($tokens[1]) {
case 'EXISTS':
case 'RECENT':
$result[strtolower($tokens[1])] = (int)$tokens[0];
break;
case '[UIDVALIDITY':
$result['uidvalidity'] = (int)$tokens[2];
break;
case '[UIDNEXT':
$result['uidnext'] = (int)$tokens[2];
break;
case '[UNSEEN':
$result['unseen'] = (int)$tokens[2];
break;
case '[NONEXISTENT]':
throw new RuntimeException("folder doesn't exist");
default:
// ignore
break;
}
}
$response->setResult($result);
if ($tokens[0] != 'OK') {
$response->addError("request failed");
}
return $response;
}
/**
* Change the current folder
* @param string $folder change to this folder
*
* @return Response see examineOrSelect()
* @throws RuntimeException
*/
public function selectFolder(string $folder = 'INBOX'): Response {
$this->uid_cache = [];
return $this->examineOrSelect('SELECT', $folder);
}
/**
* Examine a given folder
* @param string $folder examine this folder
*
* @return Response see examineOrSelect()
* @throws RuntimeException
*/
public function examineFolder(string $folder = 'INBOX'): Response {
return $this->examineOrSelect('EXAMINE', $folder);
}
/**
* Get the status of a given folder
*
* @param string $folder
* @param string[] $arguments
* @return Response list of STATUS items
*
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws ResponseException
* @throws RuntimeException
*/
public function folderStatus(string $folder = 'INBOX', $arguments = ['MESSAGES', 'UNSEEN', 'RECENT', 'UIDNEXT', 'UIDVALIDITY']): Response {
$response = $this->requestAndResponse('STATUS', [$this->escapeString($folder), $this->escapeList($arguments)]);
$data = $response->validatedData();
if (!isset($data[0]) || !isset($data[0][2])) {
throw new RuntimeException("folder status could not be fetched");
}
$result = [];
$key = null;
foreach ($data[0][2] as $value) {
if ($key === null) {
$key = $value;
} else {
$result[strtolower($key)] = (int)$value;
$key = null;
}
}
$response->setResult($result);
return $response;
}
/**
* Fetch one or more items of one or more messages
* @param array|string $items items to fetch [RFC822.HEADER, FLAGS, RFC822.TEXT, etc]
* @param array|int $from message for items or start message if $to !== null
* @param int|null $to if null only one message ($from) is fetched, else it's the
* last message, INF means last message available
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
*
* @return Response if only one item of one message is fetched it's returned as string
* if items of one message are fetched it's returned as (name => value)
* if one item of messages are fetched it's returned as (msgno => value)
* if items of messages are fetched it's returned as (msgno => (name => value))
* @throws RuntimeException
*/
public function fetch(array|string $items, array|int $from, mixed $to = null, int|string $uid = IMAP::ST_UID): Response {
if (is_array($from)) {
$set = implode(',', $from);
} elseif ($to === null) {
$set = $from;
} elseif ($to == INF) {
$set = $from . ':*';
} else {
$set = $from . ':' . (int)$to;
}
$items = (array)$items;
$itemList = $this->escapeList($items);
$response = $this->sendRequest($this->buildUIDCommand("FETCH", $uid), [$set, $itemList], $tag);
$result = [];
$tokens = []; // define $tokens variable before first use
while (!$this->readLine($response, $tokens, $tag)) {
// ignore other responses
if ($tokens[1] != 'FETCH') {
continue;
}
$uidKey = 0;
$data = [];
// find array key of UID value; try the last elements, or search for it
if ($uid === IMAP::ST_UID) {
$count = count($tokens[2]);
if ($tokens[2][$count - 2] == 'UID') {
$uidKey = $count - 1;
} else if ($tokens[2][0] == 'UID') {
$uidKey = 1;
} else {
$found = array_search('UID', $tokens[2]);
if ($found === false || $found === -1) {
continue;
}
$uidKey = $found + 1;
}
}
// ignore other messages
if ($to === null && !is_array($from) && ($uid === IMAP::ST_UID ? $tokens[2][$uidKey] != $from : $tokens[0] != $from)) {
continue;
}
// if we only want one item we return that one directly
if (count($items) == 1) {
if ($tokens[2][0] == $items[0]) {
$data = $tokens[2][1];
} elseif ($uid === IMAP::ST_UID && $tokens[2][2] == $items[0]) {
$data = $tokens[2][3];
} else {
$expectedResponse = 0;
// maybe the server send another field we didn't wanted
$count = count($tokens[2]);
// we start with 2, because 0 was already checked
for ($i = 2; $i < $count; $i += 2) {
if ($tokens[2][$i] != $items[0]) {
continue;
}
$data = $tokens[2][$i + 1];
$expectedResponse = 1;
break;
}
if (!$expectedResponse) {
continue;
}
}
} else {
while (key($tokens[2]) !== null) {
$data[current($tokens[2])] = next($tokens[2]);
next($tokens[2]);
}
}
// if we want only one message we can ignore everything else and just return
if ($to === null && !is_array($from) && ($uid === IMAP::ST_UID ? $tokens[2][$uidKey] == $from : $tokens[0] == $from)) {
// we still need to read all lines
if (!$this->readLine($response, $tokens, $tag))
return $response->setResult($data);
}
if ($uid === IMAP::ST_UID) {
$result[$tokens[2][$uidKey]] = $data;
} else {
$result[$tokens[0]] = $data;
}
}
if ($to === null && !is_array($from)) {
throw new RuntimeException('the single id was not found in response');
}
return $response->setResult($result);
}
/**
* Fetch message body (without headers)
* @param int|array $uids
* @param string $rfc
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
*
* @return Response
* @throws RuntimeException
*/
public function content(int|array $uids, string $rfc = "RFC822", int|string $uid = IMAP::ST_UID): Response {
return $this->fetch(["$rfc.TEXT"], is_array($uids) ? $uids : [$uids], null, $uid);
}
/**
* Fetch message headers
* @param int|array $uids
* @param string $rfc
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
*
* @return Response
* @throws RuntimeException
*/
public function headers(int|array $uids, string $rfc = "RFC822", int|string $uid = IMAP::ST_UID): Response {
return $this->fetch(["$rfc.HEADER"], is_array($uids) ? $uids : [$uids], null, $uid);
}
/**
* Fetch message flags
* @param int|array $uids
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
*
* @return Response
* @throws RuntimeException
*/
public function flags(int|array $uids, int|string $uid = IMAP::ST_UID): Response {
return $this->fetch(["FLAGS"], is_array($uids) ? $uids : [$uids], null, $uid);
}
/**
* Fetch message sizes
* @param int|array $uids
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
*
* @return Response
* @throws RuntimeException
*/
public function sizes(int|array $uids, int|string $uid = IMAP::ST_UID): Response {
return $this->fetch(["RFC822.SIZE"], is_array($uids) ? $uids : [$uids], null, $uid);
}
/**
* Get uid for a given id
* @param int|null $id message number
*
* @return Response message number for given message or all messages as array
* @throws MessageNotFoundException
*/
public function getUid(?int $id = null): Response {
if (!$this->enable_uid_cache || empty($this->uid_cache) || count($this->uid_cache) <= 0) {
try {
$this->setUidCache((array)$this->fetch('UID', 1, INF)->data()); // set cache for this folder
} catch (RuntimeException) {
}
}
$uids = $this->uid_cache;
if ($id == null) {
return Response::empty($this->debug)->setResult($uids);
}
foreach ($uids as $k => $v) {
if ($k == $id) {
return Response::empty($this->debug)->setResult($v);
}
}
// clear uid cache and run method again
if ($this->enable_uid_cache && $this->uid_cache) {
$this->setUidCache(null);
return $this->getUid($id);
}
throw new MessageNotFoundException('unique id not found');
}
/**
* Get a message number for a uid
* @param string $id uid
*
* @return Response message number
* @throws MessageNotFoundException
*/
public function getMessageNumber(string $id): Response {
foreach ($this->getUid()->data() as $k => $v) {
if ($v == $id) {
return Response::empty($this->debug)->setResult((int)$k);
}
}
throw new MessageNotFoundException('message number not found: ' . $id);
}
/**
* Get a list of available folders
*
* @param string $reference mailbox reference for list
* @param string $folder mailbox name match with wildcards
*
* @return Response folders that matched $folder as array(name => array('delimiter' => .., 'flags' => ..))
*
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
public function folders(string $reference = '', string $folder = '*'): Response {
$response = $this->requestAndResponse('LIST', $this->escapeString($reference, $folder))->setCanBeEmpty(true);
$list = $response->data();
$result = [];
if ($list[0] !== true) {
foreach ($list as $item) {
if (count($item) != 4 || $item[0] != 'LIST') {
continue;
}
$item[3] = str_replace("\\\\", "\\", str_replace("\\\"", "\"", $item[3]));
$result[$item[3]] = ['delimiter' => $item[2], 'flags' => $item[1]];
}
}
return $response->setResult($result);
}
/**
* Manage flags
*
* @param array|string $flags flags to set, add or remove - see $mode
* @param int $from message for items or start message if $to !== null
* @param int|null $to if null only one message ($from) is fetched, else it's the
* last message, INF means last message available
* @param string|null $mode '+' to add flags, '-' to remove flags, everything else sets the flags as given
* @param bool $silent if false the return values are the new flags for the wanted messages
* @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
* message numbers instead.
* @param string|null $item command used to store a flag
*
* @return Response new flags if $silent is false, else true or false depending on success
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
public function store(
array|string $flags, int $from, ?int $to = null, ?string $mode = null, bool $silent = true, int|string $uid = IMAP::ST_UID, ?string $item = null
): Response {
$flags = $this->escapeList(is_array($flags) ? $flags : [$flags]);
$set = $this->buildSet($from, $to);
$command = $this->buildUIDCommand("STORE", $uid);
$item = ($mode == '-' ? "-" : "+") . ($item === null ? "FLAGS" : $item) . ($silent ? '.SILENT' : "");
$response = $this->requestAndResponse($command, [$set, $item, $flags], $silent);
if ($silent) {
return $response;
}
$result = [];
foreach ($response as $token) {
if ($token[1] != 'FETCH' || $token[2][0] != 'FLAGS') {
continue;
}
$result[$token[0]] = $token[2][1];
}
return $response->setResult($result);
}
/**
* Append a new message to given folder
*
* @param string $folder name of target folder
* @param string $message full message content
* @param array|null $flags flags for new message
* @param string|null $date date for new message
*
* @return Response
*
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
*/
public function appendMessage(string $folder, string $message, ?array $flags = null, ?string $date = null): Response {
$tokens = [];
$tokens[] = $this->escapeString($folder);