Mbstring.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Polyfill\Mbstring;
  11. /**
  12. * Partial mbstring implementation in PHP, iconv based, UTF-8 centric.
  13. *
  14. * Implemented:
  15. * - mb_chr - Returns a specific character from its Unicode code point
  16. * - mb_convert_encoding - Convert character encoding
  17. * - mb_convert_variables - Convert character code in variable(s)
  18. * - mb_decode_mimeheader - Decode string in MIME header field
  19. * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED
  20. * - mb_decode_numericentity - Decode HTML numeric string reference to character
  21. * - mb_encode_numericentity - Encode character to HTML numeric string reference
  22. * - mb_convert_case - Perform case folding on a string
  23. * - mb_detect_encoding - Detect character encoding
  24. * - mb_get_info - Get internal settings of mbstring
  25. * - mb_http_input - Detect HTTP input character encoding
  26. * - mb_http_output - Set/Get HTTP output character encoding
  27. * - mb_internal_encoding - Set/Get internal character encoding
  28. * - mb_list_encodings - Returns an array of all supported encodings
  29. * - mb_ord - Returns the Unicode code point of a character
  30. * - mb_output_handler - Callback function converts character encoding in output buffer
  31. * - mb_scrub - Replaces ill-formed byte sequences with substitute characters
  32. * - mb_strlen - Get string length
  33. * - mb_strpos - Find position of first occurrence of string in a string
  34. * - mb_strrpos - Find position of last occurrence of a string in a string
  35. * - mb_str_split - Convert a string to an array
  36. * - mb_strtolower - Make a string lowercase
  37. * - mb_strtoupper - Make a string uppercase
  38. * - mb_substitute_character - Set/Get substitution character
  39. * - mb_substr - Get part of string
  40. * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive
  41. * - mb_stristr - Finds first occurrence of a string within another, case insensitive
  42. * - mb_strrchr - Finds the last occurrence of a character in a string within another
  43. * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive
  44. * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive
  45. * - mb_strstr - Finds first occurrence of a string within another
  46. * - mb_strwidth - Return width of string
  47. * - mb_substr_count - Count the number of substring occurrences
  48. * - mb_ucfirst - Make a string's first character uppercase
  49. * - mb_lcfirst - Make a string's first character lowercase
  50. * - mb_trim - Strip whitespace (or other characters) from the beginning and end of a string
  51. * - mb_ltrim - Strip whitespace (or other characters) from the beginning of a string
  52. * - mb_rtrim - Strip whitespace (or other characters) from the end of a string
  53. *
  54. * Not implemented:
  55. * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  56. * - mb_ereg_* - Regular expression with multibyte support
  57. * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable
  58. * - mb_preferred_mime_name - Get MIME charset string
  59. * - mb_regex_encoding - Returns current encoding for multibyte regex as string
  60. * - mb_regex_set_options - Set/Get the default options for mbregex functions
  61. * - mb_send_mail - Send encoded mail
  62. * - mb_split - Split multibyte string using regular expression
  63. * - mb_strcut - Get part of string
  64. * - mb_strimwidth - Get truncated string with specified width
  65. *
  66. * @author Nicolas Grekas <p@tchwork.com>
  67. *
  68. * @internal
  69. */
  70. final class Mbstring
  71. {
  72. public const MB_CASE_FOLD = \PHP_INT_MAX;
  73. private const SIMPLE_CASE_FOLD = [
  74. ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"],
  75. ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'],
  76. ];
  77. private static $encodingList = ['ASCII', 'UTF-8'];
  78. private static $language = 'neutral';
  79. private static $internalEncoding = 'UTF-8';
  80. private static $iconvSupportsIgnore;
  81. public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null)
  82. {
  83. if (\is_array($s)) {
  84. $r = [];
  85. foreach ($s as $str) {
  86. $r[] = self::mb_convert_encoding($str, $toEncoding, $fromEncoding);
  87. }
  88. return $r;
  89. }
  90. if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) {
  91. $fromEncoding = self::mb_detect_encoding($s, $fromEncoding);
  92. } else {
  93. $fromEncoding = self::getEncoding($fromEncoding);
  94. }
  95. $toEncoding = self::getEncoding($toEncoding);
  96. if ('BASE64' === $fromEncoding) {
  97. $s = base64_decode($s);
  98. $fromEncoding = $toEncoding;
  99. }
  100. if ('BASE64' === $toEncoding) {
  101. return base64_encode($s);
  102. }
  103. if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) {
  104. if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) {
  105. $fromEncoding = 'Windows-1252';
  106. }
  107. if ('UTF-8' !== $fromEncoding) {
  108. $s = self::iconv($fromEncoding, 'UTF-8', $s);
  109. }
  110. return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s);
  111. }
  112. if ('HTML-ENTITIES' === $fromEncoding) {
  113. $decodeControlChars = static function ($m) {
  114. $code = '' !== ($m[2] ?? '') ? hexdec($m[2]) : (int) $m[1];
  115. if ($code < 32 || 127 === $code) {
  116. return \chr($code);
  117. }
  118. if (128 <= $code && $code <= 159) {
  119. return "\xC2".\chr(0x80 | ($code & 0x3F));
  120. }
  121. return $m[0];
  122. };
  123. if (\PHP_VERSION_ID >= 70400) {
  124. $s = html_entity_decode($s, \ENT_QUOTES, 'UTF-8');
  125. // html_entity_decode() leaves numeric entities for C0/C1 control
  126. // characters as-is (HTML spec), but mb_convert_encoding() decodes
  127. // them. Catch what html_entity_decode() missed.
  128. if (false !== strpos($s, '&#')) {
  129. $s = preg_replace_callback('/&#(?:0*([0-9]++)|[xX]0*([0-9a-fA-F]++));/', $decodeControlChars, $s);
  130. }
  131. } else {
  132. // PHP < 7.4: html_entity_decode() truncates strings at NUL bytes,
  133. // so decode the control character entities first then call
  134. // html_entity_decode() on each NUL-delimited chunk independently.
  135. $s = preg_replace_callback('/&#(?:0*([0-9]++)|[xX]0*([0-9a-fA-F]++));/', $decodeControlChars, $s);
  136. $s = implode("\0", array_map(static function ($chunk) {
  137. return html_entity_decode($chunk, \ENT_QUOTES, 'UTF-8');
  138. }, explode("\0", $s)));
  139. }
  140. $fromEncoding = 'UTF-8';
  141. }
  142. return self::iconv($fromEncoding, $toEncoding, $s);
  143. }
  144. public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars)
  145. {
  146. $ok = true;
  147. array_walk_recursive($vars, static function (&$v) use (&$ok, $toEncoding, $fromEncoding) {
  148. if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) {
  149. $ok = false;
  150. }
  151. });
  152. return $ok ? $fromEncoding : false;
  153. }
  154. public static function mb_decode_mimeheader($s)
  155. {
  156. return iconv_mime_decode($s, 2, self::$internalEncoding);
  157. }
  158. public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null)
  159. {
  160. trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING);
  161. }
  162. public static function mb_decode_numericentity($s, $convmap, $encoding = null)
  163. {
  164. if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) {
  165. trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  166. return null;
  167. }
  168. if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) {
  169. return false;
  170. }
  171. if (null !== $encoding && !\is_scalar($encoding)) {
  172. trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  173. return ''; // Instead of null (cf. mb_encode_numericentity).
  174. }
  175. $s = (string) $s;
  176. if ('' === $s) {
  177. return '';
  178. }
  179. $encoding = self::getEncoding($encoding);
  180. if ('UTF-8' === $encoding) {
  181. $encoding = null;
  182. if (!preg_match('//u', $s)) {
  183. $s = @self::iconv('UTF-8', 'UTF-8', $s);
  184. }
  185. } else {
  186. $s = self::iconv($encoding, 'UTF-8', $s);
  187. }
  188. $cnt = floor(\count($convmap) / 4) * 4;
  189. for ($i = 0; $i < $cnt; $i += 4) {
  190. // collector_decode_htmlnumericentity ignores $convmap[$i + 3]
  191. $convmap[$i] += $convmap[$i + 2];
  192. $convmap[$i + 1] += $convmap[$i + 2];
  193. }
  194. $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))'.(\PHP_VERSION_ID >= 80200 ? '' : '(?!&)').';?/', static function (array $m) use ($cnt, $convmap) {
  195. $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1];
  196. for ($i = 0; $i < $cnt; $i += 4) {
  197. if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) {
  198. return self::mb_chr($c - $convmap[$i + 2]);
  199. }
  200. }
  201. return $m[0];
  202. }, $s);
  203. if (null === $encoding) {
  204. return $s;
  205. }
  206. return self::iconv('UTF-8', $encoding, $s);
  207. }
  208. public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false)
  209. {
  210. if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) {
  211. trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  212. return null;
  213. }
  214. if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) {
  215. return false;
  216. }
  217. if (null !== $encoding && !\is_scalar($encoding)) {
  218. trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  219. return null; // Instead of '' (cf. mb_decode_numericentity).
  220. }
  221. if (null !== $is_hex && !\is_scalar($is_hex)) {
  222. trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING);
  223. return null;
  224. }
  225. $s = (string) $s;
  226. if ('' === $s) {
  227. return '';
  228. }
  229. $encoding = self::getEncoding($encoding);
  230. if ('UTF-8' === $encoding) {
  231. $encoding = null;
  232. if (!preg_match('//u', $s)) {
  233. $s = @self::iconv('UTF-8', 'UTF-8', $s);
  234. }
  235. } else {
  236. $s = self::iconv($encoding, 'UTF-8', $s);
  237. }
  238. static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4];
  239. $cnt = floor(\count($convmap) / 4) * 4;
  240. $i = 0;
  241. $len = \strlen($s);
  242. $result = '';
  243. while ($i < $len) {
  244. $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
  245. $uchr = substr($s, $i, $ulen);
  246. $i += $ulen;
  247. $c = self::mb_ord($uchr);
  248. for ($j = 0; $j < $cnt; $j += 4) {
  249. if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) {
  250. $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3];
  251. $result .= $is_hex ? \sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';';
  252. continue 2;
  253. }
  254. }
  255. $result .= $uchr;
  256. }
  257. if (null === $encoding) {
  258. return $result;
  259. }
  260. return self::iconv('UTF-8', $encoding, $result);
  261. }
  262. public static function mb_convert_case($s, $mode, $encoding = null)
  263. {
  264. $s = (string) $s;
  265. if ('' === $s) {
  266. return '';
  267. }
  268. $encoding = self::getEncoding($encoding);
  269. if ('UTF-8' === $encoding) {
  270. $encoding = null;
  271. if (!preg_match('//u', $s)) {
  272. $s = @self::iconv('UTF-8', 'UTF-8', $s);
  273. }
  274. } else {
  275. $s = self::iconv($encoding, 'UTF-8', $s);
  276. }
  277. if (\MB_CASE_TITLE == $mode) {
  278. static $titleRegexp = null;
  279. if (null === $titleRegexp) {
  280. $titleRegexp = self::getData('titleCaseRegexp');
  281. }
  282. $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s);
  283. } else {
  284. if (\MB_CASE_UPPER == $mode) {
  285. static $upper = null;
  286. if (null === $upper) {
  287. $upper = self::getData('upperCase');
  288. }
  289. $map = $upper;
  290. } else {
  291. if (self::MB_CASE_FOLD === $mode) {
  292. static $caseFolding = null;
  293. if (null === $caseFolding) {
  294. $caseFolding = self::getData('caseFolding');
  295. }
  296. $s = strtr($s, $caseFolding);
  297. }
  298. static $lower = null;
  299. if (null === $lower) {
  300. $lower = self::getData('lowerCase');
  301. }
  302. $map = $lower;
  303. }
  304. static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4];
  305. $i = 0;
  306. $len = \strlen($s);
  307. while ($i < $len) {
  308. $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
  309. $uchr = substr($s, $i, $ulen);
  310. $i += $ulen;
  311. if (isset($map[$uchr])) {
  312. $uchr = $map[$uchr];
  313. $nlen = \strlen($uchr);
  314. if ($nlen == $ulen) {
  315. $nlen = $i;
  316. do {
  317. $s[--$nlen] = $uchr[--$ulen];
  318. } while ($ulen);
  319. } else {
  320. $s = substr_replace($s, $uchr, $i - $ulen, $ulen);
  321. $len += $nlen - $ulen;
  322. $i += $nlen - $ulen;
  323. }
  324. }
  325. }
  326. }
  327. if (null === $encoding) {
  328. return $s;
  329. }
  330. return self::iconv('UTF-8', $encoding, $s);
  331. }
  332. public static function mb_internal_encoding($encoding = null)
  333. {
  334. if (null === $encoding) {
  335. return self::$internalEncoding;
  336. }
  337. $normalizedEncoding = self::getEncoding($encoding);
  338. if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) {
  339. self::$internalEncoding = $normalizedEncoding;
  340. return true;
  341. }
  342. if (80000 > \PHP_VERSION_ID) {
  343. return false;
  344. }
  345. throw new \ValueError(\sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding));
  346. }
  347. public static function mb_language($lang = null)
  348. {
  349. if (null === $lang) {
  350. return self::$language;
  351. }
  352. switch ($normalizedLang = strtolower($lang)) {
  353. case 'uni':
  354. case 'neutral':
  355. self::$language = $normalizedLang;
  356. return true;
  357. }
  358. if (80000 > \PHP_VERSION_ID) {
  359. return false;
  360. }
  361. throw new \ValueError(\sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang));
  362. }
  363. public static function mb_list_encodings()
  364. {
  365. return ['UTF-8'];
  366. }
  367. public static function mb_encoding_aliases($encoding)
  368. {
  369. switch (strtoupper($encoding)) {
  370. case 'UTF8':
  371. case 'UTF-8':
  372. return ['utf8'];
  373. }
  374. return false;
  375. }
  376. public static function mb_check_encoding($var = null, $encoding = null)
  377. {
  378. if (null === $encoding) {
  379. if (null === $var) {
  380. return false;
  381. }
  382. $encoding = self::$internalEncoding;
  383. }
  384. if (!\is_array($var)) {
  385. return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var);
  386. }
  387. foreach ($var as $key => $value) {
  388. if (!self::mb_check_encoding($key, $encoding)) {
  389. return false;
  390. }
  391. if (!self::mb_check_encoding($value, $encoding)) {
  392. return false;
  393. }
  394. }
  395. return true;
  396. }
  397. public static function mb_detect_encoding($str, $encodingList = null, $strict = false)
  398. {
  399. if (null === $encodingList) {
  400. $encodingList = self::$encodingList;
  401. } else {
  402. if (!\is_array($encodingList)) {
  403. $encodingList = array_map('trim', explode(',', $encodingList));
  404. }
  405. $encodingList = array_map('strtoupper', $encodingList);
  406. }
  407. foreach ($encodingList as $enc) {
  408. switch ($enc) {
  409. case 'ASCII':
  410. if (!preg_match('/[\x80-\xFF]/', $str)) {
  411. return $enc;
  412. }
  413. break;
  414. case 'UTF8':
  415. case 'UTF-8':
  416. if (preg_match('//u', $str)) {
  417. return 'UTF-8';
  418. }
  419. break;
  420. default:
  421. if (0 === strncmp($enc, 'ISO-8859-', 9)) {
  422. return $enc;
  423. }
  424. }
  425. }
  426. return false;
  427. }
  428. public static function mb_detect_order($encodingList = null)
  429. {
  430. if (null === $encodingList) {
  431. return self::$encodingList;
  432. }
  433. if (!\is_array($encodingList)) {
  434. $encodingList = array_map('trim', explode(',', $encodingList));
  435. }
  436. $encodingList = array_map('strtoupper', $encodingList);
  437. foreach ($encodingList as $enc) {
  438. switch ($enc) {
  439. default:
  440. if (strncmp($enc, 'ISO-8859-', 9)) {
  441. return false;
  442. }
  443. // no break
  444. case 'ASCII':
  445. case 'UTF8':
  446. case 'UTF-8':
  447. }
  448. }
  449. self::$encodingList = $encodingList;
  450. return true;
  451. }
  452. public static function mb_strlen($s, $encoding = null)
  453. {
  454. $encoding = self::getEncoding($encoding);
  455. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  456. return \strlen($s);
  457. }
  458. if (false !== $len = @iconv_strlen($s, $encoding)) {
  459. return $len;
  460. }
  461. if ('UTF-8' !== $encoding) {
  462. return $len;
  463. }
  464. return preg_match_all('/[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]?|[\xE0-\xEF][\x80-\xBF]{0,2}|[\xF0-\xF7][\x80-\xBF]{0,3}|[\xF8-\xFB][\x80-\xBF]{0,4}|[\xFC-\xFD][\x80-\xBF]{0,5}|[\x80-\xBF\xFE\xFF]/s', $s);
  465. }
  466. public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
  467. {
  468. $encoding = self::getEncoding($encoding);
  469. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  470. return strpos($haystack, $needle, $offset);
  471. }
  472. $needle = (string) $needle;
  473. if ('' === $needle) {
  474. if (80000 > \PHP_VERSION_ID) {
  475. trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING);
  476. return false;
  477. }
  478. return 0;
  479. }
  480. return iconv_strpos($haystack, $needle, $offset, $encoding);
  481. }
  482. public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null)
  483. {
  484. $encoding = self::getEncoding($encoding);
  485. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  486. return strrpos($haystack, $needle, $offset);
  487. }
  488. if ($offset != (int) $offset) {
  489. $offset = 0;
  490. } elseif ($offset = (int) $offset) {
  491. if ($offset < 0) {
  492. if (0 > $offset += self::mb_strlen($needle)) {
  493. $haystack = self::mb_substr($haystack, 0, $offset, $encoding);
  494. }
  495. $offset = 0;
  496. } else {
  497. $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding);
  498. }
  499. }
  500. $pos = '' !== $needle || 80000 > \PHP_VERSION_ID
  501. ? iconv_strrpos($haystack, $needle, $encoding)
  502. : self::mb_strlen($haystack, $encoding);
  503. return false !== $pos ? $offset + $pos : false;
  504. }
  505. public static function mb_str_split($string, $split_length = 1, $encoding = null)
  506. {
  507. if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) {
  508. trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING);
  509. return null;
  510. }
  511. if (1 > $split_length = (int) $split_length) {
  512. if (80000 > \PHP_VERSION_ID) {
  513. trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING);
  514. return false;
  515. }
  516. throw new \ValueError('Argument #2 ($length) must be greater than 0');
  517. }
  518. if (null === $encoding) {
  519. $encoding = mb_internal_encoding();
  520. }
  521. if ('UTF-8' === $encoding = self::getEncoding($encoding)) {
  522. $rx = '/(';
  523. while (65535 < $split_length) {
  524. $rx .= '.{65535}';
  525. $split_length -= 65535;
  526. }
  527. $rx .= '.{'.$split_length.'})/us';
  528. return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
  529. }
  530. $result = [];
  531. $length = mb_strlen($string, $encoding);
  532. for ($i = 0; $i < $length; $i += $split_length) {
  533. $result[] = mb_substr($string, $i, $split_length, $encoding);
  534. }
  535. return $result;
  536. }
  537. public static function mb_strtolower($s, $encoding = null)
  538. {
  539. return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding);
  540. }
  541. public static function mb_strtoupper($s, $encoding = null)
  542. {
  543. return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding);
  544. }
  545. public static function mb_substitute_character($c = null)
  546. {
  547. if (null === $c) {
  548. return 'none';
  549. }
  550. if (0 === strcasecmp($c, 'none')) {
  551. return true;
  552. }
  553. if (80000 > \PHP_VERSION_ID) {
  554. return false;
  555. }
  556. if (\is_int($c) || 'long' === $c || 'entity' === $c) {
  557. return false;
  558. }
  559. throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint');
  560. }
  561. public static function mb_substr($s, $start, $length = null, $encoding = null)
  562. {
  563. $encoding = self::getEncoding($encoding);
  564. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  565. return (string) substr($s, $start, null === $length ? 2147483647 : $length);
  566. }
  567. if ($start < 0) {
  568. $start = iconv_strlen($s, $encoding) + $start;
  569. if ($start < 0) {
  570. $start = 0;
  571. }
  572. }
  573. if (null === $length) {
  574. $length = 2147483647;
  575. } elseif ($length < 0) {
  576. $length = iconv_strlen($s, $encoding) + $length - $start;
  577. if ($length < 0) {
  578. return '';
  579. }
  580. }
  581. return (string) iconv_substr($s, $start, $length, $encoding);
  582. }
  583. public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null)
  584. {
  585. [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [
  586. self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding),
  587. self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding),
  588. ]);
  589. return self::mb_strpos($haystack, $needle, $offset, $encoding);
  590. }
  591. public static function mb_stristr($haystack, $needle, $part = false, $encoding = null)
  592. {
  593. $pos = self::mb_stripos($haystack, $needle, 0, $encoding);
  594. return self::getSubpart($pos, $part, $haystack, $encoding);
  595. }
  596. public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null)
  597. {
  598. $encoding = self::getEncoding($encoding);
  599. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  600. $pos = strrpos($haystack, $needle);
  601. } else {
  602. $needle = self::mb_substr($needle, 0, 1, $encoding);
  603. $pos = iconv_strrpos($haystack, $needle, $encoding);
  604. }
  605. return self::getSubpart($pos, $part, $haystack, $encoding);
  606. }
  607. public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null)
  608. {
  609. $needle = self::mb_substr($needle, 0, 1, $encoding);
  610. $pos = self::mb_strripos($haystack, $needle, $encoding);
  611. return self::getSubpart($pos, $part, $haystack, $encoding);
  612. }
  613. public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null)
  614. {
  615. $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding);
  616. $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding);
  617. $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack);
  618. $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle);
  619. return self::mb_strrpos($haystack, $needle, $offset, $encoding);
  620. }
  621. public static function mb_strstr($haystack, $needle, $part = false, $encoding = null)
  622. {
  623. $pos = strpos($haystack, $needle);
  624. if (false === $pos) {
  625. return false;
  626. }
  627. if ($part) {
  628. return substr($haystack, 0, $pos);
  629. }
  630. return substr($haystack, $pos);
  631. }
  632. public static function mb_get_info($type = 'all')
  633. {
  634. $info = [
  635. 'internal_encoding' => self::$internalEncoding,
  636. 'http_output' => 'pass',
  637. 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)',
  638. 'func_overload' => 0,
  639. 'func_overload_list' => 'no overload',
  640. 'mail_charset' => 'UTF-8',
  641. 'mail_header_encoding' => 'BASE64',
  642. 'mail_body_encoding' => 'BASE64',
  643. 'illegal_chars' => 0,
  644. 'encoding_translation' => 'Off',
  645. 'language' => self::$language,
  646. 'detect_order' => self::$encodingList,
  647. 'substitute_character' => 'none',
  648. 'strict_detection' => 'Off',
  649. ];
  650. if ('all' === $type) {
  651. return $info;
  652. }
  653. if (isset($info[$type])) {
  654. return $info[$type];
  655. }
  656. return false;
  657. }
  658. public static function mb_http_input($type = '')
  659. {
  660. return false;
  661. }
  662. public static function mb_http_output($encoding = null)
  663. {
  664. return null !== $encoding ? 'pass' === $encoding : 'pass';
  665. }
  666. public static function mb_strwidth($s, $encoding = null)
  667. {
  668. $encoding = self::getEncoding($encoding);
  669. if ('UTF-8' !== $encoding) {
  670. $s = self::iconv($encoding, 'UTF-8', $s);
  671. }
  672. $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide);
  673. return ($wide << 1) + iconv_strlen($s, 'UTF-8');
  674. }
  675. public static function mb_substr_count($haystack, $needle, $encoding = null)
  676. {
  677. return substr_count($haystack, $needle);
  678. }
  679. public static function mb_output_handler($contents, $status)
  680. {
  681. return $contents;
  682. }
  683. public static function mb_chr($code, $encoding = null)
  684. {
  685. if (0x80 > $code %= 0x200000) {
  686. $s = \chr($code);
  687. } elseif (0x800 > $code) {
  688. $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
  689. } elseif (0x10000 > $code) {
  690. $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
  691. } else {
  692. $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
  693. }
  694. if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
  695. $s = mb_convert_encoding($s, $encoding, 'UTF-8');
  696. }
  697. return $s;
  698. }
  699. public static function mb_ord($s, $encoding = null)
  700. {
  701. if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
  702. $s = mb_convert_encoding($s, 'UTF-8', $encoding);
  703. }
  704. if (1 === \strlen($s)) {
  705. return \ord($s);
  706. }
  707. $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0;
  708. if (0xF0 <= $code) {
  709. return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80;
  710. }
  711. if (0xE0 <= $code) {
  712. return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80;
  713. }
  714. if (0xC0 <= $code) {
  715. return (($code - 0xC0) << 6) + $s[2] - 0x80;
  716. }
  717. return $code;
  718. }
  719. /** @return string|false */
  720. public static function mb_scrub(?string $string, ?string $encoding = null): string
  721. {
  722. if (null === $encoding) {
  723. $encoding = self::mb_internal_encoding();
  724. } elseif (!self::assertEncoding($encoding, 'mb_scrub(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) {
  725. return false;
  726. }
  727. return self::mb_convert_encoding((string) $string, $encoding, $encoding);
  728. }
  729. /** @return string|false */
  730. public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, ?string $encoding = null)
  731. {
  732. if (null === $encoding) {
  733. $encoding = self::mb_internal_encoding();
  734. } elseif (!self::assertEncoding($encoding, 'mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given')) {
  735. return false;
  736. }
  737. if (self::mb_strlen($pad_string, $encoding) <= 0) {
  738. if (\PHP_VERSION_ID < 80000) {
  739. trigger_error('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string', \E_USER_WARNING);
  740. return false;
  741. }
  742. throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string');
  743. }
  744. if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) {
  745. if (\PHP_VERSION_ID < 80000) {
  746. trigger_error('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH', \E_USER_WARNING);
  747. return false;
  748. }
  749. throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH');
  750. }
  751. $paddingRequired = $length - self::mb_strlen($string, $encoding);
  752. if ($paddingRequired < 1) {
  753. return $string;
  754. }
  755. switch ($pad_type) {
  756. case \STR_PAD_LEFT:
  757. return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string;
  758. case \STR_PAD_RIGHT:
  759. return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding);
  760. default:
  761. $leftPaddingLength = floor($paddingRequired / 2);
  762. $rightPaddingLength = $paddingRequired - $leftPaddingLength;
  763. return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding);
  764. }
  765. }
  766. /** @return string|false */
  767. public static function mb_ucfirst(string $string, ?string $encoding = null)
  768. {
  769. if (null === $encoding) {
  770. $encoding = self::mb_internal_encoding();
  771. } elseif (!self::assertEncoding($encoding, 'mb_ucfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) {
  772. return false;
  773. }
  774. $firstChar = mb_substr($string, 0, 1, $encoding);
  775. $firstChar = mb_convert_case($firstChar, \MB_CASE_TITLE, $encoding);
  776. return $firstChar.mb_substr($string, 1, null, $encoding);
  777. }
  778. /** @return string|false */
  779. public static function mb_lcfirst(string $string, ?string $encoding = null)
  780. {
  781. if (null === $encoding) {
  782. $encoding = self::mb_internal_encoding();
  783. } elseif (!self::assertEncoding($encoding, 'mb_lcfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given')) {
  784. return false;
  785. }
  786. $firstChar = mb_substr($string, 0, 1, $encoding);
  787. $firstChar = mb_convert_case($firstChar, \MB_CASE_LOWER, $encoding);
  788. return $firstChar.mb_substr($string, 1, null, $encoding);
  789. }
  790. /** @return string|false */
  791. public static function mb_trim(string $string, ?string $characters = null, ?string $encoding = null)
  792. {
  793. return self::mb_internal_trim('{^[%s]+|[%1$s]+$}Du', $string, $characters, $encoding, __FUNCTION__);
  794. }
  795. /** @return string|false */
  796. public static function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null)
  797. {
  798. return self::mb_internal_trim('{^[%s]+}Du', $string, $characters, $encoding, __FUNCTION__);
  799. }
  800. /** @return string|false */
  801. public static function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null)
  802. {
  803. return self::mb_internal_trim('{[%s]+$}Du', $string, $characters, $encoding, __FUNCTION__);
  804. }
  805. private static function getSubpart($pos, $part, $haystack, $encoding)
  806. {
  807. if (false === $pos) {
  808. return false;
  809. }
  810. if ($part) {
  811. return self::mb_substr($haystack, 0, $pos, $encoding);
  812. }
  813. return self::mb_substr($haystack, $pos, null, $encoding);
  814. }
  815. private static function html_encoding_callback(array $m)
  816. {
  817. $i = 1;
  818. $entities = '';
  819. $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8'));
  820. while (isset($m[$i])) {
  821. if (0x80 > $m[$i]) {
  822. $entities .= \chr($m[$i++]);
  823. continue;
  824. }
  825. if (0xF0 <= $m[$i]) {
  826. $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
  827. } elseif (0xE0 <= $m[$i]) {
  828. $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
  829. } else {
  830. $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80;
  831. }
  832. $entities .= '&#'.$c.';';
  833. }
  834. return $entities;
  835. }
  836. private static function title_case(array $s)
  837. {
  838. return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8');
  839. }
  840. private static function getData($file)
  841. {
  842. if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) {
  843. return require $file;
  844. }
  845. return false;
  846. }
  847. private static function getEncoding($encoding)
  848. {
  849. if (null === $encoding) {
  850. return self::$internalEncoding;
  851. }
  852. if ('UTF-8' === $encoding) {
  853. return 'UTF-8';
  854. }
  855. $encoding = strtoupper($encoding);
  856. if ('8BIT' === $encoding || 'BINARY' === $encoding) {
  857. return 'CP850';
  858. }
  859. if ('UTF8' === $encoding) {
  860. return 'UTF-8';
  861. }
  862. if ('UTF-32' === $encoding) {
  863. return 'UTF-32BE';
  864. }
  865. if ('UTF-16' === $encoding) {
  866. return 'UTF-16BE';
  867. }
  868. return $encoding;
  869. }
  870. private static function iconv($fromEncoding, $toEncoding, $s)
  871. {
  872. if (null === self::$iconvSupportsIgnore) {
  873. self::$iconvSupportsIgnore = false !== @iconv('UTF-8', 'UTF-8//IGNORE', '');
  874. }
  875. return self::$iconvSupportsIgnore
  876. ? iconv($fromEncoding, $toEncoding.'//IGNORE', $s)
  877. : iconv($fromEncoding, $toEncoding, $s);
  878. }
  879. /** @return string|false */
  880. private static function mb_internal_trim(string $regex, string $string, ?string $characters, ?string $encoding, string $function)
  881. {
  882. if (null === $encoding) {
  883. $encoding = self::mb_internal_encoding();
  884. } elseif (!self::assertEncoding($encoding, $function.'(): Argument #3 ($encoding) must be a valid encoding, "%s" given')) {
  885. return false;
  886. }
  887. if ('' === $characters) {
  888. return null === $encoding ? $string : self::mb_convert_encoding($string, $encoding);
  889. }
  890. if ('UTF-8' === $encoding) {
  891. $encoding = null;
  892. if (!preg_match('//u', $string)) {
  893. $string = @self::iconv('UTF-8', 'UTF-8', $string);
  894. }
  895. if (null !== $characters && !preg_match('//u', $characters)) {
  896. $characters = @self::iconv('UTF-8', 'UTF-8', $characters);
  897. }
  898. } else {
  899. $string = self::iconv($encoding, 'UTF-8', $string);
  900. if (null !== $characters) {
  901. $characters = self::iconv($encoding, 'UTF-8', $characters);
  902. }
  903. }
  904. if (null === $characters) {
  905. $characters = "\\0 \f\n\r\t\v\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}";
  906. } else {
  907. $characters = preg_quote($characters);
  908. }
  909. $string = preg_replace(\sprintf($regex, $characters), '', $string);
  910. if (null === $encoding) {
  911. return $string;
  912. }
  913. return self::iconv('UTF-8', $encoding, $string);
  914. }
  915. private static function assertEncoding(string $encoding, string $errorFormat): bool
  916. {
  917. try {
  918. $validEncoding = @self::mb_check_encoding('', $encoding);
  919. } catch (\ValueError $e) {
  920. throw new \ValueError(\sprintf($errorFormat, $encoding));
  921. }
  922. if (!$validEncoding) {
  923. if (80000 > \PHP_VERSION_ID) {
  924. trigger_error(\sprintf($errorFormat, $encoding), \E_USER_WARNING);
  925. } else {
  926. throw new \ValueError(\sprintf($errorFormat, $encoding));
  927. }
  928. }
  929. return $validEncoding;
  930. }
  931. }