Idn.php 29 KB

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