Idn.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com> and Trevor Rowbotham <trevor.rowbotham@pm.me>
  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\Intl\Idn;
  11. use Exception;
  12. use Normalizer;
  13. use Symfony\Polyfill\Intl\Idn\Resources\unidata\DisallowedRanges;
  14. use Symfony\Polyfill\Intl\Idn\Resources\unidata\Regex;
  15. /**
  16. * @see https://www.unicode.org/reports/tr46/
  17. *
  18. * @internal
  19. */
  20. final class Idn
  21. {
  22. public const ERROR_EMPTY_LABEL = 1;
  23. public const ERROR_LABEL_TOO_LONG = 2;
  24. public const ERROR_DOMAIN_NAME_TOO_LONG = 4;
  25. public const ERROR_LEADING_HYPHEN = 8;
  26. public const ERROR_TRAILING_HYPHEN = 0x10;
  27. public const ERROR_HYPHEN_3_4 = 0x20;
  28. public const ERROR_LEADING_COMBINING_MARK = 0x40;
  29. public const ERROR_DISALLOWED = 0x80;
  30. public const ERROR_PUNYCODE = 0x100;
  31. public const ERROR_LABEL_HAS_DOT = 0x200;
  32. public const ERROR_INVALID_ACE_LABEL = 0x400;
  33. public const ERROR_BIDI = 0x800;
  34. public const ERROR_CONTEXTJ = 0x1000;
  35. public const ERROR_CONTEXTO_PUNCTUATION = 0x2000;
  36. public const ERROR_CONTEXTO_DIGITS = 0x4000;
  37. public const INTL_IDNA_VARIANT_2003 = 0;
  38. public const INTL_IDNA_VARIANT_UTS46 = 1;
  39. public const IDNA_DEFAULT = 0;
  40. public const IDNA_ALLOW_UNASSIGNED = 1;
  41. public const IDNA_USE_STD3_RULES = 2;
  42. public const IDNA_CHECK_BIDI = 4;
  43. public const IDNA_CHECK_CONTEXTJ = 8;
  44. public const IDNA_NONTRANSITIONAL_TO_ASCII = 16;
  45. public const IDNA_NONTRANSITIONAL_TO_UNICODE = 32;
  46. public const MAX_DOMAIN_SIZE = 253;
  47. public const MAX_LABEL_SIZE = 63;
  48. public const BASE = 36;
  49. public const TMIN = 1;
  50. public const TMAX = 26;
  51. public const SKEW = 38;
  52. public const DAMP = 700;
  53. public const INITIAL_BIAS = 72;
  54. public const INITIAL_N = 128;
  55. public const DELIMITER = '-';
  56. public const MAX_INT = 2147483647;
  57. /**
  58. * Contains the numeric value of a basic code point (for use in representing integers) in the
  59. * range 0 to BASE-1, or -1 if b is does not represent a value.
  60. *
  61. * @var array<int, int>
  62. */
  63. private static $basicToDigit = [
  64. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  65. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  66. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  67. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -1,
  68. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  69. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  70. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  71. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  72. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  73. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  74. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  75. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  76. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  77. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  78. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  79. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  80. ];
  81. /**
  82. * @var array<int, int>
  83. */
  84. private static $virama;
  85. /**
  86. * @var array<int, string>
  87. */
  88. private static $mapped;
  89. /**
  90. * @var array<int, bool>
  91. */
  92. private static $ignored;
  93. /**
  94. * @var array<int, string>
  95. */
  96. private static $deviation;
  97. /**
  98. * @var array<int, bool>
  99. */
  100. private static $disallowed;
  101. /**
  102. * @var array<int, string>
  103. */
  104. private static $disallowed_STD3_mapped;
  105. /**
  106. * @var array<int, bool>
  107. */
  108. private static $disallowed_STD3_valid;
  109. /**
  110. * @var bool
  111. */
  112. private static $mappingTableLoaded = false;
  113. /**
  114. * @see https://www.unicode.org/reports/tr46/#ToASCII
  115. *
  116. * @param string $domainName
  117. * @param int $options
  118. * @param int $variant
  119. * @param array $idna_info
  120. *
  121. * @return string|false
  122. */
  123. public static function idn_to_ascii($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = [])
  124. {
  125. if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) {
  126. @trigger_error('idn_to_ascii(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED);
  127. }
  128. $options = [
  129. 'CheckHyphens' => true,
  130. 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI),
  131. 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ),
  132. 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES),
  133. 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_ASCII),
  134. 'VerifyDnsLength' => true,
  135. ];
  136. $info = new Info();
  137. $labels = self::process((string) $domainName, $options, $info);
  138. foreach ($labels as $i => $label) {
  139. // Only convert labels to punycode that contain non-ASCII code points
  140. if (1 === preg_match('/[^\x00-\x7F]/', $label)) {
  141. try {
  142. $label = 'xn--'.self::punycodeEncode($label);
  143. } catch (Exception $e) {
  144. $info->errors |= self::ERROR_PUNYCODE;
  145. }
  146. $labels[$i] = $label;
  147. }
  148. }
  149. if ($options['VerifyDnsLength']) {
  150. self::validateDomainAndLabelLength($labels, $info);
  151. }
  152. $idna_info = [
  153. 'result' => implode('.', $labels),
  154. 'isTransitionalDifferent' => $info->transitionalDifferent,
  155. 'errors' => $info->errors,
  156. ];
  157. return 0 === $info->errors ? $idna_info['result'] : false;
  158. }
  159. /**
  160. * @see https://www.unicode.org/reports/tr46/#ToUnicode
  161. *
  162. * @param string $domainName
  163. * @param int $options
  164. * @param int $variant
  165. * @param array $idna_info
  166. *
  167. * @return string|false
  168. */
  169. public static function idn_to_utf8($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = [])
  170. {
  171. if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) {
  172. @trigger_error('idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED);
  173. }
  174. $info = new Info();
  175. $labels = self::process((string) $domainName, [
  176. 'CheckHyphens' => true,
  177. 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI),
  178. 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ),
  179. 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES),
  180. 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_UNICODE),
  181. ], $info);
  182. $idna_info = [
  183. 'result' => implode('.', $labels),
  184. 'isTransitionalDifferent' => $info->transitionalDifferent,
  185. 'errors' => $info->errors,
  186. ];
  187. return 0 === $info->errors ? $idna_info['result'] : false;
  188. }
  189. /**
  190. * @param string $label
  191. *
  192. * @return bool
  193. */
  194. private static function isValidContextJ(array $codePoints, $label)
  195. {
  196. if (!isset(self::$virama)) {
  197. self::$virama = require __DIR__.\DIRECTORY_SEPARATOR.'Resources'.\DIRECTORY_SEPARATOR.'unidata'.\DIRECTORY_SEPARATOR.'virama.php';
  198. }
  199. $offset = 0;
  200. foreach ($codePoints as $i => $codePoint) {
  201. if (0x200C !== $codePoint && 0x200D !== $codePoint) {
  202. continue;
  203. }
  204. if (!isset($codePoints[$i - 1])) {
  205. return false;
  206. }
  207. // If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True;
  208. if (isset(self::$virama[$codePoints[$i - 1]])) {
  209. continue;
  210. }
  211. // If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C(Joining_Type:T)*(Joining_Type:{R,D})) Then
  212. // True;
  213. // Generated RegExp = ([Joining_Type:{L,D}][Joining_Type:T]*\u200C[Joining_Type:T]*)[Joining_Type:{R,D}]
  214. if (0x200C === $codePoint && 1 === preg_match(Regex::ZWNJ, $label, $matches, \PREG_OFFSET_CAPTURE, $offset)) {
  215. $offset += \strlen($matches[1][0]);
  216. continue;
  217. }
  218. return false;
  219. }
  220. return true;
  221. }
  222. /**
  223. * @see https://www.unicode.org/reports/tr46/#ProcessingStepMap
  224. *
  225. * @param string $input
  226. * @param array<string, bool> $options
  227. *
  228. * @return string
  229. */
  230. private static function mapCodePoints($input, array $options, Info $info)
  231. {
  232. $str = '';
  233. $useSTD3ASCIIRules = $options['UseSTD3ASCIIRules'];
  234. $transitional = $options['Transitional_Processing'];
  235. foreach (self::utf8Decode($input) as $codePoint) {
  236. $data = self::lookupCodePointStatus($codePoint, $useSTD3ASCIIRules);
  237. switch ($data['status']) {
  238. case 'disallowed':
  239. $info->errors |= self::ERROR_DISALLOWED;
  240. // no break.
  241. case 'valid':
  242. $str .= mb_chr($codePoint, 'utf-8');
  243. break;
  244. case 'ignored':
  245. // Do nothing.
  246. break;
  247. case 'mapped':
  248. $str .= $data['mapping'];
  249. break;
  250. case 'deviation':
  251. $info->transitionalDifferent = true;
  252. $str .= ($transitional ? $data['mapping'] : mb_chr($codePoint, 'utf-8'));
  253. break;
  254. }
  255. }
  256. return $str;
  257. }
  258. /**
  259. * @see https://www.unicode.org/reports/tr46/#Processing
  260. *
  261. * @param string $domain
  262. * @param array<string, bool> $options
  263. *
  264. * @return array<int, string>
  265. */
  266. private static function process($domain, array $options, Info $info)
  267. {
  268. // If VerifyDnsLength is not set, we are doing ToUnicode otherwise we are doing ToASCII and
  269. // we need to respect the VerifyDnsLength option.
  270. $checkForEmptyLabels = !isset($options['VerifyDnsLength']) || $options['VerifyDnsLength'];
  271. if ($checkForEmptyLabels && '' === $domain) {
  272. $info->errors |= self::ERROR_EMPTY_LABEL;
  273. return [$domain];
  274. }
  275. // Step 1. Map each code point in the domain name string
  276. $domain = self::mapCodePoints($domain, $options, $info);
  277. // Step 2. Normalize the domain name string to Unicode Normalization Form C.
  278. if (!Normalizer::isNormalized($domain, Normalizer::FORM_C)) {
  279. $domain = Normalizer::normalize($domain, Normalizer::FORM_C);
  280. }
  281. // Step 3. Break the string into labels at U+002E (.) FULL STOP.
  282. $labels = explode('.', $domain);
  283. $lastLabelIndex = \count($labels) - 1;
  284. // Step 4. Convert and validate each label in the domain name string.
  285. foreach ($labels as $i => $label) {
  286. $validationOptions = $options;
  287. if ('xn--' === substr($label, 0, 4)) {
  288. try {
  289. $label = self::punycodeDecode(substr($label, 4));
  290. } catch (Exception $e) {
  291. $info->errors |= self::ERROR_PUNYCODE;
  292. continue;
  293. }
  294. $validationOptions['Transitional_Processing'] = false;
  295. $labels[$i] = $label;
  296. }
  297. self::validateLabel($label, $info, $validationOptions, $i > 0 && $i === $lastLabelIndex);
  298. }
  299. if ($info->bidiDomain && !$info->validBidiDomain) {
  300. $info->errors |= self::ERROR_BIDI;
  301. }
  302. // Any input domain name string that does not record an error has been successfully
  303. // processed according to this specification. Conversely, if an input domain_name string
  304. // causes an error, then the processing of the input domain_name string fails. Determining
  305. // what to do with error input is up to the caller, and not in the scope of this document.
  306. return $labels;
  307. }
  308. /**
  309. * @see https://tools.ietf.org/html/rfc5893#section-2
  310. *
  311. * @param string $label
  312. */
  313. private static function validateBidiLabel($label, Info $info)
  314. {
  315. if (1 === preg_match(Regex::RTL_LABEL, $label)) {
  316. $info->bidiDomain = true;
  317. // Step 1. The first character must be a character with Bidi property L, R, or AL.
  318. // If it has the R or AL property, it is an RTL label
  319. if (1 !== preg_match(Regex::BIDI_STEP_1_RTL, $label)) {
  320. $info->validBidiDomain = false;
  321. return;
  322. }
  323. // Step 2. In an RTL label, only characters with the Bidi properties R, AL, AN, EN, ES,
  324. // CS, ET, ON, BN, or NSM are allowed.
  325. if (1 === preg_match(Regex::BIDI_STEP_2, $label)) {
  326. $info->validBidiDomain = false;
  327. return;
  328. }
  329. // Step 3. In an RTL label, the end of the label must be a character with Bidi property
  330. // R, AL, EN, or AN, followed by zero or more characters with Bidi property NSM.
  331. if (1 !== preg_match(Regex::BIDI_STEP_3, $label)) {
  332. $info->validBidiDomain = false;
  333. return;
  334. }
  335. // Step 4. In an RTL label, if an EN is present, no AN may be present, and vice versa.
  336. if (1 === preg_match(Regex::BIDI_STEP_4_AN, $label) && 1 === preg_match(Regex::BIDI_STEP_4_EN, $label)) {
  337. $info->validBidiDomain = false;
  338. return;
  339. }
  340. return;
  341. }
  342. // We are a LTR label
  343. // Step 1. The first character must be a character with Bidi property L, R, or AL.
  344. // If it has the L property, it is an LTR label.
  345. if (1 !== preg_match(Regex::BIDI_STEP_1_LTR, $label)) {
  346. $info->validBidiDomain = false;
  347. return;
  348. }
  349. // Step 5. In an LTR label, only characters with the Bidi properties L, EN,
  350. // ES, CS, ET, ON, BN, or NSM are allowed.
  351. if (1 === preg_match(Regex::BIDI_STEP_5, $label)) {
  352. $info->validBidiDomain = false;
  353. return;
  354. }
  355. // Step 6.In an LTR label, the end of the label must be a character with Bidi property L or
  356. // EN, followed by zero or more characters with Bidi property NSM.
  357. if (1 !== preg_match(Regex::BIDI_STEP_6, $label)) {
  358. $info->validBidiDomain = false;
  359. return;
  360. }
  361. }
  362. /**
  363. * @param array<int, string> $labels
  364. */
  365. private static function validateDomainAndLabelLength(array $labels, Info $info)
  366. {
  367. $maxDomainSize = self::MAX_DOMAIN_SIZE;
  368. $length = \count($labels);
  369. // Number of "." delimiters.
  370. $domainLength = $length - 1;
  371. // If the last label is empty and it is not the first label, then it is the root label.
  372. // Increase the max size by 1, making it 254, to account for the root label's "."
  373. // delimiter. This also means we don't need to check the last label's length for being too
  374. // long.
  375. if ($length > 1 && '' === $labels[$length - 1]) {
  376. ++$maxDomainSize;
  377. --$length;
  378. }
  379. for ($i = 0; $i < $length; ++$i) {
  380. $bytes = \strlen($labels[$i]);
  381. $domainLength += $bytes;
  382. if ($bytes > self::MAX_LABEL_SIZE) {
  383. $info->errors |= self::ERROR_LABEL_TOO_LONG;
  384. }
  385. }
  386. if ($domainLength > $maxDomainSize) {
  387. $info->errors |= self::ERROR_DOMAIN_NAME_TOO_LONG;
  388. }
  389. }
  390. /**
  391. * @see https://www.unicode.org/reports/tr46/#Validity_Criteria
  392. *
  393. * @param string $label
  394. * @param array<string, bool> $options
  395. * @param bool $canBeEmpty
  396. */
  397. private static function validateLabel($label, Info $info, array $options, $canBeEmpty)
  398. {
  399. if ('' === $label) {
  400. if (!$canBeEmpty && (!isset($options['VerifyDnsLength']) || $options['VerifyDnsLength'])) {
  401. $info->errors |= self::ERROR_EMPTY_LABEL;
  402. }
  403. return;
  404. }
  405. // Step 1. The label must be in Unicode Normalization Form C.
  406. if (!Normalizer::isNormalized($label, Normalizer::FORM_C)) {
  407. $info->errors |= self::ERROR_INVALID_ACE_LABEL;
  408. }
  409. $codePoints = self::utf8Decode($label);
  410. if ($options['CheckHyphens']) {
  411. // Step 2. If CheckHyphens, the label must not contain a U+002D HYPHEN-MINUS character
  412. // in both the thrid and fourth positions.
  413. if (isset($codePoints[2], $codePoints[3]) && 0x002D === $codePoints[2] && 0x002D === $codePoints[3]) {
  414. $info->errors |= self::ERROR_HYPHEN_3_4;
  415. }
  416. // Step 3. If CheckHyphens, the label must neither begin nor end with a U+002D
  417. // HYPHEN-MINUS character.
  418. if ('-' === substr($label, 0, 1)) {
  419. $info->errors |= self::ERROR_LEADING_HYPHEN;
  420. }
  421. if ('-' === substr($label, -1, 1)) {
  422. $info->errors |= self::ERROR_TRAILING_HYPHEN;
  423. }
  424. }
  425. // Step 4. The label must not contain a U+002E (.) FULL STOP.
  426. if (false !== strpos($label, '.')) {
  427. $info->errors |= self::ERROR_LABEL_HAS_DOT;
  428. }
  429. // Step 5. The label must not begin with a combining mark, that is: General_Category=Mark.
  430. if (1 === preg_match(Regex::COMBINING_MARK, $label)) {
  431. $info->errors |= self::ERROR_LEADING_COMBINING_MARK;
  432. }
  433. // Step 6. Each code point in the label must only have certain status values according to
  434. // Section 5, IDNA Mapping Table:
  435. $transitional = $options['Transitional_Processing'];
  436. $useSTD3ASCIIRules = $options['UseSTD3ASCIIRules'];
  437. foreach ($codePoints as $codePoint) {
  438. $data = self::lookupCodePointStatus($codePoint, $useSTD3ASCIIRules);
  439. $status = $data['status'];
  440. if ('valid' === $status || (!$transitional && 'deviation' === $status)) {
  441. continue;
  442. }
  443. $info->errors |= self::ERROR_DISALLOWED;
  444. break;
  445. }
  446. // Step 7. If CheckJoiners, the label must satisify the ContextJ rules from Appendix A, in
  447. // The Unicode Code Points and Internationalized Domain Names for Applications (IDNA)
  448. // [IDNA2008].
  449. if ($options['CheckJoiners'] && !self::isValidContextJ($codePoints, $label)) {
  450. $info->errors |= self::ERROR_CONTEXTJ;
  451. }
  452. // Step 8. If CheckBidi, and if the domain name is a Bidi domain name, then the label must
  453. // satisfy all six of the numbered conditions in [IDNA2008] RFC 5893, Section 2.
  454. if ($options['CheckBidi'] && (!$info->bidiDomain || $info->validBidiDomain)) {
  455. self::validateBidiLabel($label, $info);
  456. }
  457. }
  458. /**
  459. * @see https://tools.ietf.org/html/rfc3492#section-6.2
  460. *
  461. * @param string $input
  462. *
  463. * @return string
  464. */
  465. private static function punycodeDecode($input)
  466. {
  467. $n = self::INITIAL_N;
  468. $out = 0;
  469. $i = 0;
  470. $bias = self::INITIAL_BIAS;
  471. $lastDelimIndex = strrpos($input, self::DELIMITER);
  472. $b = false === $lastDelimIndex ? 0 : $lastDelimIndex;
  473. $inputLength = \strlen($input);
  474. $output = [];
  475. $bytes = array_map('ord', str_split($input));
  476. for ($j = 0; $j < $b; ++$j) {
  477. if ($bytes[$j] > 0x7F) {
  478. throw new Exception('Invalid input');
  479. }
  480. $output[$out++] = $input[$j];
  481. }
  482. if ($b > 0) {
  483. ++$b;
  484. }
  485. for ($in = $b; $in < $inputLength; ++$out) {
  486. $oldi = $i;
  487. $w = 1;
  488. for ($k = self::BASE; /* no condition */; $k += self::BASE) {
  489. if ($in >= $inputLength) {
  490. throw new Exception('Invalid input');
  491. }
  492. $digit = self::$basicToDigit[$bytes[$in++] & 0xFF];
  493. if ($digit < 0) {
  494. throw new Exception('Invalid input');
  495. }
  496. if ($digit > intdiv(self::MAX_INT - $i, $w)) {
  497. throw new Exception('Integer overflow');
  498. }
  499. $i += $digit * $w;
  500. if ($k <= $bias) {
  501. $t = self::TMIN;
  502. } elseif ($k >= $bias + self::TMAX) {
  503. $t = self::TMAX;
  504. } else {
  505. $t = $k - $bias;
  506. }
  507. if ($digit < $t) {
  508. break;
  509. }
  510. $baseMinusT = self::BASE - $t;
  511. if ($w > intdiv(self::MAX_INT, $baseMinusT)) {
  512. throw new Exception('Integer overflow');
  513. }
  514. $w *= $baseMinusT;
  515. }
  516. $outPlusOne = $out + 1;
  517. $bias = self::adaptBias($i - $oldi, $outPlusOne, 0 === $oldi);
  518. if (intdiv($i, $outPlusOne) > self::MAX_INT - $n) {
  519. throw new Exception('Integer overflow');
  520. }
  521. $n += intdiv($i, $outPlusOne);
  522. $i %= $outPlusOne;
  523. array_splice($output, $i++, 0, [mb_chr($n, 'utf-8')]);
  524. }
  525. return implode('', $output);
  526. }
  527. /**
  528. * @see https://tools.ietf.org/html/rfc3492#section-6.3
  529. *
  530. * @param string $input
  531. *
  532. * @return string
  533. */
  534. private static function punycodeEncode($input)
  535. {
  536. $n = self::INITIAL_N;
  537. $delta = 0;
  538. $out = 0;
  539. $bias = self::INITIAL_BIAS;
  540. $inputLength = 0;
  541. $output = '';
  542. $iter = self::utf8Decode($input);
  543. foreach ($iter as $codePoint) {
  544. ++$inputLength;
  545. if ($codePoint < 0x80) {
  546. $output .= \chr($codePoint);
  547. ++$out;
  548. }
  549. }
  550. $h = $out;
  551. $b = $out;
  552. if ($b > 0) {
  553. $output .= self::DELIMITER;
  554. ++$out;
  555. }
  556. while ($h < $inputLength) {
  557. $m = self::MAX_INT;
  558. foreach ($iter as $codePoint) {
  559. if ($codePoint >= $n && $codePoint < $m) {
  560. $m = $codePoint;
  561. }
  562. }
  563. if ($m - $n > intdiv(self::MAX_INT - $delta, $h + 1)) {
  564. throw new Exception('Integer overflow');
  565. }
  566. $delta += ($m - $n) * ($h + 1);
  567. $n = $m;
  568. foreach ($iter as $codePoint) {
  569. if ($codePoint < $n && 0 === ++$delta) {
  570. throw new Exception('Integer overflow');
  571. }
  572. if ($codePoint === $n) {
  573. $q = $delta;
  574. for ($k = self::BASE; /* no condition */; $k += self::BASE) {
  575. if ($k <= $bias) {
  576. $t = self::TMIN;
  577. } elseif ($k >= $bias + self::TMAX) {
  578. $t = self::TMAX;
  579. } else {
  580. $t = $k - $bias;
  581. }
  582. if ($q < $t) {
  583. break;
  584. }
  585. $qMinusT = $q - $t;
  586. $baseMinusT = self::BASE - $t;
  587. $output .= self::encodeDigit($t + ($qMinusT) % ($baseMinusT), false);
  588. ++$out;
  589. $q = intdiv($qMinusT, $baseMinusT);
  590. }
  591. $output .= self::encodeDigit($q, false);
  592. ++$out;
  593. $bias = self::adaptBias($delta, $h + 1, $h === $b);
  594. $delta = 0;
  595. ++$h;
  596. }
  597. }
  598. ++$delta;
  599. ++$n;
  600. }
  601. return $output;
  602. }
  603. /**
  604. * @see https://tools.ietf.org/html/rfc3492#section-6.1
  605. *
  606. * @param int $delta
  607. * @param int $numPoints
  608. * @param bool $firstTime
  609. *
  610. * @return int
  611. */
  612. private static function adaptBias($delta, $numPoints, $firstTime)
  613. {
  614. // xxx >> 1 is a faster way of doing intdiv(xxx, 2)
  615. $delta = $firstTime ? intdiv($delta, self::DAMP) : $delta >> 1;
  616. $delta += intdiv($delta, $numPoints);
  617. $k = 0;
  618. while ($delta > ((self::BASE - self::TMIN) * self::TMAX) >> 1) {
  619. $delta = intdiv($delta, self::BASE - self::TMIN);
  620. $k += self::BASE;
  621. }
  622. return $k + intdiv((self::BASE - self::TMIN + 1) * $delta, $delta + self::SKEW);
  623. }
  624. /**
  625. * @param int $d
  626. * @param bool $flag
  627. *
  628. * @return string
  629. */
  630. private static function encodeDigit($d, $flag)
  631. {
  632. return \chr($d + 22 + 75 * ($d < 26 ? 1 : 0) - (($flag ? 1 : 0) << 5));
  633. }
  634. /**
  635. * Takes a UTF-8 encoded string and converts it into a series of integer code points. Any
  636. * invalid byte sequences will be replaced by a U+FFFD replacement code point.
  637. *
  638. * @see https://encoding.spec.whatwg.org/#utf-8-decoder
  639. *
  640. * @param string $input
  641. *
  642. * @return array<int, int>
  643. */
  644. private static function utf8Decode($input)
  645. {
  646. $bytesSeen = 0;
  647. $bytesNeeded = 0;
  648. $lowerBoundary = 0x80;
  649. $upperBoundary = 0xBF;
  650. $codePoint = 0;
  651. $codePoints = [];
  652. $length = \strlen($input);
  653. for ($i = 0; $i < $length; ++$i) {
  654. $byte = \ord($input[$i]);
  655. if (0 === $bytesNeeded) {
  656. if ($byte >= 0x00 && $byte <= 0x7F) {
  657. $codePoints[] = $byte;
  658. continue;
  659. }
  660. if ($byte >= 0xC2 && $byte <= 0xDF) {
  661. $bytesNeeded = 1;
  662. $codePoint = $byte & 0x1F;
  663. } elseif ($byte >= 0xE0 && $byte <= 0xEF) {
  664. if (0xE0 === $byte) {
  665. $lowerBoundary = 0xA0;
  666. } elseif (0xED === $byte) {
  667. $upperBoundary = 0x9F;
  668. }
  669. $bytesNeeded = 2;
  670. $codePoint = $byte & 0xF;
  671. } elseif ($byte >= 0xF0 && $byte <= 0xF4) {
  672. if (0xF0 === $byte) {
  673. $lowerBoundary = 0x90;
  674. } elseif (0xF4 === $byte) {
  675. $upperBoundary = 0x8F;
  676. }
  677. $bytesNeeded = 3;
  678. $codePoint = $byte & 0x7;
  679. } else {
  680. $codePoints[] = 0xFFFD;
  681. }
  682. continue;
  683. }
  684. if ($byte < $lowerBoundary || $byte > $upperBoundary) {
  685. $codePoint = 0;
  686. $bytesNeeded = 0;
  687. $bytesSeen = 0;
  688. $lowerBoundary = 0x80;
  689. $upperBoundary = 0xBF;
  690. --$i;
  691. $codePoints[] = 0xFFFD;
  692. continue;
  693. }
  694. $lowerBoundary = 0x80;
  695. $upperBoundary = 0xBF;
  696. $codePoint = ($codePoint << 6) | ($byte & 0x3F);
  697. if (++$bytesSeen !== $bytesNeeded) {
  698. continue;
  699. }
  700. $codePoints[] = $codePoint;
  701. $codePoint = 0;
  702. $bytesNeeded = 0;
  703. $bytesSeen = 0;
  704. }
  705. // String unexpectedly ended, so append a U+FFFD code point.
  706. if (0 !== $bytesNeeded) {
  707. $codePoints[] = 0xFFFD;
  708. }
  709. return $codePoints;
  710. }
  711. /**
  712. * @param int $codePoint
  713. * @param bool $useSTD3ASCIIRules
  714. *
  715. * @return array{status: string, mapping?: string}
  716. */
  717. private static function lookupCodePointStatus($codePoint, $useSTD3ASCIIRules)
  718. {
  719. if (!self::$mappingTableLoaded) {
  720. self::$mappingTableLoaded = true;
  721. self::$mapped = require __DIR__.'/Resources/unidata/mapped.php';
  722. self::$ignored = require __DIR__.'/Resources/unidata/ignored.php';
  723. self::$deviation = require __DIR__.'/Resources/unidata/deviation.php';
  724. self::$disallowed = require __DIR__.'/Resources/unidata/disallowed.php';
  725. self::$disallowed_STD3_mapped = require __DIR__.'/Resources/unidata/disallowed_STD3_mapped.php';
  726. self::$disallowed_STD3_valid = require __DIR__.'/Resources/unidata/disallowed_STD3_valid.php';
  727. }
  728. if (isset(self::$mapped[$codePoint])) {
  729. return ['status' => 'mapped', 'mapping' => self::$mapped[$codePoint]];
  730. }
  731. if (isset(self::$ignored[$codePoint])) {
  732. return ['status' => 'ignored'];
  733. }
  734. if (isset(self::$deviation[$codePoint])) {
  735. return ['status' => 'deviation', 'mapping' => self::$deviation[$codePoint]];
  736. }
  737. if (isset(self::$disallowed[$codePoint]) || DisallowedRanges::inRange($codePoint)) {
  738. return ['status' => 'disallowed'];
  739. }
  740. $isDisallowedMapped = isset(self::$disallowed_STD3_mapped[$codePoint]);
  741. if ($isDisallowedMapped || isset(self::$disallowed_STD3_valid[$codePoint])) {
  742. $status = 'disallowed';
  743. if (!$useSTD3ASCIIRules) {
  744. $status = $isDisallowedMapped ? 'mapped' : 'valid';
  745. }
  746. if ($isDisallowedMapped) {
  747. return ['status' => $status, 'mapping' => self::$disallowed_STD3_mapped[$codePoint]];
  748. }
  749. return ['status' => $status];
  750. }
  751. return ['status' => 'valid'];
  752. }
  753. }