[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/Requests/ -> IdnaEncoder.php (source)

   1  <?php
   2  
   3  namespace WpOrg\Requests;
   4  
   5  use WpOrg\Requests\Exception;
   6  use WpOrg\Requests\Exception\InvalidArgument;
   7  use WpOrg\Requests\Utility\InputValidator;
   8  
   9  /**
  10   * IDNA URL encoder
  11   *
  12   * Note: Not fully compliant, as nameprep does nothing yet.
  13   *
  14   * @package Requests\Utilities
  15   *
  16   * @link https://tools.ietf.org/html/rfc3490 IDNA specification
  17   * @link https://tools.ietf.org/html/rfc3492 Punycode/Bootstrap specification
  18   */
  19  class IdnaEncoder {
  20      /**
  21       * ACE prefix used for IDNA
  22       *
  23       * @link https://tools.ietf.org/html/rfc3490#section-5
  24       * @var string
  25       */
  26      const ACE_PREFIX = 'xn--';
  27  
  28      /**
  29       * Maximum length of a IDNA URL in ASCII.
  30       *
  31       * @see \WpOrg\Requests\IdnaEncoder::to_ascii()
  32       *
  33       * @since 2.0.0
  34       *
  35       * @var int
  36       */
  37      const MAX_LENGTH = 64;
  38  
  39      /**#@+
  40       * Bootstrap constant for Punycode
  41       *
  42       * @link https://tools.ietf.org/html/rfc3492#section-5
  43       * @var int
  44       */
  45      const BOOTSTRAP_BASE         = 36;
  46      const BOOTSTRAP_TMIN         = 1;
  47      const BOOTSTRAP_TMAX         = 26;
  48      const BOOTSTRAP_SKEW         = 38;
  49      const BOOTSTRAP_DAMP         = 700;
  50      const BOOTSTRAP_INITIAL_BIAS = 72;
  51      const BOOTSTRAP_INITIAL_N    = 128;
  52      /**#@-*/
  53  
  54      /**
  55       * Encode a hostname using Punycode
  56       *
  57       * @param string|Stringable $hostname Hostname
  58       * @return string Punycode-encoded hostname
  59       * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
  60       */
  61  	public static function encode($hostname) {
  62          if (InputValidator::is_string_or_stringable($hostname) === false) {
  63              throw InvalidArgument::create(1, '$hostname', 'string|Stringable', gettype($hostname));
  64          }
  65  
  66          $parts = explode('.', $hostname);
  67          foreach ($parts as &$part) {
  68              $part = self::to_ascii($part);
  69          }
  70          return implode('.', $parts);
  71      }
  72  
  73      /**
  74       * Convert a UTF-8 text string to an ASCII string using Punycode
  75       *
  76       * @param string $text ASCII or UTF-8 string (max length 64 characters)
  77       * @return string ASCII string
  78       *
  79       * @throws \WpOrg\Requests\Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`)
  80       * @throws \WpOrg\Requests\Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`)
  81       * @throws \WpOrg\Requests\Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`)
  82       * @throws \WpOrg\Requests\Exception Encoded string longer than 64 ASCII characters (`idna.encoded_too_long`)
  83       */
  84  	public static function to_ascii($text) {
  85          // Step 1: Check if the text is already ASCII
  86          if (self::is_ascii($text)) {
  87              // Skip to step 7
  88              if (strlen($text) < self::MAX_LENGTH) {
  89                  return $text;
  90              }
  91  
  92              throw new Exception('Provided string is too long', 'idna.provided_too_long', $text);
  93          }
  94  
  95          // Step 2: nameprep
  96          $text = self::nameprep($text);
  97  
  98          // Step 3: UseSTD3ASCIIRules is false, continue
  99          // Step 4: Check if it's ASCII now
 100          if (self::is_ascii($text)) {
 101              // Skip to step 7
 102              /*
 103               * As the `nameprep()` method returns the original string, this code will never be reached until
 104               * that method is properly implemented.
 105               */
 106              // @codeCoverageIgnoreStart
 107              if (strlen($text) < self::MAX_LENGTH) {
 108                  return $text;
 109              }
 110  
 111              throw new Exception('Prepared string is too long', 'idna.prepared_too_long', $text);
 112              // @codeCoverageIgnoreEnd
 113          }
 114  
 115          // Step 5: Check ACE prefix
 116          if (strpos($text, self::ACE_PREFIX) === 0) {
 117              throw new Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $text);
 118          }
 119  
 120          // Step 6: Encode with Punycode
 121          $text = self::punycode_encode($text);
 122  
 123          // Step 7: Prepend ACE prefix
 124          $text = self::ACE_PREFIX . $text;
 125  
 126          // Step 8: Check size
 127          if (strlen($text) < self::MAX_LENGTH) {
 128              return $text;
 129          }
 130  
 131          throw new Exception('Encoded string is too long', 'idna.encoded_too_long', $text);
 132      }
 133  
 134      /**
 135       * Check whether a given text string contains only ASCII characters
 136       *
 137       * @internal (Testing found regex was the fastest implementation)
 138       *
 139       * @param string $text
 140       * @return bool Is the text string ASCII-only?
 141       */
 142  	protected static function is_ascii($text) {
 143          return (preg_match('/(?:[^\x00-\x7F])/', $text) !== 1);
 144      }
 145  
 146      /**
 147       * Prepare a text string for use as an IDNA name
 148       *
 149       * @todo Implement this based on RFC 3491 and the newer 5891
 150       * @param string $text
 151       * @return string Prepared string
 152       */
 153  	protected static function nameprep($text) {
 154          return $text;
 155      }
 156  
 157      /**
 158       * Convert a UTF-8 string to a UCS-4 codepoint array
 159       *
 160       * Based on \WpOrg\Requests\Iri::replace_invalid_with_pct_encoding()
 161       *
 162       * @param string $input
 163       * @return array Unicode code points
 164       *
 165       * @throws \WpOrg\Requests\Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`)
 166       */
 167  	protected static function utf8_to_codepoints($input) {
 168          $codepoints = [];
 169  
 170          // Get number of bytes
 171          $strlen = strlen($input);
 172  
 173          // phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer -- This is a deliberate choice.
 174          for ($position = 0; $position < $strlen; $position++) {
 175              $value = ord($input[$position]);
 176  
 177              // One byte sequence:
 178              if ((~$value & 0x80) === 0x80) {
 179                  $character = $value;
 180                  $length    = 1;
 181                  $remaining = 0;
 182              }
 183              // Two byte sequence:
 184              elseif (($value & 0xE0) === 0xC0) {
 185                  $character = ($value & 0x1F) << 6;
 186                  $length    = 2;
 187                  $remaining = 1;
 188              }
 189              // Three byte sequence:
 190              elseif (($value & 0xF0) === 0xE0) {
 191                  $character = ($value & 0x0F) << 12;
 192                  $length    = 3;
 193                  $remaining = 2;
 194              }
 195              // Four byte sequence:
 196              elseif (($value & 0xF8) === 0xF0) {
 197                  $character = ($value & 0x07) << 18;
 198                  $length    = 4;
 199                  $remaining = 3;
 200              }
 201              // Invalid byte:
 202              else {
 203                  throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value);
 204              }
 205  
 206              if ($remaining > 0) {
 207                  if ($position + $length > $strlen) {
 208                      throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
 209                  }
 210                  for ($position++; $remaining > 0; $position++) {
 211                      $value = ord($input[$position]);
 212  
 213                      // If it is invalid, count the sequence as invalid and reprocess the current byte:
 214                      if (($value & 0xC0) !== 0x80) {
 215                          throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
 216                      }
 217  
 218                      --$remaining;
 219                      $character |= ($value & 0x3F) << ($remaining * 6);
 220                  }
 221                  $position--;
 222              }
 223  
 224              if (// Non-shortest form sequences are invalid
 225                  $length > 1 && $character <= 0x7F
 226                  || $length > 2 && $character <= 0x7FF
 227                  || $length > 3 && $character <= 0xFFFF
 228                  // Outside of range of ucschar codepoints
 229                  // Noncharacters
 230                  || ($character & 0xFFFE) === 0xFFFE
 231                  || $character >= 0xFDD0 && $character <= 0xFDEF
 232                  || (
 233                      // Everything else not in ucschar
 234                      $character > 0xD7FF && $character < 0xF900
 235                      || $character < 0x20
 236                      || $character > 0x7E && $character < 0xA0
 237                      || $character > 0xEFFFD
 238                  )
 239              ) {
 240                  throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
 241              }
 242  
 243              $codepoints[] = $character;
 244          }
 245  
 246          return $codepoints;
 247      }
 248  
 249      /**
 250       * RFC3492-compliant encoder
 251       *
 252       * @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code
 253       *
 254       * @param string $input UTF-8 encoded string to encode
 255       * @return string Punycode-encoded string
 256       *
 257       * @throws \WpOrg\Requests\Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`)
 258       */
 259  	public static function punycode_encode($input) {
 260          $output = '';
 261          // let n = initial_n
 262          $n = self::BOOTSTRAP_INITIAL_N;
 263          // let delta = 0
 264          $delta = 0;
 265          // let bias = initial_bias
 266          $bias = self::BOOTSTRAP_INITIAL_BIAS;
 267          // let h = b = the number of basic code points in the input
 268          $h = 0;
 269          $b = 0; // see loop
 270          // copy them to the output in order
 271          $codepoints = self::utf8_to_codepoints($input);
 272          $extended   = [];
 273  
 274          foreach ($codepoints as $char) {
 275              if ($char < 128) {
 276                  // Character is valid ASCII
 277                  // TODO: this should also check if it's valid for a URL
 278                  $output .= chr($char);
 279                  $h++;
 280              }
 281              // Check if the character is non-ASCII, but below initial n
 282              // This never occurs for Punycode, so ignore in coverage
 283              // @codeCoverageIgnoreStart
 284              elseif ($char < $n) {
 285                  throw new Exception('Invalid character', 'idna.character_outside_domain', $char);
 286              }
 287              // @codeCoverageIgnoreEnd
 288              else {
 289                  $extended[$char] = true;
 290              }
 291          }
 292          $extended = array_keys($extended);
 293          sort($extended);
 294          $b = $h;
 295          // [copy them] followed by a delimiter if b > 0
 296          if (strlen($output) > 0) {
 297              $output .= '-';
 298          }
 299          // {if the input contains a non-basic code point < n then fail}
 300          // while h < length(input) do begin
 301          $codepointcount = count($codepoints);
 302          while ($h < $codepointcount) {
 303              // let m = the minimum code point >= n in the input
 304              $m = array_shift($extended);
 305              //printf('next code point to insert is %s' . PHP_EOL, dechex($m));
 306              // let delta = delta + (m - n) * (h + 1), fail on overflow
 307              $delta += ($m - $n) * ($h + 1);
 308              // let n = m
 309              $n = $m;
 310              // for each code point c in the input (in order) do begin
 311              for ($num = 0; $num < $codepointcount; $num++) {
 312                  $c = $codepoints[$num];
 313                  // if c < n then increment delta, fail on overflow
 314                  if ($c < $n) {
 315                      $delta++;
 316                  }
 317                  // if c == n then begin
 318                  elseif ($c === $n) {
 319                      // let q = delta
 320                      $q = $delta;
 321                      // for k = base to infinity in steps of base do begin
 322                      for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) {
 323                          // let t = tmin if k <= bias {+ tmin}, or
 324                          //     tmax if k >= bias + tmax, or k - bias otherwise
 325                          if ($k <= ($bias + self::BOOTSTRAP_TMIN)) {
 326                              $t = self::BOOTSTRAP_TMIN;
 327                          }
 328                          elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) {
 329                              $t = self::BOOTSTRAP_TMAX;
 330                          }
 331                          else {
 332                              $t = $k - $bias;
 333                          }
 334                          // if q < t then break
 335                          if ($q < $t) {
 336                              break;
 337                          }
 338                          // output the code point for digit t + ((q - t) mod (base - t))
 339                          $digit   = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t));
 340                          $output .= self::digit_to_char($digit);
 341                          // let q = (q - t) div (base - t)
 342                          $q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t));
 343                      } // end
 344                      // output the code point for digit q
 345                      $output .= self::digit_to_char($q);
 346                      // let bias = adapt(delta, h + 1, test h equals b?)
 347                      $bias = self::adapt($delta, $h + 1, $h === $b);
 348                      // let delta = 0
 349                      $delta = 0;
 350                      // increment h
 351                      $h++;
 352                  } // end
 353              } // end
 354              // increment delta and n
 355              $delta++;
 356              $n++;
 357          } // end
 358  
 359          return $output;
 360      }
 361  
 362      /**
 363       * Convert a digit to its respective character
 364       *
 365       * @link https://tools.ietf.org/html/rfc3492#section-5
 366       *
 367       * @param int $digit Digit in the range 0-35
 368       * @return string Single character corresponding to digit
 369       *
 370       * @throws \WpOrg\Requests\Exception On invalid digit (`idna.invalid_digit`)
 371       */
 372  	protected static function digit_to_char($digit) {
 373          // @codeCoverageIgnoreStart
 374          // As far as I know, this never happens, but still good to be sure.
 375          if ($digit < 0 || $digit > 35) {
 376              throw new Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit);
 377          }
 378          // @codeCoverageIgnoreEnd
 379          $digits = 'abcdefghijklmnopqrstuvwxyz0123456789';
 380          return substr($digits, $digit, 1);
 381      }
 382  
 383      /**
 384       * Adapt the bias
 385       *
 386       * @link https://tools.ietf.org/html/rfc3492#section-6.1
 387       * @param int $delta
 388       * @param int $numpoints
 389       * @param bool $firsttime
 390       * @return int New bias
 391       *
 392       * function adapt(delta,numpoints,firsttime):
 393       */
 394  	protected static function adapt($delta, $numpoints, $firsttime) {
 395          // if firsttime then let delta = delta div damp
 396          if ($firsttime) {
 397              $delta = floor($delta / self::BOOTSTRAP_DAMP);
 398          }
 399          // else let delta = delta div 2
 400          else {
 401              $delta = floor($delta / 2);
 402          }
 403          // let delta = delta + (delta div numpoints)
 404          $delta += floor($delta / $numpoints);
 405          // let k = 0
 406          $k = 0;
 407          // while delta > ((base - tmin) * tmax) div 2 do begin
 408          $max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2);
 409          while ($delta > $max) {
 410              // let delta = delta div (base - tmin)
 411              $delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN));
 412              // let k = k + base
 413              $k += self::BOOTSTRAP_BASE;
 414          } // end
 415          // return k + (((base - tmin + 1) * delta) div (delta + skew))
 416          return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW));
 417      }
 418  }


Generated: Mon Dec 6 01:00:03 2021 Cross-referenced by PHPXref 0.7.1