Idn.php 30 KB

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