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


Generated: Mon May 16 01:00:02 2022 Cross-referenced by PHPXref 0.7.1