| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
namespace Webklex\PHPIMAP\Decoder; |
| 14 |
|
| 15 |
use Exception; |
| 16 |
use Webklex\PHPIMAP\EncodingAliases; |
| 17 |
use Webklex\PHPIMAP\IMAP; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
class MessageDecoder extends Decoder { |
| 25 |
|
| 26 |
public function decode(array|string|null $value, ?string $encoding = null): mixed { |
| 27 |
if(is_array($value)) { |
| 28 |
return array_map(function($item){ |
| 29 |
return $this->decode($item); |
| 30 |
}, $value); |
| 31 |
} |
| 32 |
|
| 33 |
switch ($encoding) { |
| 34 |
case IMAP::MESSAGE_ENC_BINARY: |
| 35 |
if (extension_loaded('imap')) { |
| 36 |
return base64_decode(\imap_binary($value)); |
| 37 |
} |
| 38 |
return base64_decode($value); |
| 39 |
case IMAP::MESSAGE_ENC_BASE64: |
| 40 |
return base64_decode($value); |
| 41 |
case IMAP::MESSAGE_ENC_QUOTED_PRINTABLE: |
| 42 |
return quoted_printable_decode($value); |
| 43 |
case IMAP::MESSAGE_ENC_8BIT: |
| 44 |
case IMAP::MESSAGE_ENC_7BIT: |
| 45 |
case IMAP::MESSAGE_ENC_OTHER: |
| 46 |
default: |
| 47 |
return $value; |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
public function getEncoding(object|string $structure): string { |
| 58 |
if (property_exists($structure, 'parameters')) { |
| 59 |
foreach ($structure->parameters as $parameter) { |
| 60 |
if (strtolower($parameter->attribute) == "charset") { |
| 61 |
return EncodingAliases::get($parameter->value, "ISO-8859-2"); |
| 62 |
} |
| 63 |
} |
| 64 |
} elseif (property_exists($structure, 'charset')) { |
| 65 |
return EncodingAliases::get($structure->charset, "ISO-8859-2"); |
| 66 |
} elseif (is_string($structure) === true) { |
| 67 |
return EncodingAliases::detectEncoding($structure); |
| 68 |
} |
| 69 |
|
| 70 |
return $this->fallback_encoding; |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
public function convertEncoding($str, string $from = "ISO-8859-2", string $to = "UTF-8"): mixed { |
| 83 |
$from = EncodingAliases::get($from); |
| 84 |
$to = EncodingAliases::get($to); |
| 85 |
|
| 86 |
if ($from === $to) { |
| 87 |
return $str; |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
if (strtolower($from ?? '') == 'us-ascii' && $to == 'UTF-8') { |
| 102 |
return $str; |
| 103 |
} |
| 104 |
|
| 105 |
if (function_exists('iconv') && !EncodingAliases::isUtf7($from) && !EncodingAliases::isUtf7($to)) { |
| 106 |
try { |
| 107 |
return iconv($from, $to.'//IGNORE', $str); |
| 108 |
} catch (Exception) { |
| 109 |
return @iconv($from, $to, $str); |
| 110 |
} |
| 111 |
} else { |
| 112 |
if (!$from) { |
| 113 |
return mb_convert_encoding($str, $to); |
| 114 |
} |
| 115 |
return mb_convert_encoding($str, $to, $from); |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
} |