-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathMessage.php
More file actions
575 lines (482 loc) · 13.8 KB
/
Message.php
File metadata and controls
575 lines (482 loc) · 13.8 KB
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
<?php
namespace DirectoryTree\ImapEngine;
use BackedEnum;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use DirectoryTree\ImapEngine\Connection\Responses\Data\ListData;
use DirectoryTree\ImapEngine\Connection\Responses\MessageResponseParser;
use DirectoryTree\ImapEngine\Exceptions\ImapCapabilityException;
use DirectoryTree\ImapEngine\Support\Str;
use Illuminate\Contracts\Support\Arrayable;
use JsonSerializable;
use ZBateson\MailMimeParser\Header\DateHeader;
use ZBateson\MailMimeParser\Header\HeaderConsts;
use ZBateson\MailMimeParser\Header\IHeader;
use ZBateson\MailMimeParser\Header\IHeaderPart;
use ZBateson\MailMimeParser\Header\Part\AddressPart;
use ZBateson\MailMimeParser\Header\Part\ContainerPart;
use ZBateson\MailMimeParser\Header\Part\NameValuePart;
class Message implements Arrayable, JsonSerializable, MessageInterface
{
use HasFlags, HasParsedMessage;
/**
* The parsed body structure.
*/
protected ?BodyStructureCollection $bodyStructure = null;
/**
* Constructor.
*/
public function __construct(
protected FolderInterface $folder,
protected int $uid,
protected array $flags,
protected string $head,
protected string $body,
protected ?int $size = null,
protected ?ListData $bodyStructureData = null,
) {}
/**
* Get the names of properties that should be serialized.
*/
public function __sleep(): array
{
// We don't want to serialize the parsed message.
return ['folder', 'uid', 'flags', 'head', 'body', 'size'];
}
/**
* Get the message's folder.
*/
public function folder(): FolderInterface
{
return $this->folder;
}
/**
* Get the message's identifier.
*/
public function uid(): int
{
return $this->uid;
}
/**
* Get the message's size in bytes (RFC822.SIZE).
*/
public function size(): ?int
{
return $this->size;
}
/**
* Get the message's flags.
*/
public function flags(): array
{
return $this->flags;
}
/**
* Get the message's raw headers.
*/
public function head(bool $fetch = false): string
{
if (! $this->head && $fetch) {
$this->head = $this->fetchHead() ?? '';
}
return $this->head;
}
/**
* Determine if the message has headers.
*/
public function hasHead(): bool
{
return ! empty($this->head);
}
/**
* Get the message's raw body.
*/
public function body(): string
{
return $this->body;
}
/**
* Determine if the message has contents.
*/
public function hasBody(): bool
{
return ! empty($this->body);
}
/**
* Get the message's body structure.
*/
public function bodyStructure(bool $fetch = false): ?BodyStructureCollection
{
if ($this->bodyStructure) {
return $this->bodyStructure;
}
if (! $this->bodyStructureData && $fetch) {
$this->bodyStructureData = $this->fetchBodyStructureData();
}
if (! $tokens = $this->bodyStructureData?->tokens()) {
return null;
}
// If the first token is a list, it's a multipart message.
return $this->bodyStructure = head($tokens) instanceof ListData
? BodyStructureCollection::fromListData($this->bodyStructureData)
: new BodyStructureCollection(parts: [BodyStructurePart::fromListData($this->bodyStructureData)]);
}
/**
* Determine if the message has body structure data.
*/
public function hasBodyStructure(): bool
{
return (bool) $this->bodyStructureData;
}
/**
* {@inheritDoc}
*/
public function is(MessageInterface $message): bool
{
return $message instanceof self
&& $this->uid === $message->uid
&& $this->folder->is($message->folder);
}
/**
* Add or remove a flag from the message.
*/
public function flag(BackedEnum|string $flag, string $operation, bool $expunge = false): void
{
$flag = Str::enum($flag);
$this->folder->mailbox()
->connection()
->store($flag, $this->uid, mode: $operation);
if ($expunge) {
$this->folder->expunge();
}
$this->flags = match ($operation) {
'+' => array_unique(array_merge($this->flags, [$flag])),
'-' => array_diff($this->flags, [$flag]),
};
}
/**
* Copy the message to the given folder.
*/
public function copy(string $folder): ?int
{
$mailbox = $this->folder->mailbox();
$capabilities = $mailbox->capabilities();
if (! in_array('UIDPLUS', $capabilities)) {
throw new ImapCapabilityException(
'Unable to copy message. IMAP server does not support UIDPLUS capability'
);
}
$response = $mailbox->connection()->copy($folder, $this->uid);
return MessageResponseParser::getUidFromCopy($response);
}
/**
* Move the message to the given folder.
*
* @throws ImapCapabilityException
*/
public function move(string $folder, bool $expunge = false): ?int
{
$mailbox = $this->folder->mailbox();
$capabilities = $mailbox->capabilities();
switch (true) {
case in_array('MOVE', $capabilities):
$response = $mailbox->connection()->move($folder, $this->uid);
if ($expunge) {
$this->folder->expunge();
}
return MessageResponseParser::getUidFromCopy($response);
case in_array('UIDPLUS', $capabilities):
$uid = $this->copy($folder);
$this->delete($expunge);
return $uid;
default:
throw new ImapCapabilityException(
'Unable to move message. IMAP server does not support MOVE or UIDPLUS capabilities'
);
}
}
/**
* Get a header from the message.
*/
public function header(string $name, int $offset = 0, bool $fetch = false): ?IHeader
{
if ($fetch && ! $this->hasHead()) {
$this->head(fetch: true);
}
if ($this->isEmpty()) {
return null;
}
return $this->parse()->getHeader($name, $offset);
}
/**
* Get the message date and time.
*/
public function date(bool $fetch = false): ?CarbonInterface
{
if (! $header = $this->header(HeaderConsts::DATE, fetch: $fetch)) {
return null;
}
if (! $header instanceof DateHeader) {
return null;
}
if (! $date = $header->getDateTime()) {
return null;
}
return Carbon::instance($date);
}
/**
* Get the message's message-id.
*/
public function messageId(bool $fetch = false): ?string
{
return $this->header(HeaderConsts::MESSAGE_ID, fetch: $fetch)?->getValue();
}
/**
* Get the message's subject.
*/
public function subject(bool $fetch = false): ?string
{
return $this->header(HeaderConsts::SUBJECT, fetch: $fetch)?->getValue();
}
/**
* Get the FROM address.
*/
public function from(bool $fetch = false): ?Address
{
return head($this->addresses(HeaderConsts::FROM, fetch: $fetch)) ?: null;
}
/**
* Get the SENDER address.
*/
public function sender(bool $fetch = false): ?Address
{
return head($this->addresses(HeaderConsts::SENDER, fetch: $fetch)) ?: null;
}
/**
* Get the REPLY-TO address.
*/
public function replyTo(bool $fetch = false): ?Address
{
return head($this->addresses(HeaderConsts::REPLY_TO, fetch: $fetch)) ?: null;
}
/**
* Get the IN-REPLY-TO message identifier(s).
*
* @return string[]
*/
public function inReplyTo(bool $fetch = false): array
{
$parts = $this->header(HeaderConsts::IN_REPLY_TO, fetch: $fetch)?->getParts() ?? [];
$values = array_map(fn (IHeaderPart $part) => $part->getValue(), $parts);
return array_values(array_filter($values));
}
/**
* Get the TO addresses.
*
* @return Address[]
*/
public function to(bool $fetch = false): array
{
return $this->addresses(HeaderConsts::TO, fetch: $fetch);
}
/**
* Get the CC addresses.
*
* @return Address[]
*/
public function cc(bool $fetch = false): array
{
return $this->addresses(HeaderConsts::CC, fetch: $fetch);
}
/**
* Get the BCC addresses.
*
* @return Address[]
*/
public function bcc(bool $fetch = false): array
{
return $this->addresses(HeaderConsts::BCC, fetch: $fetch);
}
/**
* Get addresses from the given header.
*
* @return Address[]
*/
public function addresses(string $header, bool $fetch = false): array
{
$parts = $this->header($header, fetch: $fetch)?->getParts() ?? [];
$addresses = array_map(fn (IHeaderPart $part) => match (true) {
$part instanceof AddressPart => new Address($part->getEmail(), $part->getName()),
$part instanceof NameValuePart => new Address($part->getName(), $part->getValue()),
$part instanceof ContainerPart => new Address($part->getValue(), ''),
default => null,
}, $parts);
return array_filter($addresses);
}
/**
* Get the message's text content.
*/
public function text(bool $fetch = false): ?string
{
if ($fetch && ! $this->hasBody()) {
if ($part = $this->bodyStructure(fetch: true)?->text()) {
return Support\BodyPartDecoder::text($part, $this->bodyPart($part->partNumber()));
}
}
if ($this->isEmpty()) {
return null;
}
return $this->parse()->getTextContent();
}
/**
* Get the message's HTML content.
*/
public function html(bool $fetch = false): ?string
{
if ($fetch && ! $this->hasBody()) {
if ($part = $this->bodyStructure(fetch: true)?->html()) {
return Support\BodyPartDecoder::text($part, $this->bodyPart($part->partNumber()));
}
}
if ($this->isEmpty()) {
return null;
}
return $this->parse()->getHtmlContent();
}
/**
* Get the message's attachments.
*
* @return Attachment[]
*/
public function attachments(bool $fetch = false): array
{
if ($fetch && ! $this->hasBody()) {
return Attachment::lazy($this);
}
if ($this->isEmpty()) {
return [];
}
return Attachment::parsed($this);
}
/**
* Determine if the message has attachments.
*/
public function hasAttachments(): bool
{
return $this->attachmentCount() > 0;
}
/**
* Get the count of attachments.
*/
public function attachmentCount(): int
{
if ($this->isEmpty()) {
return 0;
}
return $this->parse()->getAttachmentCount();
}
/**
* Fetch a specific body part by part number.
*/
public function bodyPart(string $partNumber, bool $peek = true): ?string
{
$response = $this->folder->mailbox()
->connection()
->bodyPart($partNumber, $this->uid, $peek);
if ($response->isEmpty()) {
return null;
}
$data = $response->first()->tokenAt(3);
if (! $data instanceof ListData) {
return null;
}
return $data->lookup("[$partNumber]")?->value;
}
/**
* Delete the message.
*/
public function delete(bool $expunge = false): void
{
$this->markDeleted($expunge);
}
/**
* Restore the message.
*/
public function restore(): void
{
$this->unmarkDeleted();
}
/**
* Get the array representation of the message.
*/
public function toArray(): array
{
return [
'uid' => $this->uid,
'flags' => $this->flags,
'head' => $this->head,
'body' => $this->body,
'size' => $this->size,
];
}
/**
* Get the string representation of the message.
*/
public function __toString(): string
{
return implode("\r\n\r\n", array_filter([
rtrim($this->head),
ltrim($this->body),
]));
}
/**
* Get the JSON representation of the message.
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* Determine if the message is empty.
*/
public function isEmpty(): bool
{
return ! $this->hasHead() && ! $this->hasBody();
}
/**
* Fetch the headers from the server.
*/
protected function fetchHead(): ?string
{
$response = $this->folder
->mailbox()
->connection()
->bodyHeader($this->uid);
if ($response->isEmpty()) {
return null;
}
$data = $response->first()->tokenAt(3);
if (! $data instanceof ListData) {
return null;
}
return $data->lookup('[HEADER]')?->value;
}
/**
* Fetch the body structure data from the server.
*/
protected function fetchBodyStructureData(): ?ListData
{
$response = $this->folder
->mailbox()
->connection()
->bodyStructure($this->uid);
if ($response->isEmpty()) {
return null;
}
$data = $response->first()->tokenAt(3);
if (! $data instanceof ListData) {
return null;
}
return $data->lookup('BODYSTRUCTURE');
}
}