Debian Codegraph @

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

raw symbols SCIP
1 <?php
2 /*
3 * File: Attachment.php
4 * Category: -
5 * Author: M. Goldenbaum
6 * Created: 16.03.18 19:37
7 * Updated: -
8 *
9 * Description:
10 * -
11 */
12
13 namespace Webklex\PHPIMAP;
14
15 use Illuminate\Support\Str;
16 use Webklex\PHPIMAP\Decoder\DecoderInterface;
17 use Webklex\PHPIMAP\Exceptions\DecoderNotFoundException;
18 use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
19 use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
20 use Webklex\PHPIMAP\Support\Masks\AttachmentMask;
21
22 /**
23 * Class Attachment
24 *
25 * @package Webklex\PHPIMAP
26 *
27 * @property integer $part_number
28 * @property integer $size
29 * @property string $content
30 * @property string $type
31 * @property string $content_type
32 * @property string $id
33 * @property string $hash
34 * @property string $name
35 * @property string $description
36 * @property string $filename
37 * @property ?string $disposition
38 * @property string $img_src
39 *
40 * @method integer getPartNumber()
41 * @method integer setPartNumber(integer $part_number)
42 * @method string getContent()
43 * @method string setContent(string $content)
44 * @method string getType()
45 * @method string setType(string $type)
46 * @method string getContentType()
47 * @method string setContentType(string $content_type)
48 * @method string getId()
49 * @method string setId(string $id)
50 * @method string getHash()
51 * @method string setHash(string $hash)
52 * @method string getSize()
53 * @method string setSize(integer $size)
54 * @method string getName()
55 * @method string getDisposition()
56 * @method string setDisposition(string $disposition)
57 * @method string setImgSrc(string $img_src)
58 */
59 class Attachment {
60
61 /**
62 * @var Message $message
63 */
64 protected Message $message;
65
66 /**
67 * Used config
68 *
69 * @var Config $config
70 */
71 protected Config $config;
72
73 /**
74 * Attachment options
75 *
76 * @var array $options
77 */
78 protected array $options = [];
79
80 /** @var Part $part */
81 protected Part $part;
82
83 /**
84 * Decoder instance
85 *
86 * @var DecoderInterface $decoder
87 */
88 protected DecoderInterface $decoder;
89
90 /**
91 * Attribute holder
92 *
93 * @var array $attributes
94 */
95 protected array $attributes = [
96 'content' => null,
97 'hash' => null,
98 'type' => null,
99 'part_number' => 0,
100 'content_type' => null,
101 'id' => null,
102 'name' => null,
103 'filename' => null,
104 'description' => null,
105 'disposition' => null,
106 'img_src' => null,
107 'size' => null,
108 ];
109
110 /**
111 * Default mask
112 *
113 * @var string $mask
114 */
115 protected string $mask = AttachmentMask::class;
116
117 /**
118 * Attachment constructor.
119 * @param Message $message
120 * @param Part $part
121 * @throws DecoderNotFoundException
122 */
123 public function __construct(Message $message, Part $part) {
124 $this->message = $message;
125 $this->config = $this->message->getConfig();
126 $this->options = $this->config->get('options');
127 $this->decoder = $this->config->getDecoder("attachment");
128
129 $this->part = $part;
130 $this->part_number = $part->part_number;
131
132 if ($this->message->getClient()) {
133 $default_mask = $this->message->getClient()?->getDefaultAttachmentMask();
134 if ($default_mask != null) {
135 $this->mask = $default_mask;
136 }
137 } else {
138 $default_mask = $this->config->getMask("attachment");
139 if ($default_mask != "") {
140 $this->mask = $default_mask;
141 }
142 }
143
144 $this->findType();
145 $this->fetch();
146 }
147
148 /**
149 * Call dynamic attribute setter and getter methods
150 * @param string $method
151 * @param array $arguments
152 *
153 * @return mixed
154 * @throws MethodNotFoundException
155 */
156 public function __call(string $method, array $arguments) {
157 if (strtolower(substr($method, 0, 3)) === 'get') {
158 $name = Str::snake(substr($method, 3));
159
160 if (isset($this->attributes[$name])) {
161 return $this->attributes[$name];
162 }
163
164 return null;
165 } elseif (strtolower(substr($method, 0, 3)) === 'set') {
166 $name = Str::snake(substr($method, 3));
167
168 $this->attributes[$name] = array_pop($arguments);
169
170 return $this->attributes[$name];
171 }
172
173 throw new MethodNotFoundException("Method " . self::class . '::' . $method . '() is not supported');
174 }
175
176 /**
177 * Magic setter
178 * @param $name
179 * @param $value
180 *
181 * @return mixed
182 */
183 public function __set($name, $value) {
184 $this->attributes[$name] = $value;
185
186 return $this->attributes[$name];
187 }
188
189 /**
190 * magic getter
191 * @param $name
192 *
193 * @return mixed|null
194 */
195 public function __get($name) {
196 if (isset($this->attributes[$name])) {
197 return $this->attributes[$name];
198 }
199
200 return null;
201 }
202
203 /**
204 * Determine the structure type
205 */
206 protected function findType(): void {
207 $this->type = match ($this->part->type) {
208 IMAP::ATTACHMENT_TYPE_MESSAGE => 'message',
209 IMAP::ATTACHMENT_TYPE_APPLICATION => 'application',
210 IMAP::ATTACHMENT_TYPE_AUDIO => 'audio',
211 IMAP::ATTACHMENT_TYPE_IMAGE => 'image',
212 IMAP::ATTACHMENT_TYPE_VIDEO => 'video',
213 IMAP::ATTACHMENT_TYPE_MODEL => 'model',
214 IMAP::ATTACHMENT_TYPE_TEXT => 'text',
215 IMAP::ATTACHMENT_TYPE_MULTIPART => 'multipart',
216 default => 'other',
217 };
218 }
219
220 /**
221 * Fetch the given attachment
222 */
223 protected function fetch(): void {
224 $content = $this->part->content;
225
226 $this->content_type = $this->part->content_type;
227 $this->content = $this->decoder->decode($content, $this->part->encoding);
228
229 // Create a hash of the raw part - this can be used to identify the attachment in the message context. However,
230 // it is not guaranteed to be unique and collisions are possible.
231 // Some additional online resources:
232 // - https://en.wikipedia.org/wiki/Hash_collision
233 // - https://www.php.net/manual/en/function.hash.php
234 // - https://php.watch/articles/php-hash-benchmark
235 // Benchmark speeds:
236 // -xxh3 ~15.19(GB/s) (requires php-xxhash extension or >= php8.1)
237 // -crc32c ~14.12(GB/s)
238 // -sha256 ~0.25(GB/s)
239 // xxh3 would be nice to use, because of its extra speed and 32 instead of 8 bytes, but it is not compatible with
240 // php < 8.1. crc32c is the next fastest and is compatible with php >= 5.1. sha256 is the slowest, but is compatible
241 // with php >= 5.1 and is the most likely to be unique. crc32c is the best compromise between speed and uniqueness.
242 // Unique enough for our purposes, but not so slow that it could be a bottleneck.
243 $this->hash = hash("crc32c", $this->part->getHeader()->raw."\r\n\r\n".$this->part->content);
244
245 if (($id = $this->part->id) !== null) {
246 $this->id = str_replace(['<', '>'], '', $id);
247 }else {
248 $this->id = $this->hash;
249 }
250
251 $this->size = $this->part->bytes;
252 $this->disposition = $this->part->disposition;
253
254 if (($filename = $this->part->filename) !== null) {
255 $this->filename = $this->decodeName($filename);
256 }
257
258 if (($description = $this->part->description) !== null) {
259 $this->description = $this->part->getHeader()->getDecoder()->decode($description);
260 }
261
262 if (($name = $this->part->name) !== null) {
263 $this->name = $this->decodeName($name);
264 }
265
266 if (IMAP::ATTACHMENT_TYPE_MESSAGE == $this->part->type) {
267 if ($this->part->ifdescription) {
268 if (!$this->name) {
269 $this->name = $this->part->description;
270 }
271 } else if (!$this->name) {
272 $this->name = $this->part->subtype;
273 }
274 }
275 $this->attributes = array_merge($this->part->getHeader()->getAttributes(), $this->attributes);
276
277 if (!$this->filename) {
278 $this->filename = $this->hash;
279 }
280
281 if (!$this->name && $this->filename != "") {
282 $this->name = $this->filename;
283 }
284 }
285
286 /**
287 * Save the attachment content to your filesystem
288 * @param string $path
289 * @param string|null $filename
290 *
291 * @return boolean
292 */
293 public function save(string $path, ?string $filename = null): bool {
294 $filename = $filename ? $this->decodeName($filename) : $this->filename;
295
296 return file_put_contents($path . DIRECTORY_SEPARATOR . $filename, $this->getContent()) !== false;
297 }
298
299 /**
300 * Decode a given name
301 * @param string|null $name
302 *
303 * @return string
304 */
305 public function decodeName(?string $name): string {
306 if ($name !== null) {
307 if (str_contains($name, "''")) {
308 $parts = explode("''", $name);
309 if (EncodingAliases::has($parts[0])) {
310 $encoding = $parts[0];
311 $name = implode("''", array_slice($parts, 1));
312 }
313 }
314
315 $decoder = $this->decoder->getOptions()['message'];
316 if (preg_match('/=\?([^?]+)\?(Q|B)\?(.+)\?=/i', $name, $matches)) {
317 $name = $this->part->getHeader()->getDecoder()->decode($name);
318 } elseif ($decoder === 'utf-8' && extension_loaded('imap')) {
319 $name = \imap_utf8($name);
320 }
321
322 // check if $name is url encoded
323 if (preg_match('/%[0-9A-F]{2}/i', $name)) {
324 $name = urldecode($name);
325 }
326
327 if (isset($encoding)) {
328 $name = EncodingAliases::convert($name, $encoding);
329 }
330
331 if($this->config->get('security.sanitize_filenames', true)) {
332 $name = $this->sanitizeName($name);
333 }
334
335 return $name;
336 }
337 return "";
338 }
339
340 /**
341 * Get the attachment mime type
342 *
343 * @return string|null
344 */
345 public function getMimeType(): ?string {
346 return (new \finfo())->buffer($this->getContent(), FILEINFO_MIME_TYPE);
347 }
348
349 /**
350 * Try to guess the attachment file extension
351 *
352 * @return string|null
353 */
354 public function getExtension(): ?string {
355 $extension = null;
356 $guesser = "\Symfony\Component\Mime\MimeTypes";
357 if (class_exists($guesser) !== false) {
358 /** @var Symfony\Component\Mime\MimeTypes $guesser */
359 $extensions = $guesser::getDefault()->getExtensions($this->getMimeType());
360 $extension = $extensions[0] ?? null;
361 }
362 if ($extension === null) {
363 $deprecated_guesser = "\Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser";
364 if (class_exists($deprecated_guesser) !== false) {
365 /** @var \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser $deprecated_guesser */
366 $extension = $deprecated_guesser::getInstance()->guess($this->getMimeType());
367 }
368 }
369 if ($extension === null) {
370 $parts = explode(".", $this->filename);
371 $extension = count($parts) > 1 ? end($parts) : null;
372 }
373 if ($extension === null) {
374 $parts = explode(".", $this->name);
375 $extension = count($parts) > 1 ? end($parts) : null;
376 }
377 return $extension;
378 }
379
380 /**
381 * Get all attributes
382 *
383 * @return array
384 */
385 public function getAttributes(): array {
386 return $this->attributes;
387 }
388
389 /**
390 * @return Message
391 */
392 public function getMessage(): Message {
393 return $this->message;
394 }
395
396 /**
397 * Set the default mask
398 * @param $mask
399 *
400 * @return $this
401 */
402 public function setMask($mask): Attachment {
403 if (class_exists($mask)) {
404 $this->mask = $mask;
405 }
406
407 return $this;
408 }
409
410 /**
411 * Get the used default mask
412 *
413 * @return string
414 */
415 public function getMask(): string {
416 return $this->mask;
417 }
418
419 /**
420 * Get the attachment options
421 * @return array
422 */
423 public function getOptions(): array {
424 return $this->options;
425 }
426
427 /**
428 * Set the attachment options
429 * @param array $options
430 *
431 * @return $this
432 */
433 public function setOptions(array $options): Attachment {
434 $this->options = $options;
435 return $this;
436 }
437
438 /**
439 * Get the used config
440 *
441 * @return Config
442 */
443 public function getConfig(): Config {
444 return $this->config;
445 }
446
447 /**
448 * Set the used config
449 * @param Config $config
450 *
451 * @return $this
452 */
453 public function setConfig(Config $config): Attachment {
454 $this->config = $config;
455 return $this;
456 }
457
458 /**
459 * Get a masked instance by providing a mask name
460 * @param string|null $mask
461 *
462 * @return mixed
463 * @throws MaskNotFoundException
464 */
465 public function mask(?string $mask = null): mixed {
466 $mask = $mask !== null ? $mask : $this->mask;
467 if (class_exists($mask)) {
468 return new $mask($this);
469 }
470
471 throw new MaskNotFoundException("Unknown mask provided: " . $mask);
472 }
473
474 /**
475 * Get the decoder instance
476 *
477 * @return DecoderInterface
478 */
479 public function getDecoder(): DecoderInterface {
480 return $this->decoder;
481 }
482
483 /**
484 * Set the decoder instance
485 * @param DecoderInterface $decoder
486 *
487 * @return $this
488 */
489 public function setDecoder(DecoderInterface $decoder): static {
490 $this->decoder = $decoder;
491 return $this;
492 }
493
494 /**
495 * Sanitize a given name to prevent common attacks
496 * !!IMPORTANT!! Do not rely on this method alone - this is just the bare minimum. Additional measures should be taken
497 * to ensure that the file is safe to use.
498 * @param string $name
499 *
500 * @return string
501 */
502 private function sanitizeName(string $name): string {
503 $replaces = [
504 '/\\\\/' => '',
505 '/[\/\0:]+/' => '',
506 '/\.+/' => '.',
507 ];
508 $name_starts_with_dots = str_starts_with($name, '..');
509 $name = preg_replace(array_keys($replaces), array_values($replaces), $name);
510 if($name_starts_with_dots) {
511 return substr($name, 1);
512 }
513 return $name;
514 }
515 }