[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> compat.php (source)

   1  <?php
   2  /**
   3   * WordPress implementation for PHP functions either missing from older PHP versions or not included by default.
   4   *
   5   * @package PHP
   6   * @access private
   7   */
   8  
   9  // If gettext isn't available
  10  if ( ! function_exists( '_' ) ) {
  11      function _( $string ) {
  12          return $string;
  13      }
  14  }
  15  
  16  /**
  17   * Returns whether PCRE/u (PCRE_UTF8 modifier) is available for use.
  18   *
  19   * @ignore
  20   * @since 4.2.2
  21   * @access private
  22   *
  23   * @staticvar string $utf8_pcre
  24   *
  25   * @param bool $set - Used for testing only
  26   *             null   : default - get PCRE/u capability
  27   *             false  : Used for testing - return false for future calls to this function
  28   *             'reset': Used for testing - restore default behavior of this function
  29   */
  30  function _wp_can_use_pcre_u( $set = null ) {
  31      static $utf8_pcre = 'reset';
  32  
  33      if ( null !== $set ) {
  34          $utf8_pcre = $set;
  35      }
  36  
  37      if ( 'reset' === $utf8_pcre ) {
  38          // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- intentional error generated to detect PCRE/u support.
  39          $utf8_pcre = @preg_match( '/^./u', 'a' );
  40      }
  41  
  42      return $utf8_pcre;
  43  }
  44  
  45  if ( ! function_exists( 'mb_substr' ) ) :
  46      /**
  47       * Compat function to mimic mb_substr().
  48       *
  49       * @ignore
  50       * @since 3.2.0
  51       *
  52       * @see _mb_substr()
  53       *
  54       * @param string      $str      The string to extract the substring from.
  55       * @param int         $start    Position to being extraction from in `$str`.
  56       * @param int|null    $length   Optional. Maximum number of characters to extract from `$str`.
  57       *                              Default null.
  58       * @param string|null $encoding Optional. Character encoding to use. Default null.
  59       * @return string Extracted substring.
  60       */
  61  	function mb_substr( $str, $start, $length = null, $encoding = null ) {
  62          return _mb_substr( $str, $start, $length, $encoding );
  63      }
  64  endif;
  65  
  66  /**
  67   * Internal compat function to mimic mb_substr().
  68   *
  69   * Only understands UTF-8 and 8bit.  All other character sets will be treated as 8bit.
  70   * For $encoding === UTF-8, the $str input is expected to be a valid UTF-8 byte sequence.
  71   * The behavior of this function for invalid inputs is undefined.
  72   *
  73   * @ignore
  74   * @since 3.2.0
  75   *
  76   * @param string      $str      The string to extract the substring from.
  77   * @param int         $start    Position to being extraction from in `$str`.
  78   * @param int|null    $length   Optional. Maximum number of characters to extract from `$str`.
  79   *                              Default null.
  80   * @param string|null $encoding Optional. Character encoding to use. Default null.
  81   * @return string Extracted substring.
  82   */
  83  function _mb_substr( $str, $start, $length = null, $encoding = null ) {
  84      if ( null === $encoding ) {
  85          $encoding = get_option( 'blog_charset' );
  86      }
  87  
  88      /*
  89       * The solution below works only for UTF-8, so in case of a different
  90       * charset just use built-in substr().
  91       */
  92      if ( ! in_array( $encoding, array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) ) {
  93          return is_null( $length ) ? substr( $str, $start ) : substr( $str, $start, $length );
  94      }
  95  
  96      if ( _wp_can_use_pcre_u() ) {
  97          // Use the regex unicode support to separate the UTF-8 characters into an array.
  98          preg_match_all( '/./us', $str, $match );
  99          $chars = is_null( $length ) ? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length );
 100          return implode( '', $chars );
 101      }
 102  
 103      $regex = '/(
 104          [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
 105          | [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
 106          | \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
 107          | [\xE1-\xEC][\x80-\xBF]{2}
 108          | \xED[\x80-\x9F][\x80-\xBF]
 109          | [\xEE-\xEF][\x80-\xBF]{2}
 110          | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
 111          | [\xF1-\xF3][\x80-\xBF]{3}
 112          | \xF4[\x80-\x8F][\x80-\xBF]{2}
 113      )/x';
 114  
 115      // Start with 1 element instead of 0 since the first thing we do is pop.
 116      $chars = array( '' );
 117      do {
 118          // We had some string left over from the last round, but we counted it in that last round.
 119          array_pop( $chars );
 120  
 121          /*
 122           * Split by UTF-8 character, limit to 1000 characters (last array element will contain
 123           * the rest of the string).
 124           */
 125          $pieces = preg_split( $regex, $str, 1000, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
 126  
 127          $chars = array_merge( $chars, $pieces );
 128  
 129          // If there's anything left over, repeat the loop.
 130      } while ( count( $pieces ) > 1 && $str = array_pop( $pieces ) );
 131  
 132      return join( '', array_slice( $chars, $start, $length ) );
 133  }
 134  
 135  if ( ! function_exists( 'mb_strlen' ) ) :
 136      /**
 137       * Compat function to mimic mb_strlen().
 138       *
 139       * @ignore
 140       * @since 4.2.0
 141       *
 142       * @see _mb_strlen()
 143       *
 144       * @param string      $str      The string to retrieve the character length from.
 145       * @param string|null $encoding Optional. Character encoding to use. Default null.
 146       * @return int String length of `$str`.
 147       */
 148  	function mb_strlen( $str, $encoding = null ) {
 149          return _mb_strlen( $str, $encoding );
 150      }
 151  endif;
 152  
 153  /**
 154   * Internal compat function to mimic mb_strlen().
 155   *
 156   * Only understands UTF-8 and 8bit.  All other character sets will be treated as 8bit.
 157   * For $encoding === UTF-8, the `$str` input is expected to be a valid UTF-8 byte
 158   * sequence. The behavior of this function for invalid inputs is undefined.
 159   *
 160   * @ignore
 161   * @since 4.2.0
 162   *
 163   * @param string      $str      The string to retrieve the character length from.
 164   * @param string|null $encoding Optional. Character encoding to use. Default null.
 165   * @return int String length of `$str`.
 166   */
 167  function _mb_strlen( $str, $encoding = null ) {
 168      if ( null === $encoding ) {
 169          $encoding = get_option( 'blog_charset' );
 170      }
 171  
 172      /*
 173       * The solution below works only for UTF-8, so in case of a different charset
 174       * just use built-in strlen().
 175       */
 176      if ( ! in_array( $encoding, array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) ) {
 177          return strlen( $str );
 178      }
 179  
 180      if ( _wp_can_use_pcre_u() ) {
 181          // Use the regex unicode support to separate the UTF-8 characters into an array.
 182          preg_match_all( '/./us', $str, $match );
 183          return count( $match[0] );
 184      }
 185  
 186      $regex = '/(?:
 187          [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
 188          | [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
 189          | \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
 190          | [\xE1-\xEC][\x80-\xBF]{2}
 191          | \xED[\x80-\x9F][\x80-\xBF]
 192          | [\xEE-\xEF][\x80-\xBF]{2}
 193          | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
 194          | [\xF1-\xF3][\x80-\xBF]{3}
 195          | \xF4[\x80-\x8F][\x80-\xBF]{2}
 196      )/x';
 197  
 198      // Start at 1 instead of 0 since the first thing we do is decrement.
 199      $count = 1;
 200      do {
 201          // We had some string left over from the last round, but we counted it in that last round.
 202          $count--;
 203  
 204          /*
 205           * Split by UTF-8 character, limit to 1000 characters (last array element will contain
 206           * the rest of the string).
 207           */
 208          $pieces = preg_split( $regex, $str, 1000 );
 209  
 210          // Increment.
 211          $count += count( $pieces );
 212  
 213          // If there's anything left over, repeat the loop.
 214      } while ( $str = array_pop( $pieces ) );
 215  
 216      // Fencepost: preg_split() always returns one extra item in the array.
 217      return --$count;
 218  }
 219  
 220  if ( ! function_exists( 'hash_hmac' ) ) :
 221      /**
 222       * Compat function to mimic hash_hmac().
 223       *
 224       * The Hash extension is bundled with PHP by default since PHP 5.1.2.
 225       * However, the extension may be explicitly disabled on select servers.
 226       * As of PHP 7.4.0, the Hash extension is a core PHP extension and can no
 227       * longer be disabled.
 228       * I.e. when PHP 7.4.0 becomes the minimum requirement, this polyfill
 229       * and the associated `_hash_hmac()` function can be safely removed.
 230       *
 231       * @ignore
 232       * @since 3.2.0
 233       *
 234       * @see _hash_hmac()
 235       *
 236       * @param string $algo       Hash algorithm. Accepts 'md5' or 'sha1'.
 237       * @param string $data       Data to be hashed.
 238       * @param string $key        Secret key to use for generating the hash.
 239       * @param bool   $raw_output Optional. Whether to output raw binary data (true),
 240       *                           or lowercase hexits (false). Default false.
 241       * @return string|false The hash in output determined by `$raw_output`. False if `$algo`
 242       *                      is unknown or invalid.
 243       */
 244  	function hash_hmac( $algo, $data, $key, $raw_output = false ) {
 245          return _hash_hmac( $algo, $data, $key, $raw_output );
 246      }
 247  endif;
 248  
 249  /**
 250   * Internal compat function to mimic hash_hmac().
 251   *
 252   * @ignore
 253   * @since 3.2.0
 254   *
 255   * @param string $algo       Hash algorithm. Accepts 'md5' or 'sha1'.
 256   * @param string $data       Data to be hashed.
 257   * @param string $key        Secret key to use for generating the hash.
 258   * @param bool   $raw_output Optional. Whether to output raw binary data (true),
 259   *                           or lowercase hexits (false). Default false.
 260   * @return string|false The hash in output determined by `$raw_output`. False if `$algo`
 261   *                      is unknown or invalid.
 262   */
 263  function _hash_hmac( $algo, $data, $key, $raw_output = false ) {
 264      $packs = array(
 265          'md5'  => 'H32',
 266          'sha1' => 'H40',
 267      );
 268  
 269      if ( ! isset( $packs[ $algo ] ) ) {
 270          return false;
 271      }
 272  
 273      $pack = $packs[ $algo ];
 274  
 275      if ( strlen( $key ) > 64 ) {
 276          $key = pack( $pack, $algo( $key ) );
 277      }
 278  
 279      $key = str_pad( $key, 64, chr( 0 ) );
 280  
 281      $ipad = ( substr( $key, 0, 64 ) ^ str_repeat( chr( 0x36 ), 64 ) );
 282      $opad = ( substr( $key, 0, 64 ) ^ str_repeat( chr( 0x5C ), 64 ) );
 283  
 284      $hmac = $algo( $opad . pack( $pack, $algo( $ipad . $data ) ) );
 285  
 286      if ( $raw_output ) {
 287          return pack( $pack, $hmac );
 288      }
 289      return $hmac;
 290  }
 291  
 292  if ( ! function_exists( 'json_encode' ) ) {
 293  	function json_encode( $string ) {
 294          global $wp_json;
 295  
 296          if ( ! ( $wp_json instanceof Services_JSON ) ) {
 297              require_once ( ABSPATH . WPINC . '/class-json.php' );
 298              $wp_json = new Services_JSON();
 299          }
 300  
 301          return $wp_json->encodeUnsafe( $string );
 302      }
 303  }
 304  
 305  if ( ! function_exists( 'json_decode' ) ) {
 306      /**
 307       * @global Services_JSON $wp_json
 308       * @param string $string
 309       * @param bool   $assoc_array
 310       * @return object|array
 311       */
 312  	function json_decode( $string, $assoc_array = false ) {
 313          global $wp_json;
 314  
 315          if ( ! ( $wp_json instanceof Services_JSON ) ) {
 316              require_once ( ABSPATH . WPINC . '/class-json.php' );
 317              $wp_json = new Services_JSON();
 318          }
 319  
 320          $res = $wp_json->decode( $string );
 321          if ( $assoc_array ) {
 322              $res = _json_decode_object_helper( $res );
 323          }
 324          return $res;
 325      }
 326  
 327      /**
 328       * @param object $data
 329       * @return array
 330       */
 331  	function _json_decode_object_helper( $data ) {
 332          if ( is_object( $data ) ) {
 333              $data = get_object_vars( $data );
 334          }
 335          return is_array( $data ) ? array_map( __FUNCTION__, $data ) : $data;
 336      }
 337  }
 338  
 339  if ( ! function_exists( 'hash_equals' ) ) :
 340      /**
 341       * Timing attack safe string comparison
 342       *
 343       * Compares two strings using the same time whether they're equal or not.
 344       *
 345       * Note: It can leak the length of a string when arguments of differing length are supplied.
 346       *
 347       * This function was added in PHP 5.6.
 348       * However, the Hash extension may be explicitly disabled on select servers.
 349       * As of PHP 7.4.0, the Hash extension is a core PHP extension and can no
 350       * longer be disabled.
 351       * I.e. when PHP 7.4.0 becomes the minimum requirement, this polyfill
 352       * can be safely removed.
 353       *
 354       * @since 3.9.2
 355       *
 356       * @param string $a Expected string.
 357       * @param string $b Actual, user supplied, string.
 358       * @return bool Whether strings are equal.
 359       */
 360  	function hash_equals( $a, $b ) {
 361          $a_length = strlen( $a );
 362          if ( $a_length !== strlen( $b ) ) {
 363              return false;
 364          }
 365          $result = 0;
 366  
 367          // Do not attempt to "optimize" this.
 368          for ( $i = 0; $i < $a_length; $i++ ) {
 369              $result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
 370          }
 371  
 372          return $result === 0;
 373      }
 374  endif;
 375  
 376  // JSON_PRETTY_PRINT was introduced in PHP 5.4
 377  // Defined here to prevent a notice when using it with wp_json_encode()
 378  if ( ! defined( 'JSON_PRETTY_PRINT' ) ) {
 379      define( 'JSON_PRETTY_PRINT', 128 );
 380  }
 381  
 382  if ( ! function_exists( 'json_last_error_msg' ) ) :
 383      /**
 384       * Retrieves the error string of the last json_encode() or json_decode() call.
 385       *
 386       * @since 4.4.0
 387       *
 388       * @internal This is a compatibility function for PHP <5.5
 389       *
 390       * @return bool|string Returns the error message on success, "No Error" if no error has occurred,
 391       *                     or false on failure.
 392       */
 393  	function json_last_error_msg() {
 394          // See https://core.trac.wordpress.org/ticket/27799.
 395          if ( ! function_exists( 'json_last_error' ) ) {
 396              return false;
 397          }
 398  
 399          $last_error_code = json_last_error();
 400  
 401          // Just in case JSON_ERROR_NONE is not defined.
 402          $error_code_none = defined( 'JSON_ERROR_NONE' ) ? JSON_ERROR_NONE : 0;
 403  
 404          switch ( true ) {
 405              case $last_error_code === $error_code_none:
 406                  return 'No error';
 407  
 408              case defined( 'JSON_ERROR_DEPTH' ) && JSON_ERROR_DEPTH === $last_error_code:
 409                  return 'Maximum stack depth exceeded';
 410  
 411              case defined( 'JSON_ERROR_STATE_MISMATCH' ) && JSON_ERROR_STATE_MISMATCH === $last_error_code:
 412                  return 'State mismatch (invalid or malformed JSON)';
 413  
 414              case defined( 'JSON_ERROR_CTRL_CHAR' ) && JSON_ERROR_CTRL_CHAR === $last_error_code:
 415                  return 'Control character error, possibly incorrectly encoded';
 416  
 417              case defined( 'JSON_ERROR_SYNTAX' ) && JSON_ERROR_SYNTAX === $last_error_code:
 418                  return 'Syntax error';
 419  
 420              case defined( 'JSON_ERROR_UTF8' ) && JSON_ERROR_UTF8 === $last_error_code:
 421                  return 'Malformed UTF-8 characters, possibly incorrectly encoded';
 422  
 423              case defined( 'JSON_ERROR_RECURSION' ) && JSON_ERROR_RECURSION === $last_error_code:
 424                  return 'Recursion detected';
 425  
 426              case defined( 'JSON_ERROR_INF_OR_NAN' ) && JSON_ERROR_INF_OR_NAN === $last_error_code:
 427                  return 'Inf and NaN cannot be JSON encoded';
 428  
 429              case defined( 'JSON_ERROR_UNSUPPORTED_TYPE' ) && JSON_ERROR_UNSUPPORTED_TYPE === $last_error_code:
 430                  return 'Type is not supported';
 431  
 432              default:
 433                  return 'An unknown error occurred';
 434          }
 435      }
 436  endif;
 437  
 438  if ( ! interface_exists( 'JsonSerializable' ) ) {
 439      define( 'WP_JSON_SERIALIZE_COMPATIBLE', true );
 440      /**
 441       * JsonSerializable interface.
 442       *
 443       * Compatibility shim for PHP <5.4
 444       *
 445       * @link https://secure.php.net/jsonserializable
 446       *
 447       * @since 4.4.0
 448       */
 449      interface JsonSerializable {
 450          // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
 451  		public function jsonSerialize();
 452      }
 453  }
 454  
 455  // random_int was introduced in PHP 7.0
 456  if ( ! function_exists( 'random_int' ) ) {
 457      require  ABSPATH . WPINC . '/random_compat/random.php';
 458  }
 459  // sodium_crypto_box was introduced in PHP 7.2
 460  if ( ! function_exists( 'sodium_crypto_box' ) ) {
 461      require  ABSPATH . WPINC . '/sodium_compat/autoload.php';
 462  }
 463  
 464  if ( ! function_exists( 'is_countable' ) ) {
 465      /**
 466       * Polyfill for is_countable() function added in PHP 7.3.
 467       *
 468       * Verify that the content of a variable is an array or an object
 469       * implementing the Countable interface.
 470       *
 471       * @since 4.9.6
 472       *
 473       * @param mixed $var The value to check.
 474       *
 475       * @return bool True if `$var` is countable, false otherwise.
 476       */
 477  	function is_countable( $var ) {
 478          return ( is_array( $var )
 479              || $var instanceof Countable
 480              || $var instanceof SimpleXMLElement
 481              || $var instanceof ResourceBundle
 482          );
 483      }
 484  }
 485  
 486  if ( ! function_exists( 'is_iterable' ) ) {
 487      /**
 488       * Polyfill for is_iterable() function added in PHP 7.1.
 489       *
 490       * Verify that the content of a variable is an array or an object
 491       * implementing the Traversable interface.
 492       *
 493       * @since 4.9.6
 494       *
 495       * @param mixed $var The value to check.
 496       *
 497       * @return bool True if `$var` is iterable, false otherwise.
 498       */
 499  	function is_iterable( $var ) {
 500          return ( is_array( $var ) || $var instanceof Traversable );
 501      }
 502  }


Generated: Sun Sep 15 01:00:03 2019 Cross-referenced by PHPXref 0.7.1