forked from Webklex/php-imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Folder.php
executable file
·615 lines (546 loc) · 18.5 KB
/
Folder.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
<?php
/*
* File: Folder.php
* Category: -
* Author: M. Goldenbaum
* Created: 19.01.17 22:21
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PHPIMAP;
use Carbon\Carbon;
use Webklex\PHPIMAP\Connection\Protocols\Response;
use Webklex\PHPIMAP\Exceptions\AuthFailedException;
use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
use Webklex\PHPIMAP\Exceptions\EventNotFoundException;
use Webklex\PHPIMAP\Exceptions\FolderFetchingException;
use Webklex\PHPIMAP\Exceptions\ImapBadRequestException;
use Webklex\PHPIMAP\Exceptions\ImapServerErrorException;
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
use Webklex\PHPIMAP\Exceptions\NotSupportedCapabilityException;
use Webklex\PHPIMAP\Exceptions\ResponseException;
use Webklex\PHPIMAP\Exceptions\RuntimeException;
use Webklex\PHPIMAP\Query\WhereQuery;
use Webklex\PHPIMAP\Support\FolderCollection;
use Webklex\PHPIMAP\Traits\HasEvents;
/**
* Class Folder
*
* @package Webklex\PHPIMAP
*/
class Folder {
use HasEvents;
/**
* Client instance
*
* @var Client
*/
protected Client $client;
/**
* Folder full path
*
* @var string
*/
public string $path;
/**
* Folder name
*
* @var string
*/
public string $name;
/**
* Folder full name
*
* @var string
*/
public string $full_name;
/**
* Children folders
*
* @var FolderCollection
*/
public FolderCollection $children;
/**
* Delimiter for folder
*
* @var string
*/
public string $delimiter;
/**
* Indicates if folder can't contain any "children".
* CreateFolder won't work on this folder.
*
* @var boolean
*/
public bool $no_inferiors;
/**
* Indicates if folder is only container, not a mailbox - you can't open it.
*
* @var boolean
*/
public bool $no_select;
/**
* Indicates if folder is marked. This means that it may contain new messages since the last time it was checked.
* Not provided by all IMAP servers.
*
* @var boolean
*/
public bool $marked;
/**
* Indicates if folder contains any "children".
* Not provided by all IMAP servers.
*
* @var boolean
*/
public bool $has_children;
/**
* Indicates if folder refers to others.
* Not provided by all IMAP servers.
*
* @var boolean
*/
public bool $referral;
/** @var array */
public array $status;
/** @var array */
public array $attributes = [];
const SPECIAL_ATTRIBUTES = [
'haschildren' => ['\haschildren'],
'hasnochildren' => ['\hasnochildren'],
'template' => ['\template', '\templates'],
'inbox' => ['\inbox'],
'sent' => ['\sent'],
'drafts' => ['\draft', '\drafts'],
'archive' => ['\archive', '\archives'],
'trash' => ['\trash'],
'junk' => ['\junk', '\spam'],
];
/**
* Folder constructor.
* @param Client $client
* @param string $folder_name
* @param string $delimiter
* @param string[] $attributes
*/
public function __construct(Client $client, string $folder_name, string $delimiter, array $attributes) {
$this->client = $client;
$this->events["message"] = $client->getDefaultEvents("message");
$this->events["folder"] = $client->getDefaultEvents("folder");
$this->setDelimiter($delimiter);
$this->path = $folder_name;
$this->full_name = $this->decodeName($folder_name);
$this->name = $this->getSimpleName($this->delimiter, $this->full_name);
$this->children = new FolderCollection();
$this->has_children = false;
$this->parseAttributes($attributes);
}
/**
* Get a new search query instance
* @param string[] $extensions
*
* @return WhereQuery
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ResponseException
*/
public function query(array $extensions = []): WhereQuery {
$this->getClient()->checkConnection();
$this->getClient()->openFolder($this->path);
$extensions = count($extensions) > 0 ? $extensions : $this->getClient()->extensions;
return new WhereQuery($this->getClient(), $extensions);
}
/**
* Get a new search query instance
* @param string[] $extensions
*
* @return WhereQuery
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ResponseException
*/
public function search(array $extensions = []): WhereQuery {
return $this->query($extensions);
}
/**
* Get a new search query instance
* @param string[] $extensions
*
* @return WhereQuery
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ResponseException
*/
public function messages(array $extensions = []): WhereQuery {
return $this->query($extensions);
}
/**
* Determine if folder has children.
*
* @return bool
*/
public function hasChildren(): bool {
return $this->has_children;
}
/**
* Set children.
* @param FolderCollection $children
*
* @return Folder
*/
public function setChildren(FolderCollection $children): Folder {
$this->children = $children;
return $this;
}
/**
* Get children.
*
* @return FolderCollection
*/
public function getChildren(): FolderCollection {
return $this->children;
}
/**
* Decode name.
* It converts UTF7-IMAP encoding to UTF-8.
* @param $name
*
* @return string|array|bool|string[]|null
*/
protected function decodeName($name): string|array|bool|null {
$parts = [];
foreach(explode($this->delimiter, $name) as $item) {
$parts[] = EncodingAliases::convert($item, "UTF7-IMAP");
}
return implode($this->delimiter, $parts);
}
/**
* Get simple name (without parent folders).
* @param $delimiter
* @param $full_name
*
* @return string|bool
*/
protected function getSimpleName($delimiter, $full_name): string|bool {
$arr = explode($delimiter, $full_name);
return end($arr);
}
/**
* Parse attributes and set it to object properties.
* @param $attributes
*/
protected function parseAttributes($attributes): void {
$this->no_inferiors = in_array('\NoInferiors', $attributes);
$this->no_select = in_array('\NoSelect', $attributes);
$this->marked = in_array('\Marked', $attributes);
$this->referral = in_array('\Referral', $attributes);
$this->has_children = in_array('\HasChildren', $attributes);
array_map(function($el) {
foreach(self::SPECIAL_ATTRIBUTES as $key => $attribute) {
if(in_array(strtolower($el), $attribute)){
$this->attributes[] = $key;
}
}
}, $attributes);
}
/**
* Move or rename the current folder
* @param string $new_name
* @param boolean $expunge
*
* @return array
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws FolderFetchingException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function move(string $new_name, bool $expunge = true): array {
$this->client->checkConnection();
$status = $this->client->getConnection()->renameFolder($this->full_name, $new_name)->validatedData();
if($expunge) $this->client->expunge();
$folder = $this->client->getFolder($new_name);
$event = $this->getEvent("folder", "moved");
$event::dispatch($this, $folder);
return $status;
}
/**
* Get a message overview
* @param string|null $sequence uid sequence
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws InvalidMessageDateException
* @throws MessageNotFoundException
* @throws ResponseException
*/
public function overview(?string $sequence = null): array {
$this->client->openFolder($this->path);
$sequence = $sequence === null ? "1:*" : $sequence;
$uid = $this->client->getConfig()->get('options.sequence', IMAP::ST_MSGN);
$response = $this->client->getConnection()->overview($sequence, $uid);
return $response->validatedData();
}
/**
* Append a string message to the current mailbox
* @param string $message
* @param array|null $options
* @param string|Carbon|null $internal_date
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function appendMessage(string $message, ?array $options = null, Carbon|string|null $internal_date = null): array {
/**
* Check if $internal_date is parsed. If it is null it should not be set. Otherwise, the message can't be stored.
* If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a
* date string that conforms to the rfc2060 specifications for a date_time value or be a Carbon object.
*/
if($internal_date instanceof Carbon){
$internal_date = $internal_date->format('d-M-Y H:i:s O');
}
return $this->client->getConnection()->appendMessage($this->path, $message, $options, $internal_date)->validatedData();
}
/**
* Rename the current folder
* @param string $new_name
* @param boolean $expunge
*
* @return array
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws FolderFetchingException
* @throws RuntimeException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws AuthFailedException
* @throws ResponseException
*/
public function rename(string $new_name, bool $expunge = true): array {
return $this->move($new_name, $expunge);
}
/**
* Delete the current folder
* @param boolean $expunge
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws EventNotFoundException
* @throws AuthFailedException
* @throws ResponseException
*/
public function delete(bool $expunge = true): array {
$status = $this->client->getConnection()->deleteFolder($this->path)->validatedData();
if($this->client->getActiveFolder() == $this->path){
$this->client->setActiveFolder();
}
if($expunge) $this->client->expunge();
$event = $this->getEvent("folder", "deleted");
$event::dispatch($this);
return $status;
}
/**
* Subscribe the current folder
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function subscribe(): array {
$this->client->openFolder($this->path);
return $this->client->getConnection()->subscribeFolder($this->path)->validatedData();
}
/**
* Unsubscribe the current folder
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function unsubscribe(): array {
$this->client->openFolder($this->path);
return $this->client->getConnection()->unsubscribeFolder($this->path)->validatedData();
}
/**
* Idle the current connection
* @param callable $callback function(Message $message) gets called if a new message is received
* @param integer $timeout max 1740 seconds - recommended by rfc2177 §3. Should not be lower than the servers "* OK Still here" message interval
*
* @throws ConnectionFailedException
* @throws RuntimeException
* @throws AuthFailedException
* @throws NotSupportedCapabilityException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws ResponseException
*/
public function idle(callable $callback, int $timeout = 300): void {
$this->client->setTimeout($timeout);
if(!in_array("IDLE", $this->client->getConnection()->getCapabilities()->validatedData())){
throw new Exceptions\NotSupportedCapabilityException("IMAP server does not support IDLE");
}
$idle_client = $this->client->clone();
$idle_client->connect();
$idle_client->openFolder($this->path, true);
$idle_client->getConnection()->idle();
$last_action = Carbon::now()->addSeconds($timeout);
$sequence = $this->client->getConfig()->get('options.sequence', IMAP::ST_MSGN);
while(true) {
// This polymorphic call is fine - Protocol::idle() will throw an exception beforehand
$line = $idle_client->getConnection()->nextLine(Response::empty());
if(($pos = strpos($line, "EXISTS")) !== false){
$msgn = (int)substr($line, 2, $pos - 2);
// Check if the stream is still alive or should be considered stale
if(!$this->client->isConnected() || $last_action->isBefore(Carbon::now())){
// Reset the connection before interacting with it. Otherwise, the resource might be stale which
// would result in a stuck interaction. If you know of a way of detecting a stale resource, please
// feel free to improve this logic. I tried a lot but nothing seem to work reliably...
// Things that didn't work:
// - Closing the resource with fclose()
// - Verifying the resource with stream_get_meta_data()
// - Bool validating the resource stream (e.g.: (bool)$stream)
// - Sending a NOOP command
// - Sending a null package
// - Reading a null package
// - Catching the fs warning
// This polymorphic call is fine - Protocol::idle() will throw an exception beforehand
$this->client->getConnection()->reset();
// Establish a new connection
$this->client->connect();
}
$last_action = Carbon::now()->addSeconds($timeout);
// Always reopen the folder - otherwise the new message number isn't known to the current remote session
$this->client->openFolder($this->path, true);
$message = $this->query()->getMessageByMsgn($msgn);
$message->setSequence($sequence);
$callback($message);
$event = $this->getEvent("message", "new");
$event::dispatch($message);
}
}
}
/**
* Get folder status information from the EXAMINE command
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function status(): array {
return $this->client->getConnection()->folderStatus($this->path)->validatedData();
}
/**
* Get folder status information from the EXAMINE command
*
* @return array
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws ResponseException
* @throws RuntimeException
*
* @deprecated Use Folder::status() instead
*/
public function getStatus(): array {
return $this->status();
}
/**
* Load folder status information from the EXAMINE command
* @return Folder
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws ResponseException
* @throws RuntimeException
*/
public function loadStatus(): Folder {
$this->status = $this->examine();
return $this;
}
/**
* Examine the current folder
*
* @return array
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws AuthFailedException
* @throws ResponseException
*/
public function examine(): array {
return $this->client->getConnection()->examineFolder($this->path)->validatedData();
}
/**
* Select the current folder
*
* @return array
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws ResponseException
* @throws RuntimeException
*/
public function select(): array {
return $this->client->getConnection()->selectFolder($this->path)->validatedData();
}
/**
* Get the current Client instance
*
* @return Client
*/
public function getClient(): Client {
return $this->client;
}
/**
* Set the delimiter
* @param $delimiter
*/
public function setDelimiter($delimiter): void {
if(in_array($delimiter, [null, '', ' ', false]) === true){
$delimiter = $this->client->getConfig()->get('options.delimiter', '/');
}
$this->delimiter = $delimiter;
}
}