Debian Codegraph @

lib/3rdParty/composer/webklex/php-imap/src/Connection/Protocols/ImapProtocol.php

raw symbols SCIP
1 <?php
2 /*
3 * File: ImapProtocol.php
4 * Category: Protocol
5 * Author: M.Goldenbaum
6 * Created: 16.09.20 18:27
7 * Updated: -
8 *
9 * Description:
10 * -
11 */
12
13 namespace Webklex\PHPIMAP\Connection\Protocols;
14
15 use Exception;
16 use Throwable;
17 use Webklex\PHPIMAP\Config;
18 use Webklex\PHPIMAP\Exceptions\AuthFailedException;
19 use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
20 use Webklex\PHPIMAP\Exceptions\ImapBadRequestException;
21 use Webklex\PHPIMAP\Exceptions\ImapServerErrorException;
22 use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
23 use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
24 use Webklex\PHPIMAP\Exceptions\ResponseException;
25 use Webklex\PHPIMAP\Exceptions\RuntimeException;
26 use Webklex\PHPIMAP\Header;
27 use Webklex\PHPIMAP\IMAP;
28
29 /**
30 * Class ImapProtocol
31 *
32 * @package Webklex\PHPIMAP\Connection\Protocols
33 *
34 * @reference https://www.rfc-editor.org/rfc/rfc2087.txt
35 */
36 class ImapProtocol extends Protocol {
37
38 /**
39 * Request noun
40 * @var int
41 */
42 protected int $noun = 0;
43
44 /**
45 * Imap constructor.
46 * @param Config $config
47 * @param bool $cert_validation set to false to skip SSL certificate validation
48 * @param mixed $encryption Connection encryption method
49 */
50 public function __construct(Config $config, bool $cert_validation = true, mixed $encryption = false) {
51 $this->config = $config;
52 $this->setCertValidation($cert_validation);
53 $this->encryption = $encryption;
54 }
55
56 /**
57 * Handle the class destruction / tear down
58 */
59 public function __destruct() {
60 $this->logout();
61 }
62
63 /**
64 * Open connection to IMAP server
65 * @param string $host hostname or IP address of IMAP server
66 * @param int|null $port of IMAP server, default is 143 and 993 for ssl
67 *
68 * @throws ConnectionFailedException
69 */
70 public function connect(string $host, ?int $port = null): bool {
71 $transport = 'tcp';
72 $encryption = '';
73
74 if ($this->encryption) {
75 $encryption = strtolower($this->encryption);
76 if (in_array($encryption, ['ssl', 'tls'])) {
77 $transport = $encryption;
78 $port = $port === null ? 993 : $port;
79 }
80 }
81 $port = $port === null ? 143 : $port;
82 try {
83 $response = new Response(0, $this->debug);
84 $this->stream = $this->createStream($transport, $host, $port, $this->connection_timeout);
85 if (!$this->stream || !$this->assumedNextLine($response, '* OK')) {
86 throw new ConnectionFailedException('connection refused');
87 }
88 if ($encryption == 'starttls') {
89 $this->enableStartTls();
90 }
91 } catch (Exception $e) {
92 throw new ConnectionFailedException('connection failed', 0, $e);
93 }
94 return true;
95 }
96
97 /**
98 * Check if the current session is connected
99 *
100 * @return bool
101 * @throws ImapBadRequestException
102 */
103 public function connected(): bool {
104 if ((bool)$this->stream) {
105 try {
106 $this->requestAndResponse('NOOP');
107 return true;
108 } catch (ImapServerErrorException|RuntimeException) {
109 return false;
110 }
111 }
112 return false;
113 }
114
115 /**
116 * Enable tls on the current connection
117 *
118 * @throws ConnectionFailedException
119 * @throws ImapBadRequestException
120 * @throws ImapServerErrorException
121 * @throws RuntimeException
122 */
123 protected function enableStartTls(): void {
124 $response = $this->requestAndResponse('STARTTLS');
125 $result = $response->successful() && stream_socket_enable_crypto($this->stream, true, $this->getCryptoMethod());
126 if (!$result) {
127 throw new ConnectionFailedException('failed to enable TLS');
128 }
129 }
130
131 /**
132 * Get the next line from stream
133 *
134 * @return string next line
135 * @throws RuntimeException
136 */
137 public function nextLine(Response $response): string {
138 $line = "";
139 while (($next_char = fread($this->stream, 1)) !== false && !in_array($next_char, ["", "\n"])) {
140 $line .= $next_char;
141 }
142 if ($line === "" && ($next_char === false || $next_char === "")) {
143 throw new RuntimeException('empty response');
144 }
145 $line .= "\n";
146 $response->addResponse($line);
147 if ($this->debug) echo "<< " . $line;
148 return $line;
149 }
150
151 /**
152 * Get the next line and check if it starts with a given string
153 * @param Response $response
154 * @param string $start
155 *
156 * @return bool
157 * @throws RuntimeException
158 */
159 protected function assumedNextLine(Response $response, string $start): bool {
160 return str_starts_with($this->nextLine($response), $start);
161 }
162
163 /**
164 * Get the next line and check if it starts with a given string
165 * The server can send untagged status updates starting with '*' if we are not looking for a status update,
166 * the untagged lines will be ignored.
167 *
168 * @param Response $response
169 * @param string $start
170 *
171 * @return bool
172 * @throws RuntimeException
173 */
174 protected function assumedNextLineIgnoreUntagged(Response $response, string $start): bool {
175 do {
176 $line = $this->nextLine($response);
177 } while (!(str_starts_with($start, '*')) && $this->isUntaggedLine($line));
178
179 return str_starts_with($line, $start);
180 }
181
182 /**
183 * Get the next line and split the tag
184 * @param string|null $tag reference tag
185 *
186 * @return string next line
187 * @throws RuntimeException
188 */
189 protected function nextTaggedLine(Response $response, ?string &$tag): string {
190 $line = $this->nextLine($response);
191 if (str_contains($line, ' ')) {
192 list($tag, $line) = explode(' ', $line, 2);
193 }
194
195 return $line ?? '';
196 }
197
198 /**
199 * Get the next line and split the tag
200 * The server can send untagged status updates starting with '*', the untagged lines will be ignored.
201 *
202 * @param string|null $tag reference tag
203 *
204 * @return string next line
205 * @throws RuntimeException
206 */
207 protected function nextTaggedLineIgnoreUntagged(Response $response, &$tag): string {
208 do {
209 $line = $this->nextLine($response);
210 } while ($this->isUntaggedLine($line));
211
212 list($tag, $line) = explode(' ', $line, 2);
213
214 return $line;
215 }
216
217 /**
218 * Get the next line and check if it contains a given string and split the tag
219 * @param Response $response
220 * @param string $start
221 * @param $tag
222 *
223 * @return bool
224 * @throws RuntimeException
225 */
226 protected function assumedNextTaggedLine(Response $response, string $start, &$tag): bool {
227 return str_contains($this->nextTaggedLine($response, $tag), $start);
228 }
229
230 /**
231 * Get the next line and check if it contains a given string and split the tag
232 * @param string $start
233 * @param $tag
234 *
235 * @return bool
236 * @throws RuntimeException
237 */
238 protected function assumedNextTaggedLineIgnoreUntagged(Response $response, string $start, &$tag): bool {
239 $line = $this->nextTaggedLineIgnoreUntagged($response, $tag);
240 return strpos($line, $start) !== false;
241 }
242
243 /**
244 * RFC3501 - 2.2.2
245 * Data transmitted by the server to the client and status responses
246 * that do not indicate command completion are prefixed with the token
247 * "*", and are called untagged responses.
248 *
249 * @param string $line
250 * @return bool
251 */
252 protected function isUntaggedLine(string $line) : bool {
253 return str_starts_with($line, '* ');
254 }
255
256 /**
257 * Split a given line in values. A value is literal of any form or a list
258 * @param Response $response
259 * @param string $line
260 *
261 * @return array
262 * @throws RuntimeException
263 */
264 protected function decodeLine(Response $response, string $line): array {
265 $tokens = [];
266 $stack = [];
267
268 // replace any trailing <NL> including spaces with a single space
269 $line = rtrim($line) . ' ';
270 while (($pos = strpos($line, ' ')) !== false) {
271 $token = substr($line, 0, $pos);
272 if (!strlen($token)) {
273 $line = substr($line, $pos + 1);
274 continue;
275 }
276 while ($token[0] == '(') {
277 $stack[] = $tokens;
278 $tokens = [];
279 $token = substr($token, 1);
280 }
281 if ($token[0] == '"') {
282 if (preg_match('%^\(*\"((.|\\\|\")*?)\"( |$)%', $line, $matches)) {
283 $tokens[] = $matches[1];
284 $line = substr($line, strlen($matches[0]));
285 continue;
286 }
287 }
288 if ($token[0] == '{') {
289 $endPos = strpos($token, '}');
290 $chars = substr($token, 1, $endPos - 1);
291 if (is_numeric($chars)) {
292 $token = '';
293 while (strlen($token) < $chars) {
294 $token .= $this->nextLine($response);
295 }
296 $line = '';
297 if (strlen($token) > $chars) {
298 $line = substr($token, $chars);
299 $token = substr($token, 0, $chars);
300 } else {
301 $line .= $this->nextLine($response);
302 }
303 $tokens[] = $token;
304 $line = trim($line) . ' ';
305 continue;
306 }
307 }
308 if ($stack && $token[strlen($token) - 1] == ')') {
309 // closing braces are not separated by spaces, so we need to count them
310 $braces = strlen($token);
311 $token = rtrim($token, ')');
312 // only count braces if more than one
313 $braces -= strlen($token) + 1;
314 // only add if token had more than just closing braces
315 if (rtrim($token) != '') {
316 $tokens[] = rtrim($token);
317 }
318 $token = $tokens;
319 $tokens = array_pop($stack);
320 // special handling if more than one closing brace
321 while ($braces-- > 0) {
322 $tokens[] = $token;
323 $token = $tokens;
324 $tokens = array_pop($stack);
325 }
326 }
327 $tokens[] = $token;
328 $line = substr($line, $pos + 1);
329 }
330
331 // maybe the server forgot to send some closing braces
332 while ($stack) {
333 $child = $tokens;
334 $tokens = array_pop($stack);
335 $tokens[] = $child;
336 }
337
338 return $tokens;
339 }
340
341 /**
342 * Read abd decode a response "line"
343 * @param Response $response
344 * @param array|string $tokens to decode
345 * @param string $wantedTag targeted tag
346 * @param bool $dontParse if true only the unparsed line is returned in $tokens
347 *
348 * @return bool
349 * @throws RuntimeException
350 */
351 public function readLine(Response $response, array|string &$tokens = [], string $wantedTag = '*', bool $dontParse = false): bool {
352 $line = $this->nextTaggedLine($response, $tag); // get next tag
353 if (!$dontParse) {
354 $tokens = $this->decodeLine($response, $line);
355 } else {
356 $tokens = $line;
357 }
358
359 // if tag is wanted tag we might be at the end of a multiline response
360 return $tag == $wantedTag;
361 }
362
363 /**
364 * Read all lines of response until given tag is found
365 * @param Response $response
366 * @param string $tag request tag
367 * @param bool $dontParse if true every line is returned unparsed instead of the decoded tokens
368 *
369 * @return array
370 *
371 * @throws ImapBadRequestException
372 * @throws ImapServerErrorException
373 * @throws RuntimeException
374 */
375 public function readResponse(Response $response, string $tag, bool $dontParse = false): array {
376 $lines = [];
377 $tokens = ""; // define $tokens variable before first use
378 do {
379 $readAll = $this->readLine($response, $tokens, $tag, $dontParse);
380 $lines[] = $tokens;
381 } while (!$readAll);
382
383 $original = $tokens;
384 if ($dontParse) {
385 // First two chars are still needed for the response code
386 $tokens = [trim(substr($tokens, 0, 3))];
387 }
388
389 $original = is_array($original) ? $original : [$original];
390
391
392 // last line has response code
393 if ($tokens[0] == 'OK') {
394 return $lines ?: [true];
395 } elseif ($tokens[0] == 'NO' || $tokens[0] == 'BAD' || $tokens[0] == 'BYE') {
396 throw new ImapServerErrorException($this->stringifyArray($original));
397 }
398
399 throw new ImapBadRequestException($this->stringifyArray($original));
400 }
401
402 /**
403 * Convert an array to a string
404 * @param array $arr array to stringify
405 *
406 * @return string stringified array
407 */
408 private function stringifyArray(array $arr): string {
409 $string = "";
410 foreach ($arr as $value) {
411 if (is_array($value)) {
412 $string .= "(" . $this->stringifyArray($value) . ")";
413 } else {
414 $string .= $value . " ";
415 }
416 }
417 return $string;
418 }
419
420 /**
421 * Send a new request
422 * @param string $command
423 * @param array $tokens additional parameters to command, use escapeString() to prepare
424 * @param string|null $tag provide a tag otherwise an autogenerated is returned
425 *
426 * @return Response
427 * @throws RuntimeException
428 */
429 public function sendRequest(string $command, array $tokens = [], ?string &$tag = null): Response {
430 if (!$tag) {
431 $this->noun++;
432 $tag = 'TAG' . $this->noun;
433 }
434
435 $line = $tag . ' ' . $command;
436
437 $response = new Response($this->noun, $this->debug);
438
439 foreach ($tokens as $token) {
440 if (is_array($token)) {
441 $this->write($response, $line . ' ' . $token[0]);
442 if (!$this->assumedNextLine($response, '+ ')) {
443 throw new RuntimeException('failed to send literal string');
444 }
445 $line = $token[1];
446 } else {
447 $line .= ' ' . $token;
448 }
449 }
450 $this->write($response, $line);
451
452 return $response;
453 }
454
455 /**
456 * Write data to the current stream
457 * @param Response $response
458 * @param string $data
459 *
460 * @return void
461 * @throws RuntimeException
462 */
463 public function write(Response $response, string $data): void {
464 $command = $data . "\r\n";
465 if ($this->debug) echo ">> " . $command . "\n";
466
467 $response->addCommand($command);
468
469 if (fwrite($this->stream, $command) === false) {
470 throw new RuntimeException('failed to write - connection closed?');
471 }
472 }
473
474 /**
475 * Send a request and get response at once
476 *
477 * @param string $command
478 * @param array $tokens parameters as in sendRequest()
479 * @param bool $dontParse if true unparsed lines are returned instead of tokens
480 *
481 * @return Response response as in readResponse()
482 * @throws ImapBadRequestException
483 * @throws ImapServerErrorException
484 * @throws RuntimeException
485 */
486 public function requestAndResponse(string $command, array $tokens = [], bool $dontParse = false): Response {
487 $response = $this->sendRequest($command, $tokens, $tag);
488 $response->setResult($this->readResponse($response, $tag, $dontParse));
489
490 return $response;
491 }
492
493 /**
494 * Escape one or more literals i.e. for sendRequest
495 * @param array|string $string the literal/-s
496 *
497 * @return string|array escape literals, literals with newline ar returned
498 * as array('{size}', 'string');
499 */
500 public function escapeString(array|string $string): array|string {
501 if (func_num_args() < 2) {
502 if (str_contains($string, "\n")) {
503 return ['{' . strlen($string) . '}', $string];
504 } else {
505 return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $string) . '"';
506 }
507 }
508 $result = [];
509 foreach (func_get_args() as $string) {
510 $result[] = $this->escapeString($string);
511 }
512 return $result;
513 }
514
515 /**
516 * Escape a list with literals or lists
517 * @param array $list list with literals or lists as PHP array
518 *
519 * @return string escaped list for imap
520 */
521 public function escapeList(array $list): string {
522 $result = [];
523 foreach ($list as $v) {
524 if (!is_array($v)) {
525 $result[] = $v;
526 continue;
527 }
528 $result[] = $this->escapeList($v);
529 }
530 return '(' . implode(' ', $result) . ')';
531 }
532
533 /**
534 * Login to a new session.
535 *
536 * @param string $user username
537 * @param string $password password
538 *
539 * @return Response
540 * @throws AuthFailedException
541 * @throws ImapBadRequestException
542 * @throws ImapServerErrorException
543 */
544 public function login(string $user, string $password): Response {
545 try {
546 $command = 'LOGIN';
547 $params = $this->escapeString($user, $password);
548
549 return $this->requestAndResponse($command, $params, true);
550 } catch (RuntimeException $e) {
551 throw new AuthFailedException("failed to authenticate", 0, $e);
552 }
553 }
554
555 /**
556 * Authenticate your current IMAP session.
557 * @param string $user username
558 * @param string $token access token
559 *
560 * @return Response
561 * @throws AuthFailedException
562 */
563 public function authenticate(string $user, string $token): Response {
564 try {
565 $authenticateParams = ['XOAUTH2', base64_encode("user=$user\1auth=Bearer $token\1\1")];
566 $response = $this->sendRequest('AUTHENTICATE', $authenticateParams);
567
568 while (true) {
569 $tokens = "";
570 $is_plus = $this->readLine($response, $tokens, '+', true);
571 if ($is_plus) {
572 // try to log the challenge somewhere where it can be found
573 error_log("got an extra server challenge: $tokens");
574 // respond with an empty response.
575 $response->stack($this->sendRequest(''));
576 } else {
577 if (preg_match('/^NO /i', $tokens) ||
578 preg_match('/^BAD /i', $tokens)) {
579 error_log("got failure response: $tokens");
580 return $response->addError("got failure response: $tokens");
581 } else if (preg_match("/^OK /i", $tokens)) {
582 return $response->setResult(is_array($tokens) ? $tokens : [$tokens]);
583 }
584 }
585 }
586 } catch (RuntimeException $e) {
587 throw new AuthFailedException("failed to authenticate", 0, $e);
588 }
589 }
590
591 /**
592 * Logout of imap server
593 *
594 * @return Response
595 */
596 public function logout(): Response {
597 if (!$this->stream) {
598 $this->reset();
599 return new Response(0, $this->debug);
600 } elseif ($this->meta()["timed_out"]) {
601 $this->reset();
602 return new Response(0, $this->debug);
603 }
604
605 $result = null;
606 try {
607 $result = $this->requestAndResponse('LOGOUT', [], true);
608 fclose($this->stream);
609 } catch (Throwable) {
610 }
611
612 $this->reset();
613
614 return $result ?? new Response(0, $this->debug);
615 }
616
617 /**
618 * Reset the current stream and uid cache
619 *
620 * @return void
621 */
622 public function reset(): void {
623 $this->stream = null;
624 $this->uid_cache = [];
625 }
626
627 /**
628 * Get an array of available capabilities
629 *
630 * @return Response list of capabilities
631 *
632 * @throws ImapBadRequestException
633 * @throws ImapServerErrorException
634 * @throws RuntimeException
635 * @throws ResponseException
636 */
637 public function getCapabilities(): Response {
638 $response = $this->requestAndResponse('CAPABILITY');
639
640 if (!$response->getResponse()) return $response;
641
642 return $response->setResult($response->validatedData()[0]);
643 }
644
645 /**
646 * Examine and select have the same response.
647 * @param string $command can be 'EXAMINE' or 'SELECT'
648 * @param string $folder target folder
649 *
650 * @return Response
651 * @throws RuntimeException
652 */
653 public function examineOrSelect(string $command = 'EXAMINE', string $folder = 'INBOX'): Response {
654 $response = $this->sendRequest($command, [$this->escapeString($folder)], $tag);
655
656 $result = [];
657 $tokens = []; // define $tokens variable before first use
658 while (!$this->readLine($response, $tokens, $tag)) {
659 if ($tokens[0] == 'FLAGS') {
660 array_shift($tokens);
661 $result['flags'] = $tokens;
662 continue;
663 }
664 switch ($tokens[1]) {
665 case 'EXISTS':
666 case 'RECENT':
667 $result[strtolower($tokens[1])] = (int)$tokens[0];
668 break;
669 case '[UIDVALIDITY':
670 $result['uidvalidity'] = (int)$tokens[2];
671 break;
672 case '[UIDNEXT':
673 $result['uidnext'] = (int)$tokens[2];
674 break;
675 case '[UNSEEN':
676 $result['unseen'] = (int)$tokens[2];
677 break;
678 case '[NONEXISTENT]':
679 throw new RuntimeException("folder doesn't exist");
680 default:
681 // ignore
682 break;
683 }
684 }
685
686 $response->setResult($result);
687
688 if ($tokens[0] != 'OK') {
689 $response->addError("request failed");
690 }
691 return $response;
692 }
693
694 /**
695 * Change the current folder
696 * @param string $folder change to this folder
697 *
698 * @return Response see examineOrSelect()
699 * @throws RuntimeException
700 */
701 public function selectFolder(string $folder = 'INBOX'): Response {
702 $this->uid_cache = [];
703
704 return $this->examineOrSelect('SELECT', $folder);
705 }
706
707 /**
708 * Examine a given folder
709 * @param string $folder examine this folder
710 *
711 * @return Response see examineOrSelect()
712 * @throws RuntimeException
713 */
714 public function examineFolder(string $folder = 'INBOX'): Response {
715 return $this->examineOrSelect('EXAMINE', $folder);
716 }
717
718 /**
719 * Get the status of a given folder
720 *
721 * @param string $folder
722 * @param string[] $arguments
723 * @return Response list of STATUS items
724 *
725 * @throws ImapBadRequestException
726 * @throws ImapServerErrorException
727 * @throws ResponseException
728 * @throws RuntimeException
729 */
730 public function folderStatus(string $folder = 'INBOX', $arguments = ['MESSAGES', 'UNSEEN', 'RECENT', 'UIDNEXT', 'UIDVALIDITY']): Response {
731 $response = $this->requestAndResponse('STATUS', [$this->escapeString($folder), $this->escapeList($arguments)]);
732 $data = $response->validatedData();
733
734 if (!isset($data[0]) || !isset($data[0][2])) {
735 throw new RuntimeException("folder status could not be fetched");
736 }
737
738 $result = [];
739 $key = null;
740 foreach ($data[0][2] as $value) {
741 if ($key === null) {
742 $key = $value;
743 } else {
744 $result[strtolower($key)] = (int)$value;
745 $key = null;
746 }
747 }
748
749 $response->setResult($result);
750
751 return $response;
752 }
753
754 /**
755 * Fetch one or more items of one or more messages
756 * @param array|string $items items to fetch [RFC822.HEADER, FLAGS, RFC822.TEXT, etc]
757 * @param array|int $from message for items or start message if $to !== null
758 * @param int|null $to if null only one message ($from) is fetched, else it's the
759 * last message, INF means last message available
760 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
761 * message numbers instead.
762 *
763 * @return Response if only one item of one message is fetched it's returned as string
764 * if items of one message are fetched it's returned as (name => value)
765 * if one item of messages are fetched it's returned as (msgno => value)
766 * if items of messages are fetched it's returned as (msgno => (name => value))
767 * @throws RuntimeException
768 */
769 public function fetch(array|string $items, array|int $from, mixed $to = null, int|string $uid = IMAP::ST_UID): Response {
770 if (is_array($from) && count($from) > 1) {
771 $set = implode(',', $from);
772 } elseif (is_array($from) && count($from) === 1) {
773 $from = array_values($from);
774 $set = $from[0] . ':' . $from[0];
775 } elseif ($to === null) {
776 $set = $from . ':' . $from;
777 } elseif ($to == INF) {
778 $set = $from . ':*';
779 } else {
780 $set = $from . ':' . (int)$to;
781 }
782
783 $items = (array)$items;
784 $itemList = $this->escapeList($items);
785
786 $response = $this->sendRequest($this->buildUIDCommand("FETCH", $uid), [$set, $itemList], $tag);
787 $result = [];
788 $tokens = []; // define $tokens variable before first use
789 while (!$this->readLine($response, $tokens, $tag)) {
790 // ignore other responses
791 if ($tokens[1] != 'FETCH') {
792 continue;
793 }
794
795 $uidKey = 0;
796 $data = [];
797
798 // find array key of UID value; try the last elements, or search for it
799 if ($uid === IMAP::ST_UID) {
800 $count = count($tokens[2]);
801 if ($tokens[2][$count - 2] == 'UID') {
802 $uidKey = $count - 1;
803 } else if ($tokens[2][0] == 'UID') {
804 $uidKey = 1;
805 } else {
806 $found = array_search('UID', $tokens[2]);
807 if ($found === false || $found === -1) {
808 continue;
809 }
810
811 $uidKey = $found + 1;
812 }
813 }
814
815 // ignore other messages
816 if ($to === null && !is_array($from) && ($uid === IMAP::ST_UID ? $tokens[2][$uidKey] != $from : $tokens[0] != $from)) {
817 continue;
818 }
819
820 // if we only want one item we return that one directly
821 if (count($items) == 1) {
822 if ($tokens[2][0] == $items[0]) {
823 $data = $tokens[2][1];
824 } elseif ($uid === IMAP::ST_UID && $tokens[2][2] == $items[0]) {
825 $data = $tokens[2][3];
826 } else {
827 $expectedResponse = 0;
828 // maybe the server send another field we didn't wanted
829 $count = count($tokens[2]);
830 // we start with 2, because 0 was already checked
831 for ($i = 2; $i < $count; $i += 2) {
832 if ($tokens[2][$i] != $items[0]) {
833 continue;
834 }
835 $data = $tokens[2][$i + 1];
836 $expectedResponse = 1;
837 break;
838 }
839 if (!$expectedResponse) {
840 continue;
841 }
842 }
843 } else {
844 while (key($tokens[2]) !== null) {
845 $data[current($tokens[2])] = next($tokens[2]);
846 next($tokens[2]);
847 }
848 }
849
850 // if we want only one message we can ignore everything else and just return
851 if ($to === null && !is_array($from) && ($uid === IMAP::ST_UID ? $tokens[2][$uidKey] == $from : $tokens[0] == $from)) {
852 // we still need to read all lines
853 if (!$this->readLine($response, $tokens, $tag))
854 return $response->setResult($data);
855 }
856 if ($uid === IMAP::ST_UID) {
857 $result[$tokens[2][$uidKey]] = $data;
858 } else {
859 $result[$tokens[0]] = $data;
860 }
861 }
862
863 if ($to === null && !is_array($from)) {
864 throw new RuntimeException('the single id was not found in response');
865 }
866
867 return $response->setResult($result);
868 }
869
870 /**
871 * Fetch message body (without headers)
872 * @param int|array $uids
873 * @param string $rfc
874 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
875 * message numbers instead.
876 *
877 * @return Response
878 * @throws RuntimeException
879 */
880 public function content(int|array $uids, string $rfc = "RFC822", int|string $uid = IMAP::ST_UID): Response {
881 $rfc = $rfc ?? "RFC822";
882 $item = $rfc === "BODY" ? "BODY[TEXT]" : "$rfc.TEXT";
883 return $this->fetch([$item], is_array($uids) ? $uids : [$uids], null, $uid);
884 }
885
886 /**
887 * Fetch message headers
888 * @param int|array $uids
889 * @param string $rfc
890 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
891 * message numbers instead.
892 *
893 * @return Response
894 * @throws RuntimeException
895 */
896 public function headers(int|array $uids, string $rfc = "RFC822", int|string $uid = IMAP::ST_UID): Response {
897 return $this->fetch(["$rfc.HEADER"], is_array($uids) ? $uids : [$uids], null, $uid);
898 }
899
900 /**
901 * Fetch message flags
902 * @param int|array $uids
903 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
904 * message numbers instead.
905 *
906 * @return Response
907 * @throws RuntimeException
908 */
909 public function flags(int|array $uids, int|string $uid = IMAP::ST_UID): Response {
910 return $this->fetch(["FLAGS"], is_array($uids) ? $uids : [$uids], null, $uid);
911 }
912
913 /**
914 * Fetch message sizes
915 * @param int|array $uids
916 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
917 * message numbers instead.
918 *
919 * @return Response
920 * @throws RuntimeException
921 */
922 public function sizes(int|array $uids, int|string $uid = IMAP::ST_UID): Response {
923 return $this->fetch(["RFC822.SIZE"], is_array($uids) ? $uids : [$uids], null, $uid);
924 }
925
926 /**
927 * Get uid for a given id
928 * @param int|null $id message number
929 *
930 * @return Response message number for given message or all messages as array
931 * @throws MessageNotFoundException
932 */
933 public function getUid(?int $id = null): Response {
934 if (!$this->enable_uid_cache || empty($this->uid_cache) || count($this->uid_cache) <= 0) {
935 try {
936 $this->setUidCache((array)$this->fetch('UID', 1, INF)->data()); // set cache for this folder
937 } catch (RuntimeException) {
938 }
939 }
940 $uids = $this->uid_cache;
941
942 if ($id == null) {
943 return Response::empty($this->debug)->setResult($uids)->setCanBeEmpty(true);
944 }
945
946 foreach ($uids as $k => $v) {
947 if ($k == $id) {
948 return Response::empty($this->debug)->setResult($v);
949 }
950 }
951
952 // clear uid cache and run method again
953 if ($this->enable_uid_cache && $this->uid_cache) {
954 $this->setUidCache(null);
955 return $this->getUid($id);
956 }
957
958 throw new MessageNotFoundException('unique id not found');
959 }
960
961 /**
962 * Get a message number for a uid
963 * @param string $id uid
964 *
965 * @return Response message number
966 * @throws MessageNotFoundException
967 */
968 public function getMessageNumber(string $id): Response {
969 foreach ($this->getUid()->data() as $k => $v) {
970 if ($v == $id) {
971 return Response::empty($this->debug)->setResult((int)$k);
972 }
973 }
974
975 throw new MessageNotFoundException('message number not found: ' . $id);
976 }
977
978 /**
979 * Get a list of available folders
980 *
981 * @param string $reference mailbox reference for list
982 * @param string $folder mailbox name match with wildcards
983 *
984 * @return Response folders that matched $folder as array(name => array('delimiter' => .., 'flags' => ..))
985 *
986 * @throws ImapBadRequestException
987 * @throws ImapServerErrorException
988 * @throws RuntimeException
989 */
990 public function folders(string $reference = '', string $folder = '*'): Response {
991 $response = $this->requestAndResponse('LIST', $this->escapeString($reference, $folder))->setCanBeEmpty(true);
992 $list = $response->data();
993
994 $result = [];
995 if ($list[0] !== true) {
996 foreach ($list as $item) {
997 if (count($item) != 4 || $item[0] != 'LIST') {
998 continue;
999 }
1000 $item[3] = str_replace("\\\\", "\\", str_replace("\\\"", "\"", $item[3]));
1001 $result[$item[3]] = ['delimiter' => $item[2], 'flags' => $item[1]];
1002 }
1003 }
1004
1005 return $response->setResult($result);
1006 }
1007
1008 /**
1009 * Manage flags
1010 *
1011 * @param array|string $flags flags to set, add or remove - see $mode
1012 * @param int $from message for items or start message if $to !== null
1013 * @param int|null $to if null only one message ($from) is fetched, else it's the
1014 * last message, INF means last message available
1015 * @param string|null $mode '+' to add flags, '-' to remove flags, everything else sets the flags as given
1016 * @param bool $silent if false the return values are the new flags for the wanted messages
1017 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1018 * message numbers instead.
1019 * @param string|null $item command used to store a flag
1020 *
1021 * @return Response new flags if $silent is false, else true or false depending on success
1022 * @throws ImapBadRequestException
1023 * @throws ImapServerErrorException
1024 * @throws RuntimeException
1025 */
1026 public function store(
1027 array|string $flags, int $from, ?int $to = null, ?string $mode = null, bool $silent = true, int|string $uid = IMAP::ST_UID, ?string $item = null
1028 ): Response {
1029 $flags = $this->escapeList(is_array($flags) ? $flags : [$flags]);
1030 $set = $this->buildSet($from, $to);
1031
1032 $command = $this->buildUIDCommand("STORE", $uid);
1033 $item = ($mode == '-' ? "-" : "+") . ($item === null ? "FLAGS" : $item) . ($silent ? '.SILENT' : "");
1034
1035 $response = $this->requestAndResponse($command, [$set, $item, $flags], $silent);
1036
1037 if ($silent) {
1038 return $response;
1039 }
1040
1041 $result = [];
1042 foreach ($response as $token) {
1043 if ($token[1] != 'FETCH' || $token[2][0] != 'FLAGS') {
1044 continue;
1045 }
1046 $result[$token[0]] = $token[2][1];
1047 }
1048
1049
1050 return $response->setResult($result);
1051 }
1052
1053 /**
1054 * Append a new message to given folder
1055 *
1056 * @param string $folder name of target folder
1057 * @param string $message full message content
1058 * @param array|null $flags flags for new message
1059 * @param string|null $date date for new message
1060 *
1061 * @return Response
1062 *
1063 * @throws ImapBadRequestException
1064 * @throws ImapServerErrorException
1065 * @throws RuntimeException
1066 */
1067 public function appendMessage(string $folder, string $message, ?array $flags = null, ?string $date = null): Response {
1068 $tokens = [];
1069 $tokens[] = $this->escapeString($folder);
1070 if ($flags !== null) {
1071 $tokens[] = $this->escapeList($flags);
1072 }
1073 if ($date !== null) {
1074 $tokens[] = $this->escapeString($date);
1075 }
1076 $tokens[] = $this->escapeString($message);
1077
1078 return $this->requestAndResponse('APPEND', $tokens, true);
1079 }
1080
1081 /**
1082 * Copy a message set from current folder to another folder
1083 *
1084 * @param string $folder destination folder
1085 * @param $from
1086 * @param int|null $to if null only one message ($from) is fetched, else it's the
1087 * last message, INF means last message available
1088 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1089 * message numbers instead.
1090 *
1091 * @return Response
1092 *
1093 * @throws ImapBadRequestException
1094 * @throws ImapServerErrorException
1095 * @throws RuntimeException
1096 */
1097 public function copyMessage(string $folder, $from, ?int $to = null, int|string $uid = IMAP::ST_UID): Response {
1098 $set = $this->buildSet($from, $to);
1099 $command = $this->buildUIDCommand("COPY", $uid);
1100
1101 return $this->requestAndResponse($command, [$set, $this->escapeString($folder)], true);
1102 }
1103
1104 /**
1105 * Copy multiple messages to the target folder
1106 *
1107 * @param array $messages List of message identifiers
1108 * @param string $folder Destination folder
1109 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1110 * message numbers instead.
1111 *
1112 * @return Response Tokens if operation successful, false if an error occurred
1113 *
1114 * @throws ImapBadRequestException
1115 * @throws ImapServerErrorException
1116 * @throws RuntimeException
1117 */
1118 public function copyManyMessages(array $messages, string $folder, int|string $uid = IMAP::ST_UID): Response {
1119 $command = $this->buildUIDCommand("COPY", $uid);
1120
1121 $set = implode(',', $messages);
1122 $tokens = [$set, $this->escapeString($folder)];
1123
1124 return $this->requestAndResponse($command, $tokens, true);
1125 }
1126
1127 /**
1128 * Move a message set from current folder to another folder
1129 *
1130 * @param string $folder destination folder
1131 * @param $from
1132 * @param int|null $to if null only one message ($from) is fetched, else it's the
1133 * last message, INF means last message available
1134 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1135 * message numbers instead.
1136 *
1137 * @return Response
1138 *
1139 * @throws ImapBadRequestException
1140 * @throws ImapServerErrorException
1141 * @throws RuntimeException
1142 */
1143 public function moveMessage(string $folder, $from, ?int $to = null, int|string $uid = IMAP::ST_UID): Response {
1144 $set = $this->buildSet($from, $to);
1145 $command = $this->buildUIDCommand("MOVE", $uid);
1146
1147 $result = $this->requestAndResponse($command, [$set, $this->escapeString($folder)], true);
1148 // RFC4315 fallback to COPY, STORE and EXPUNGE.
1149 // Required for cases where MOVE isn't supported by the server. So we copy the message to the target folder,
1150 // mark the original message as deleted and expunge the mailbox.
1151 // See the following links for more information:
1152 // - https://github.com/freescout-help-desk/freescout/issues/4313
1153 // - https://github.com/Webklex/php-imap/issues/123
1154 if (!$result->boolean()) {
1155 $result = $this->copyMessage($folder, $from, $to, $uid);
1156 if (!$result->boolean()) {
1157 return $result;
1158 }
1159 $result = $this->store(['\Deleted'], $from, $to, null, true, $uid);
1160 if (!$result->boolean()) {
1161 return $result;
1162 }
1163 return $this->expunge();
1164 }
1165 return $result;
1166 }
1167
1168 /**
1169 * Move multiple messages to the target folder
1170 *
1171 * @param array $messages List of message identifiers
1172 * @param string $folder Destination folder
1173 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1174 * message numbers instead.
1175 *
1176 * @return Response
1177 *
1178 * @throws ImapBadRequestException
1179 * @throws ImapServerErrorException
1180 * @throws RuntimeException
1181 */
1182 public function moveManyMessages(array $messages, string $folder, int|string $uid = IMAP::ST_UID): Response {
1183 $command = $this->buildUIDCommand("MOVE", $uid);
1184 $set = implode(',', $messages);
1185 $tokens = [$set, $this->escapeString($folder)];
1186
1187 $result = $this->requestAndResponse($command, $tokens, true);
1188 // RFC4315 fallback to COPY, STORE and EXPUNGE.
1189 // Required for cases where MOVE isn't supported by the server. So we copy the message to the target folder,
1190 // mark the original message as deleted and expunge the mailbox.
1191 // See the following links for more information:
1192 // - https://github.com/freescout-help-desk/freescout/issues/4313
1193 // - https://github.com/Webklex/php-imap/issues/123
1194 if (!$result->boolean()) {
1195 $result = $this->copyManyMessages($messages, $folder, $uid);
1196 if (!$result->boolean()) {
1197 return $result;
1198 }
1199 foreach ($messages as $message) {
1200 $result = $this->store(['\Deleted'], $message, $message, null, true, $uid);
1201 if (!$result->boolean()) {
1202 return $result;
1203 }
1204 }
1205 return $this->expunge();
1206 }
1207 return $result;
1208 }
1209
1210 /**
1211 * Exchange identification information
1212 * Ref.: https://datatracker.ietf.org/doc/html/rfc2971
1213 *
1214 * @param array|null $ids
1215 * @return Response
1216 *
1217 * @throws ImapBadRequestException
1218 * @throws ImapServerErrorException
1219 * @throws RuntimeException
1220 */
1221 public function ID($ids = null): Response {
1222 $token = "NIL";
1223 if (is_array($ids) && !empty($ids)) {
1224 $token = "(";
1225 foreach ($ids as $id) {
1226 $token .= '"' . $id . '" ';
1227 }
1228 $token = rtrim($token) . ")";
1229 }
1230
1231 return $this->requestAndResponse("ID", [$token], true);
1232 }
1233
1234 /**
1235 * Create a new folder (and parent folders if needed)
1236 *
1237 * @param string $folder folder name
1238 * @return Response
1239 *
1240 * @throws ImapBadRequestException
1241 * @throws ImapServerErrorException
1242 * @throws RuntimeException
1243 */
1244 public function createFolder(string $folder): Response {
1245 return $this->requestAndResponse('CREATE', [$this->escapeString($folder)], true);
1246 }
1247
1248 /**
1249 * Rename an existing folder
1250 *
1251 * @param string $old old name
1252 * @param string $new new name
1253 *
1254 * @return Response
1255 *
1256 * @throws ImapBadRequestException
1257 * @throws ImapServerErrorException
1258 * @throws RuntimeException
1259 */
1260 public function renameFolder(string $old, string $new): Response {
1261 return $this->requestAndResponse('RENAME', $this->escapeString($old, $new), true);
1262 }
1263
1264 /**
1265 * Delete a folder
1266 *
1267 * @param string $folder folder name
1268 * @return Response
1269 *
1270 * @throws ImapBadRequestException
1271 * @throws ImapServerErrorException
1272 * @throws RuntimeException
1273 */
1274 public function deleteFolder(string $folder): Response {
1275 return $this->requestAndResponse('DELETE', [$this->escapeString($folder)], true);
1276 }
1277
1278 /**
1279 * Subscribe to a folder
1280 *
1281 * @param string $folder folder name
1282 * @return Response
1283 *
1284 * @throws ImapBadRequestException
1285 * @throws ImapServerErrorException
1286 * @throws RuntimeException
1287 */
1288 public function subscribeFolder(string $folder): Response {
1289 return $this->requestAndResponse('SUBSCRIBE', [$this->escapeString($folder)], true);
1290 }
1291
1292 /**
1293 * Unsubscribe from a folder
1294 *
1295 * @param string $folder folder name
1296 * @return Response
1297 *
1298 * @throws ImapBadRequestException
1299 * @throws ImapServerErrorException
1300 * @throws RuntimeException
1301 */
1302 public function unsubscribeFolder(string $folder): Response {
1303 return $this->requestAndResponse('UNSUBSCRIBE', [$this->escapeString($folder)], true);
1304 }
1305
1306 /**
1307 * Apply session saved changes to the server
1308 *
1309 * @return Response
1310 * @throws ImapBadRequestException
1311 * @throws ImapServerErrorException
1312 * @throws RuntimeException
1313 */
1314 public function expunge(): Response {
1315 $this->uid_cache = [];
1316 return $this->requestAndResponse('EXPUNGE');
1317 }
1318
1319 /**
1320 * Send noop command
1321 *
1322 * @return Response
1323 * @throws ImapBadRequestException
1324 * @throws ImapServerErrorException
1325 * @throws RuntimeException
1326 */
1327 public function noop(): Response {
1328 return $this->requestAndResponse('NOOP');
1329 }
1330
1331 /**
1332 * Retrieve the quota level settings, and usage statics per mailbox
1333 *
1334 * @param $username
1335 * @return Response
1336 *
1337 * @throws ImapBadRequestException
1338 * @throws ImapServerErrorException
1339 * @throws RuntimeException
1340 *
1341 * @Doc https://www.rfc-editor.org/rfc/rfc2087.txt
1342 */
1343 public function getQuota($username): Response {
1344 $command = "GETQUOTA";
1345 $params = ['"#user/' . $username . '"'];
1346
1347 return $this->requestAndResponse($command, $params);
1348 }
1349
1350 /**
1351 * Retrieve the quota settings per user
1352 *
1353 * @param string $quota_root
1354 * @return Response
1355 *
1356 * @throws ImapBadRequestException
1357 * @throws ImapServerErrorException
1358 * @throws RuntimeException
1359 *
1360 * @Doc https://www.rfc-editor.org/rfc/rfc2087.txt
1361 */
1362 public function getQuotaRoot(string $quota_root = 'INBOX'): Response {
1363 $command = "GETQUOTAROOT";
1364 $params = [$quota_root];
1365
1366 return $this->requestAndResponse($command, $params);
1367 }
1368
1369 /**
1370 * Send idle command
1371 *
1372 * @throws RuntimeException
1373 */
1374 public function idle(): void {
1375 $response = $this->sendRequest("IDLE");
1376 if (!$this->assumedNextLineIgnoreUntagged($response, '+ ')) {
1377 throw new RuntimeException('idle failed');
1378 }
1379 }
1380
1381 /**
1382 * Send done command
1383 * @throws RuntimeException
1384 */
1385 public function done(): bool {
1386 $response = new Response($this->noun, $this->debug);
1387 $this->write($response, "DONE");
1388 if (!$this->assumedNextTaggedLineIgnoreUntagged($response, 'OK', $tags)) {
1389 throw new RuntimeException('done failed');
1390 }
1391 return true;
1392 }
1393
1394 /**
1395 * Search for matching messages
1396 *
1397 * @param array $params
1398 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1399 * message numbers instead.
1400 *
1401 * @return Response message ids
1402 * @throws ImapBadRequestException
1403 * @throws ImapServerErrorException
1404 * @throws RuntimeException
1405 */
1406 public function search(array $params, int|string $uid = IMAP::ST_UID): Response {
1407 $command = $this->buildUIDCommand("SEARCH", $uid);
1408 $response = $this->requestAndResponse($command, $params)->setCanBeEmpty(true);
1409
1410 foreach ($response->data() as $ids) {
1411 if ($ids[0] === 'SEARCH') {
1412 array_shift($ids);
1413 return $response->setResult($ids);
1414 }
1415 }
1416
1417 return $response;
1418 }
1419
1420 /**
1421 * Get a message overview
1422 * @param string $sequence
1423 * @param int|string $uid set to IMAP::ST_UID or any string representing the UID - set to IMAP::ST_MSGN to use
1424 * message numbers instead.
1425 *
1426 * @return Response
1427 * @throws RuntimeException
1428 * @throws MessageNotFoundException
1429 * @throws InvalidMessageDateException
1430 */
1431 public function overview(string $sequence, int|string $uid = IMAP::ST_UID): Response {
1432 $result = [];
1433 list($from, $to) = explode(":", $sequence);
1434
1435 $response = $this->getUid();
1436 $ids = [];
1437 foreach ($response->data() as $msgn => $v) {
1438 $id = $uid === IMAP::ST_UID ? $v : $msgn;
1439 if (($to >= $id && $from <= $id) || ($to === "*" && $from <= $id)) {
1440 $ids[] = $id;
1441 }
1442 }
1443 if (!empty($ids)) {
1444 $headers = $this->headers($ids, "RFC822", $uid);
1445 $response->stack($headers);
1446 foreach ($headers->data() as $id => $raw_header) {
1447 $result[$id] = (new Header($raw_header, $this->config))->getAttributes();
1448 }
1449 }
1450 return $response->setResult($result)->setCanBeEmpty(true);
1451 }
1452
1453 /**
1454 * Enable the debug mode
1455 *
1456 * @return void
1457 */
1458 public function enableDebug(): void {
1459 $this->debug = true;
1460 }
1461
1462 /**
1463 * Disable the debug mode
1464 *
1465 * @return void
1466 */
1467 public function disableDebug(): void {
1468 $this->debug = false;
1469 }
1470
1471 /**
1472 * Build a valid UID number set
1473 * @param $from
1474 * @param null $to
1475 *
1476 * @return int|string
1477 */
1478 public function buildSet($from, $to = null): int|string {
1479 $set = (int)$from;
1480 if ($to !== null) {
1481 $set .= ':' . ($to == INF ? '*' : (int)$to);
1482 }
1483 return $set;
1484 }
1485 }