forked from Webklex/php-imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Attachment.php
executable file
·455 lines (401 loc) · 12.7 KB
/
Attachment.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
<?php
/*
* File: Attachment.php
* Category: -
* Author: M. Goldenbaum
* Created: 16.03.18 19:37
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PHPIMAP;
use Illuminate\Support\Str;
use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
use Webklex\PHPIMAP\Support\Masks\AttachmentMask;
/**
* Class Attachment
*
* @package Webklex\PHPIMAP
*
* @property integer part_number
* @property integer size
* @property string content
* @property string type
* @property string content_type
* @property string id
* @property string hash
* @property string name
* @property string description
* @property string filename
* @property ?string disposition
* @property string img_src
*
* @method integer getPartNumber()
* @method integer setPartNumber(integer $part_number)
* @method string getContent()
* @method string setContent(string $content)
* @method string getType()
* @method string setType(string $type)
* @method string getContentType()
* @method string setContentType(string $content_type)
* @method string getId()
* @method string setId(string $id)
* @method string getHash()
* @method string setHash(string $hash)
* @method string getSize()
* @method string setSize(integer $size)
* @method string getName()
* @method string getDisposition()
* @method string setDisposition(string $disposition)
* @method string setImgSrc(string $img_src)
*/
class Attachment {
/**
* @var Message $message
*/
protected Message $message;
/**
* Used config
*
* @var Config $config
*/
protected Config $config;
/**
* Attachment options
*
* @var array $options
*/
protected array $options = [];
/** @var Part $part */
protected Part $part;
/**
* Attribute holder
*
* @var array $attributes
*/
protected array $attributes = [
'content' => null,
'hash' => null,
'type' => null,
'part_number' => 0,
'content_type' => null,
'id' => null,
'name' => null,
'filename' => null,
'description' => null,
'disposition' => null,
'img_src' => null,
'size' => null,
];
/**
* Default mask
*
* @var string $mask
*/
protected string $mask = AttachmentMask::class;
/**
* Attachment constructor.
* @param Message $message
* @param Part $part
*/
public function __construct(Message $message, Part $part) {
$this->message = $message;
$this->config = $this->message->getConfig();
$this->options = $this->config->get('options');
$this->part = $part;
$this->part_number = $part->part_number;
if ($this->message->getClient()) {
$default_mask = $this->message->getClient()?->getDefaultAttachmentMask();
if ($default_mask != null) {
$this->mask = $default_mask;
}
} else {
$default_mask = $this->config->getMask("attachment");
if ($default_mask != "") {
$this->mask = $default_mask;
}
}
$this->findType();
$this->fetch();
}
/**
* Call dynamic attribute setter and getter methods
* @param string $method
* @param array $arguments
*
* @return mixed
* @throws MethodNotFoundException
*/
public function __call(string $method, array $arguments) {
if (strtolower(substr($method, 0, 3)) === 'get') {
$name = Str::snake(substr($method, 3));
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
} elseif (strtolower(substr($method, 0, 3)) === 'set') {
$name = Str::snake(substr($method, 3));
$this->attributes[$name] = array_pop($arguments);
return $this->attributes[$name];
}
throw new MethodNotFoundException("Method " . self::class . '::' . $method . '() is not supported');
}
/**
* Magic setter
* @param $name
* @param $value
*
* @return mixed
*/
public function __set($name, $value) {
$this->attributes[$name] = $value;
return $this->attributes[$name];
}
/**
* magic getter
* @param $name
*
* @return mixed|null
*/
public function __get($name) {
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
}
/**
* Determine the structure type
*/
protected function findType(): void {
$this->type = match ($this->part->type) {
IMAP::ATTACHMENT_TYPE_MESSAGE => 'message',
IMAP::ATTACHMENT_TYPE_APPLICATION => 'application',
IMAP::ATTACHMENT_TYPE_AUDIO => 'audio',
IMAP::ATTACHMENT_TYPE_IMAGE => 'image',
IMAP::ATTACHMENT_TYPE_VIDEO => 'video',
IMAP::ATTACHMENT_TYPE_MODEL => 'model',
IMAP::ATTACHMENT_TYPE_TEXT => 'text',
IMAP::ATTACHMENT_TYPE_MULTIPART => 'multipart',
default => 'other',
};
}
/**
* Fetch the given attachment
*/
protected function fetch(): void {
$content = $this->part->content;
$this->content_type = $this->part->content_type;
$this->content = $this->message->decodeString($content, $this->part->encoding);
// Create a hash of the raw part - this can be used to identify the attachment in the message context. However,
// it is not guaranteed to be unique and collisions are possible.
// Some additional online resources:
// - https://en.wikipedia.org/wiki/Hash_collision
// - https://www.php.net/manual/en/function.hash.php
// - https://php.watch/articles/php-hash-benchmark
// Benchmark speeds:
// -xxh3 ~15.19(GB/s) (requires php-xxhash extension or >= php8.1)
// -crc32c ~14.12(GB/s)
// -sha256 ~0.25(GB/s)
// xxh3 would be nice to use, because of its extra speed and 32 instead of 8 bytes, but it is not compatible with
// php < 8.1. crc32c is the next fastest and is compatible with php >= 5.1. sha256 is the slowest, but is compatible
// with php >= 5.1 and is the most likely to be unique. crc32c is the best compromise between speed and uniqueness.
// Unique enough for our purposes, but not so slow that it could be a bottleneck.
$this->hash = hash("crc32c", $this->part->getHeader()->raw."\r\n\r\n".$this->part->content);
if (($id = $this->part->id) !== null) {
$this->id = str_replace(['<', '>'], '', $id);
}else {
$this->id = $this->hash;
}
$this->size = $this->part->bytes;
$this->disposition = $this->part->disposition;
if (($filename = $this->part->filename) !== null) {
$this->filename = $this->decodeName($filename);
}
if (($description = $this->part->description) !== null) {
$this->description = $this->part->getHeader()->decode($description);
}
if (($name = $this->part->name) !== null) {
$this->name = $this->decodeName($name);
}
if (IMAP::ATTACHMENT_TYPE_MESSAGE == $this->part->type) {
if ($this->part->ifdescription) {
if (!$this->name) {
$this->name = $this->part->description;
}
} else if (!$this->name) {
$this->name = $this->part->subtype;
}
}
$this->attributes = array_merge($this->part->getHeader()->getAttributes(), $this->attributes);
if (!$this->filename) {
$this->filename = $this->hash;
}
if (!$this->name && $this->filename != "") {
$this->name = $this->filename;
}
}
/**
* Save the attachment content to your filesystem
* @param string $path
* @param string|null $filename
*
* @return boolean
*/
public function save(string $path, ?string $filename = null): bool {
$filename = $filename ? $this->decodeName($filename) : $this->filename;
return file_put_contents($path . DIRECTORY_SEPARATOR . $filename, $this->getContent()) !== false;
}
/**
* Decode a given name
* @param string|null $name
*
* @return string
*/
public function decodeName(?string $name): string {
if ($name !== null) {
if (str_contains($name, "''")) {
$parts = explode("''", $name);
if (EncodingAliases::has($parts[0])) {
$name = implode("''", array_slice($parts, 1));
}
}
$decoder = $this->options['decoder']['message'];
if (preg_match('/=\?([^?]+)\?(Q|B)\?(.+)\?=/i', $name, $matches)) {
$name = $this->part->getHeader()->decode($name);
} elseif ($decoder === 'utf-8' && extension_loaded('imap')) {
$name = \imap_utf8($name);
}
// check if $name is url encoded
if (preg_match('/%[0-9A-F]{2}/i', $name)) {
$name = urldecode($name);
}
// sanitize $name
// order of '..' is important
return str_replace(['\\', '/', chr(0), ':', '..'], '', $name);
}
return "";
}
/**
* Get the attachment mime type
*
* @return string|null
*/
public function getMimeType(): ?string {
return (new \finfo())->buffer($this->getContent(), FILEINFO_MIME_TYPE);
}
/**
* Try to guess the attachment file extension
*
* @return string|null
*/
public function getExtension(): ?string {
$extension = null;
$guesser = "\Symfony\Component\Mime\MimeTypes";
if (class_exists($guesser) !== false) {
/** @var Symfony\Component\Mime\MimeTypes $guesser */
$extensions = $guesser::getDefault()->getExtensions($this->getMimeType());
$extension = $extensions[0] ?? null;
}
if ($extension === null) {
$deprecated_guesser = "\Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser";
if (class_exists($deprecated_guesser) !== false) {
/** @var \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser $deprecated_guesser */
$extension = $deprecated_guesser::getInstance()->guess($this->getMimeType());
}
}
if ($extension === null) {
$parts = explode(".", $this->filename);
$extension = count($parts) > 1 ? end($parts) : null;
}
if ($extension === null) {
$parts = explode(".", $this->name);
$extension = count($parts) > 1 ? end($parts) : null;
}
return $extension;
}
/**
* Get all attributes
*
* @return array
*/
public function getAttributes(): array {
return $this->attributes;
}
/**
* @return Message
*/
public function getMessage(): Message {
return $this->message;
}
/**
* Set the default mask
* @param $mask
*
* @return $this
*/
public function setMask($mask): Attachment {
if (class_exists($mask)) {
$this->mask = $mask;
}
return $this;
}
/**
* Get the used default mask
*
* @return string
*/
public function getMask(): string {
return $this->mask;
}
/**
* Get the attachment options
* @return array
*/
public function getOptions(): array {
return $this->options;
}
/**
* Set the attachment options
* @param array $options
*
* @return $this
*/
public function setOptions(array $options): Attachment {
$this->options = $options;
return $this;
}
/**
* Get the used config
*
* @return Config
*/
public function getConfig(): Config {
return $this->config;
}
/**
* Set the used config
* @param Config $config
*
* @return $this
*/
public function setConfig(Config $config): Attachment {
$this->config = $config;
return $this;
}
/**
* Get a masked instance by providing a mask name
* @param string|null $mask
*
* @return mixed
* @throws MaskNotFoundException
*/
public function mask(string $mask = null): mixed {
$mask = $mask !== null ? $mask : $this->mask;
if (class_exists($mask)) {
return new $mask($this);
}
throw new MaskNotFoundException("Unknown mask provided: " . $mask);
}
}