Debian Codegraph @

lib/3rdParty/composer/webklex/php-imap/src/Decoder/HeaderDecoder.php

raw symbols SCIP
1 <?php
2 /*
3 * File: Decoder.php
4 * Category: -
5 * Author: M.Goldenbaum
6 * Created: 12.04.24 20:14
7 * Updated: -
8 *
9 * Description:
10 * -
11 */
12
13 namespace Webklex\PHPIMAP\Decoder;
14
15 use Webklex\PHPIMAP\EncodingAliases;
16
17 /**
18 * Class HeaderDecoder
19 *
20 * @package Webklex\PHPIMAP
21 */
22 class HeaderDecoder extends Decoder {
23
24 public function decode(array|string|null $value, ?string $encoding = null): mixed {
25 if (is_array($value)) {
26 return $this->decodeHeaderArray($value);
27 }
28 $original_value = $value;
29 $decoder = $this->options['header'];
30
31 if ($value !== null) {
32 if ($decoder === 'utf-8') {
33 $decoded_values = $this->mimeHeaderDecode($value);
34 $tempValue = "";
35 foreach ($decoded_values as $decoded_value) {
36 $tempValue .= $this->convertEncoding($decoded_value->text, $decoded_value->charset);
37 }
38 if ($tempValue) {
39 $value = $tempValue;
40 } else if (extension_loaded('imap')) {
41 $value = \imap_utf8($value);
42 } else if (function_exists('iconv_mime_decode')) {
43 $value = iconv_mime_decode($value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "UTF-8");
44 } else {
45 $value = mb_decode_mimeheader($value);
46 }
47 } elseif ($decoder === 'iconv') {
48 $value = iconv_mime_decode($value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "UTF-8");
49 } else if (self::isUTF8($value)) {
50 $value = mb_decode_mimeheader($value);
51 }
52
53 if (self::notDecoded($original_value, $value)) {
54 $value = $this->convertEncoding($original_value, $this->getEncoding($original_value));
55 }
56 }
57
58 return $value;
59 }
60
61 /**
62 * Get the encoding of a given abject
63 * @param object|string $structure
64 *
65 * @return string
66 */
67 public function getEncoding(object|string $structure): string {
68 if (property_exists($structure, 'parameters')) {
69 foreach ($structure->parameters as $parameter) {
70 if (strtolower($parameter->attribute) == "charset") {
71 return EncodingAliases::get($parameter->value == "default" ? EncodingAliases::detectEncoding($parameter->value) : $parameter->value, $this->fallback_encoding);
72 }
73 }
74 } elseif (property_exists($structure, 'charset')) {
75 return EncodingAliases::get($structure->charset == "default" ? EncodingAliases::detectEncoding($structure->charset) : $structure->charset, $this->fallback_encoding);
76 } elseif (is_string($structure) === true) {
77 $result = mb_detect_encoding($structure);
78 return $result === false ? $this->fallback_encoding : $result;
79 }
80
81 return $this->fallback_encoding;
82 }
83
84
85 /**
86 * Decode a given array
87 * @param array $values
88 *
89 * @return array
90 */
91 private function decodeHeaderArray(array $values): array {
92 foreach ($values as $key => $value) {
93 $values[$key] = $this->decode($value);
94 }
95 return $values;
96 }
97
98 }