| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
namespace Liuch\DmarcSrg\Mail\PhpExtension; |
| 24 |
|
| 25 |
use Liuch\DmarcSrg\Mail\MailAttachmentInterface; |
| 26 |
use Liuch\DmarcSrg\ReportFile\ReportFile; |
| 27 |
use Liuch\DmarcSrg\Exception\SoftException; |
| 28 |
|
| 29 |
class MailAttachment extends \Liuch\DmarcSrg\Mail\MailAttachment |
| 30 |
{ |
| 31 |
private $mailbox; |
| 32 |
private $filename; |
| 33 |
private $bytes; |
| 34 |
private $number; |
| 35 |
private $mnumber; |
| 36 |
private $encoding; |
| 37 |
private $stream; |
| 38 |
private $mime_type; |
| 39 |
|
| 40 |
public function __construct($data) |
| 41 |
{ |
| 42 |
$this->mailbox = $data['mailbox']; |
| 43 |
$this->filename = $data['filename']; |
| 44 |
$this->bytes = $data['bytes']; |
| 45 |
$this->number = $data['number']; |
| 46 |
$this->mnumber = $data['mnumber']; |
| 47 |
$this->encoding = $data['encoding']; |
| 48 |
$this->stream = null; |
| 49 |
$this->mime_type = null; |
| 50 |
} |
| 51 |
|
| 52 |
public function __destruct() |
| 53 |
{ |
| 54 |
if (!is_null($this->stream) && get_resource_type($this->stream) == 'stream') { |
| 55 |
fclose($this->stream); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
public function mimeType(): string |
| 60 |
{ |
| 61 |
if (is_null($this->mime_type)) { |
| 62 |
$this->mime_type = ReportFile::getMimeType($this->filename, $this->datastream()); |
| 63 |
} |
| 64 |
return $this->mime_type; |
| 65 |
} |
| 66 |
|
| 67 |
public function size(): int |
| 68 |
{ |
| 69 |
return $this->bytes; |
| 70 |
} |
| 71 |
|
| 72 |
public function filename() |
| 73 |
{ |
| 74 |
return $this->filename; |
| 75 |
} |
| 76 |
|
| 77 |
public function datastream() |
| 78 |
{ |
| 79 |
if (is_null($this->stream)) { |
| 80 |
$this->stream = fopen('php://temp', 'r+'); |
| 81 |
fwrite($this->stream, $this->toString()); |
| 82 |
} |
| 83 |
if (stream_get_meta_data($this->stream)['seekable'] ?? false) { |
| 84 |
rewind($this->stream); |
| 85 |
} |
| 86 |
return $this->stream; |
| 87 |
} |
| 88 |
|
| 89 |
private function fetchBody() |
| 90 |
{ |
| 91 |
return imap_fetchbody($this->mailbox->connection(), $this->mnumber, strval($this->number), FT_PEEK | FT_UID); |
| 92 |
} |
| 93 |
|
| 94 |
private function toString() |
| 95 |
{ |
| 96 |
switch ($this->encoding) { |
| 97 |
case ENC7BIT: |
| 98 |
case ENC8BIT: |
| 99 |
case ENCBINARY: |
| 100 |
return $this->fetchBody(); |
| 101 |
case ENCBASE64: |
| 102 |
return base64_decode($this->fetchBody()); |
| 103 |
case ENCQUOTEDPRINTABLE: |
| 104 |
return imap_qprint($this->fetchBody()); |
| 105 |
} |
| 106 |
throw new SoftException('Encoding failed: Unknown encoding'); |
| 107 |
} |
| 108 |
} |