Debian Codegraph @

lib/3rdParty/composer/webklex/php-imap/src/Folder.php

raw symbols SCIP
1 <?php
2 /*
3 * File: Folder.php
4 * Category: -
5 * Author: M. Goldenbaum
6 * Created: 19.01.17 22:21
7 * Updated: -
8 *
9 * Description:
10 * -
11 */
12
13 namespace Webklex\PHPIMAP;
14
15 use Carbon\Carbon;
16 use Webklex\PHPIMAP\Connection\Protocols\Response;
17 use Webklex\PHPIMAP\Exceptions\AuthFailedException;
18 use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
19 use Webklex\PHPIMAP\Exceptions\EventNotFoundException;
20 use Webklex\PHPIMAP\Exceptions\FolderFetchingException;
21 use Webklex\PHPIMAP\Exceptions\ImapBadRequestException;
22 use Webklex\PHPIMAP\Exceptions\ImapServerErrorException;
23 use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
24 use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
25 use Webklex\PHPIMAP\Exceptions\NotSupportedCapabilityException;
26 use Webklex\PHPIMAP\Exceptions\ResponseException;
27 use Webklex\PHPIMAP\Exceptions\RuntimeException;
28 use Webklex\PHPIMAP\Query\WhereQuery;
29 use Webklex\PHPIMAP\Support\FolderCollection;
30 use Webklex\PHPIMAP\Traits\HasEvents;
31
32 /**
33 * Class Folder
34 *
35 * @package Webklex\PHPIMAP
36 */
37 class Folder {
38 use HasEvents;
39
40 /**
41 * Client instance
42 *
43 * @var Client
44 */
45 protected Client $client;
46
47 /**
48 * Folder full path
49 *
50 * @var string
51 */
52 public string $path;
53
54 /**
55 * Folder name
56 *
57 * @var string
58 */
59 public string $name;
60
61 /**
62 * Folder full name
63 *
64 * @var string
65 */
66 public string $full_name;
67
68 /**
69 * Children folders
70 *
71 * @var FolderCollection
72 */
73 public FolderCollection $children;
74
75 /**
76 * Delimiter for folder
77 *
78 * @var string
79 */
80 public string $delimiter;
81
82 /**
83 * Indicates if folder can't contain any "children".
84 * CreateFolder won't work on this folder.
85 *
86 * @var boolean
87 */
88 public bool $no_inferiors;
89
90 /**
91 * Indicates if folder is only container, not a mailbox - you can't open it.
92 *
93 * @var boolean
94 */
95 public bool $no_select;
96
97 /**
98 * Indicates if folder is marked. This means that it may contain new messages since the last time it was checked.
99 * Not provided by all IMAP servers.
100 *
101 * @var boolean
102 */
103 public bool $marked;
104
105 /**
106 * Indicates if folder contains any "children".
107 * Not provided by all IMAP servers.
108 *
109 * @var boolean
110 */
111 public bool $has_children;
112
113 /**
114 * Indicates if folder refers to others.
115 * Not provided by all IMAP servers.
116 *
117 * @var boolean
118 */
119 public bool $referral;
120
121 /** @var array */
122 public array $status;
123
124 /**
125 * Folder constructor.
126 * @param Client $client
127 * @param string $folder_name
128 * @param string $delimiter
129 * @param string[] $attributes
130 */
131 public function __construct(Client $client, string $folder_name, string $delimiter, array $attributes) {
132 $this->client = $client;
133
134 $this->events["message"] = $client->getDefaultEvents("message");
135 $this->events["folder"] = $client->getDefaultEvents("folder");
136
137 $this->setDelimiter($delimiter);
138 $this->path = $folder_name;
139 $this->full_name = $this->decodeName($folder_name);
140 $this->name = $this->getSimpleName($this->delimiter, $this->full_name);
141 $this->children = new FolderCollection();
142 $this->has_children = false;
143
144 $this->parseAttributes($attributes);
145 }
146
147 /**
148 * Get a new search query instance
149 * @param string[] $extensions
150 *
151 * @return WhereQuery
152 * @throws ImapBadRequestException
153 * @throws ImapServerErrorException
154 * @throws RuntimeException
155 * @throws AuthFailedException
156 * @throws ConnectionFailedException
157 * @throws ResponseException
158 */
159 public function query(array $extensions = []): WhereQuery {
160 $this->getClient()->checkConnection();
161 $this->getClient()->openFolder($this->path);
162 $extensions = count($extensions) > 0 ? $extensions : $this->getClient()->extensions;
163
164 return new WhereQuery($this->getClient(), $extensions);
165 }
166
167 /**
168 * Get a new search query instance
169 * @param string[] $extensions
170 *
171 * @return WhereQuery
172 * @throws ImapBadRequestException
173 * @throws ImapServerErrorException
174 * @throws RuntimeException
175 * @throws AuthFailedException
176 * @throws ConnectionFailedException
177 * @throws ResponseException
178 */
179 public function search(array $extensions = []): WhereQuery {
180 return $this->query($extensions);
181 }
182
183 /**
184 * Get a new search query instance
185 * @param string[] $extensions
186 *
187 * @return WhereQuery
188 * @throws ImapBadRequestException
189 * @throws ImapServerErrorException
190 * @throws RuntimeException
191 * @throws AuthFailedException
192 * @throws ConnectionFailedException
193 * @throws ResponseException
194 */
195 public function messages(array $extensions = []): WhereQuery {
196 return $this->query($extensions);
197 }
198
199 /**
200 * Determine if folder has children.
201 *
202 * @return bool
203 */
204 public function hasChildren(): bool {
205 return $this->has_children;
206 }
207
208 /**
209 * Set children.
210 * @param FolderCollection $children
211 *
212 * @return Folder
213 */
214 public function setChildren(FolderCollection $children): Folder {
215 $this->children = $children;
216
217 return $this;
218 }
219
220 /**
221 * Get children.
222 *
223 * @return FolderCollection
224 */
225 public function getChildren(): FolderCollection {
226 return $this->children;
227 }
228
229 /**
230 * Decode name.
231 * It converts UTF7-IMAP encoding to UTF-8.
232 * @param $name
233 *
234 * @return string|array|bool|string[]|null
235 */
236 protected function decodeName($name): string|array|bool|null {
237 $parts = [];
238 foreach (explode($this->delimiter, $name) as $item) {
239 $parts[] = EncodingAliases::convert($item, "UTF7-IMAP");
240 }
241
242 return implode($this->delimiter, $parts);
243 }
244
245 /**
246 * Get simple name (without parent folders).
247 * @param $delimiter
248 * @param $full_name
249 *
250 * @return string|bool
251 */
252 protected function getSimpleName($delimiter, $full_name): string|bool {
253 $arr = explode($delimiter, $full_name);
254 return end($arr);
255 }
256
257 /**
258 * Parse attributes and set it to object properties.
259 * @param $attributes
260 */
261 protected function parseAttributes($attributes): void {
262 $this->no_inferiors = in_array('\NoInferiors', $attributes, true) || \in_array('\Noinferiors', $attributes, true);
263 $this->no_select = in_array('\NoSelect', $attributes, true) || \in_array('\Noselect', $attributes, true);
264 $this->marked = in_array('\Marked', $attributes);
265 $this->referral = in_array('\Referral', $attributes);
266 $this->has_children = in_array('\HasChildren', $attributes);
267 }
268
269 /**
270 * Move or rename the current folder
271 * @param string $new_name
272 * @param boolean $expunge
273 *
274 * @return array
275 * @throws ConnectionFailedException
276 * @throws EventNotFoundException
277 * @throws FolderFetchingException
278 * @throws ImapBadRequestException
279 * @throws ImapServerErrorException
280 * @throws RuntimeException
281 * @throws AuthFailedException
282 * @throws ResponseException
283 */
284 public function move(string $new_name, bool $expunge = true): array {
285 $this->client->checkConnection();
286 $status = $this->client->getConnection()->renameFolder($this->full_name, $new_name)->validatedData();
287 if ($expunge) $this->client->expunge();
288
289 $folder = $this->client->getFolder($new_name);
290 $this->dispatch("folder", "moved", $this, $folder);
291
292 return $status;
293 }
294
295 /**
296 * Get a message overview
297 * @param string|null $sequence uid sequence
298 *
299 * @return array
300 * @throws ConnectionFailedException
301 * @throws ImapBadRequestException
302 * @throws ImapServerErrorException
303 * @throws RuntimeException
304 * @throws AuthFailedException
305 * @throws InvalidMessageDateException
306 * @throws MessageNotFoundException
307 * @throws ResponseException
308 */
309 public function overview(?string $sequence = null): array {
310 $this->client->openFolder($this->path);
311 $sequence = $sequence === null ? "1:*" : $sequence;
312 $uid = $this->client->getConfig()->get('options.sequence', IMAP::ST_MSGN);
313 $response = $this->client->getConnection()->overview($sequence, $uid);
314 return $response->validatedData();
315 }
316
317 /**
318 * Append a string message to the current mailbox
319 * @param string $message
320 * @param array|null $options
321 * @param string|Carbon|null $internal_date
322 *
323 * @return array
324 * @throws ConnectionFailedException
325 * @throws ImapBadRequestException
326 * @throws ImapServerErrorException
327 * @throws RuntimeException
328 * @throws AuthFailedException
329 * @throws ResponseException
330 */
331 public function appendMessage(string $message, ?array $options = null, Carbon|string|null $internal_date = null): array {
332 /**
333 * Check if $internal_date is parsed. If it is null it should not be set. Otherwise, the message can't be stored.
334 * If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a
335 * date string that conforms to the rfc2060 specifications for a date_time value or be a Carbon object.
336 */
337
338 if ($internal_date instanceof Carbon) {
339 $internal_date = $internal_date->format('d-M-Y H:i:s O');
340 }
341
342 return $this->client->getConnection()->appendMessage($this->path, $message, $options, $internal_date)->validatedData();
343 }
344
345 /**
346 * Rename the current folder
347 * @param string $new_name
348 * @param boolean $expunge
349 *
350 * @return array
351 * @throws ConnectionFailedException
352 * @throws EventNotFoundException
353 * @throws FolderFetchingException
354 * @throws RuntimeException
355 * @throws ImapBadRequestException
356 * @throws ImapServerErrorException
357 * @throws AuthFailedException
358 * @throws ResponseException
359 */
360 public function rename(string $new_name, bool $expunge = true): array {
361 return $this->move($new_name, $expunge);
362 }
363
364 /**
365 * Delete the current folder
366 * @param boolean $expunge
367 *
368 * @return array
369 * @throws ConnectionFailedException
370 * @throws ImapBadRequestException
371 * @throws ImapServerErrorException
372 * @throws RuntimeException
373 * @throws EventNotFoundException
374 * @throws AuthFailedException
375 * @throws ResponseException
376 */
377 public function delete(bool $expunge = true): array {
378 $status = $this->client->getConnection()->deleteFolder($this->path)->validatedData();
379 if ($this->client->getActiveFolder() == $this->path){
380 $this->client->setActiveFolder();
381 }
382
383 if ($expunge) $this->client->expunge();
384
385 $this->dispatch("folder", "deleted", $this);
386
387 return $status;
388 }
389
390 /**
391 * Subscribe the current folder
392 *
393 * @return array
394 * @throws ConnectionFailedException
395 * @throws ImapBadRequestException
396 * @throws ImapServerErrorException
397 * @throws RuntimeException
398 * @throws AuthFailedException
399 * @throws ResponseException
400 */
401 public function subscribe(): array {
402 $this->client->openFolder($this->path);
403 return $this->client->getConnection()->subscribeFolder($this->path)->validatedData();
404 }
405
406 /**
407 * Unsubscribe the current folder
408 *
409 * @return array
410 * @throws ConnectionFailedException
411 * @throws ImapBadRequestException
412 * @throws ImapServerErrorException
413 * @throws RuntimeException
414 * @throws AuthFailedException
415 * @throws ResponseException
416 */
417 public function unsubscribe(): array {
418 $this->client->openFolder($this->path);
419 return $this->client->getConnection()->unsubscribeFolder($this->path)->validatedData();
420 }
421
422 /**
423 * Idle the current connection
424 * @param callable $callback function(Message $message) gets called if a new message is received
425 * @param integer $timeout max 1740 seconds - recommended by rfc2177 ยง3. Should not be lower than the servers "* OK Still here" message interval
426 *
427 * @throws ConnectionFailedException
428 * @throws RuntimeException
429 * @throws AuthFailedException
430 * @throws NotSupportedCapabilityException
431 * @throws ImapBadRequestException
432 * @throws ImapServerErrorException
433 * @throws ResponseException
434 */
435 public function idle(callable $callback, int $timeout = 300): void {
436 $this->client->setTimeout($timeout);
437
438 if (!in_array("IDLE", $this->client->getConnection()->getCapabilities()->validatedData())) {
439 throw new Exceptions\NotSupportedCapabilityException("IMAP server does not support IDLE");
440 }
441
442 $idle_client = $this->client->clone();
443 $idle_client->connect();
444 $idle_client->openFolder($this->path, true);
445 $idle_client->getConnection()->idle();
446
447 $last_action = Carbon::now()->addSeconds($timeout);
448
449 $sequence = $this->client->getConfig()->get('options.sequence', IMAP::ST_MSGN);
450
451 while (true) {
452 try {
453 // This polymorphic call is fine - Protocol::idle() will throw an exception beforehand
454 $line = $idle_client->getConnection()->nextLine(Response::empty());
455 } catch (Exceptions\RuntimeException $e) {
456 if(strpos($e->getMessage(), "empty response") >= 0 && $idle_client->getConnection()->connected()) {
457 continue;
458 }
459 if(!str_contains($e->getMessage(), "connection closed")) {
460 throw $e;
461 }
462 }
463
464 if (($pos = strpos($line, "EXISTS")) !== false) {
465 $msgn = (int)substr($line, 2, $pos - 2);
466
467 // Check if the stream is still alive or should be considered stale
468 if (!$this->client->isConnected() || $last_action->isBefore(Carbon::now())) {
469 // Reset the connection before interacting with it. Otherwise, the resource might be stale which
470 // would result in a stuck interaction. If you know of a way of detecting a stale resource, please
471 // feel free to improve this logic. I tried a lot but nothing seem to work reliably...
472 // Things that didn't work:
473 // - Closing the resource with fclose()
474 // - Verifying the resource with stream_get_meta_data()
475 // - Bool validating the resource stream (e.g.: (bool)$stream)
476 // - Sending a NOOP command
477 // - Sending a null package
478 // - Reading a null package
479 // - Catching the fs warning
480
481 // This polymorphic call is fine - Protocol::idle() will throw an exception beforehand
482 $this->client->getConnection()->reset();
483 // Establish a new connection
484 $this->client->connect();
485 }
486 $last_action = Carbon::now()->addSeconds($timeout);
487
488 // Always reopen the folder - otherwise the new message number isn't known to the current remote session
489 $this->client->openFolder($this->path, true);
490
491 $message = $this->query()->getMessageByMsgn($msgn);
492 $message->setSequence($sequence);
493 $callback($message);
494
495 $this->dispatch("message", "new", $message);
496 }
497 }
498 }
499
500 /**
501 * Get folder status information from the EXAMINE command
502 *
503 * @return array
504 * @throws ConnectionFailedException
505 * @throws ImapBadRequestException
506 * @throws ImapServerErrorException
507 * @throws RuntimeException
508 * @throws AuthFailedException
509 * @throws ResponseException
510 */
511 public function status(): array {
512 return $this->client->getConnection()->folderStatus($this->path)->validatedData();
513 }
514
515 /**
516 * Get folder status information from the EXAMINE command
517 *
518 * @return array
519 * @throws AuthFailedException
520 * @throws ConnectionFailedException
521 * @throws ImapBadRequestException
522 * @throws ImapServerErrorException
523 * @throws ResponseException
524 * @throws RuntimeException
525 *
526 * @deprecated Use Folder::status() instead
527 */
528 public function getStatus(): array {
529 return $this->status();
530 }
531
532 /**
533 * Load folder status information from the EXAMINE command
534 * @return Folder
535 * @throws AuthFailedException
536 * @throws ConnectionFailedException
537 * @throws ImapBadRequestException
538 * @throws ImapServerErrorException
539 * @throws ResponseException
540 * @throws RuntimeException
541 */
542 public function loadStatus(): Folder {
543 $this->status = $this->examine();
544 return $this;
545 }
546
547 /**
548 * Examine the current folder
549 *
550 * @return array
551 * @throws ConnectionFailedException
552 * @throws ImapBadRequestException
553 * @throws ImapServerErrorException
554 * @throws RuntimeException
555 * @throws AuthFailedException
556 * @throws ResponseException
557 */
558 public function examine(): array {
559 return $this->client->getConnection()->examineFolder($this->path)->validatedData();
560 }
561
562 /**
563 * Select the current folder
564 *
565 * @return array
566 * @throws AuthFailedException
567 * @throws ConnectionFailedException
568 * @throws ImapBadRequestException
569 * @throws ImapServerErrorException
570 * @throws ResponseException
571 * @throws RuntimeException
572 */
573 public function select(): array {
574 return $this->client->getConnection()->selectFolder($this->path)->validatedData();
575 }
576
577 /**
578 * Get the current Client instance
579 *
580 * @return Client
581 */
582 public function getClient(): Client {
583 return $this->client;
584 }
585
586 /**
587 * Set the delimiter
588 * @param $delimiter
589 */
590 public function setDelimiter($delimiter): void {
591 if (in_array($delimiter, [null, '', ' ', false]) === true) {
592 $delimiter = $this->client->getConfig()->get('options.delimiter', '/');
593 }
594
595 $this->delimiter = $delimiter;
596 }
597 }