[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Main WordPress API
   4   *
   5   * @package WordPress
   6   */
   7  
   8  require  ABSPATH . WPINC . '/option.php';
   9  
  10  /**
  11   * Convert given MySQL date string into a different format.
  12   *
  13   * `$format` should be a PHP date format string.
  14   * 'U' and 'G' formats will return a sum of timestamp with timezone offset.
  15   * `$date` is expected to be local time in MySQL format (`Y-m-d H:i:s`).
  16   *
  17   * Historically UTC time could be passed to the function to produce Unix timestamp.
  18   *
  19   * If `$translate` is true then the given date and format string will
  20   * be passed to `wp_date()` for translation.
  21   *
  22   * @since 0.71
  23   *
  24   * @param string $format    Format of the date to return.
  25   * @param string $date      Date string to convert.
  26   * @param bool   $translate Whether the return date should be translated. Default true.
  27   * @return string|int|false Formatted date string or sum of Unix timestamp and timezone offset.
  28   *                          False on failure.
  29   */
  30  function mysql2date( $format, $date, $translate = true ) {
  31      if ( empty( $date ) ) {
  32          return false;
  33      }
  34  
  35      $datetime = date_create( $date, wp_timezone() );
  36  
  37      if ( false === $datetime ) {
  38          return false;
  39      }
  40  
  41      // Returns a sum of timestamp with timezone offset. Ideally should never be used.
  42      if ( 'G' === $format || 'U' === $format ) {
  43          return $datetime->getTimestamp() + $datetime->getOffset();
  44      }
  45  
  46      if ( $translate ) {
  47          return wp_date( $format, $datetime->getTimestamp() );
  48      }
  49  
  50      return $datetime->format( $format );
  51  }
  52  
  53  /**
  54   * Retrieves the current time based on specified type.
  55   *
  56   * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  57   * The 'timestamp' type will return the current timestamp or a sum of timestamp
  58   * and timezone offset, depending on `$gmt`.
  59   * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  60   *
  61   * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  62   * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  63   *
  64   * @since 1.0.0
  65   *
  66   * @param string   $type Type of time to retrieve. Accepts 'mysql', 'timestamp',
  67   *                       or PHP date format string (e.g. 'Y-m-d').
  68   * @param int|bool $gmt  Optional. Whether to use GMT timezone. Default false.
  69   * @return int|string Integer if $type is 'timestamp', string otherwise.
  70   */
  71  function current_time( $type, $gmt = 0 ) {
  72      // Don't use non-GMT timestamp, unless you know the difference and really need to.
  73      if ( 'timestamp' === $type || 'U' === $type ) {
  74          return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  75      }
  76  
  77      if ( 'mysql' === $type ) {
  78          $type = 'Y-m-d H:i:s';
  79      }
  80  
  81      $timezone = $gmt ? new DateTimeZone( 'UTC' ) : wp_timezone();
  82      $datetime = new DateTime( 'now', $timezone );
  83  
  84      return $datetime->format( $type );
  85  }
  86  
  87  /**
  88   * Retrieves the current time as an object with the timezone from settings.
  89   *
  90   * @since 5.3.0
  91   *
  92   * @return DateTimeImmutable Date and time object.
  93   */
  94  function current_datetime() {
  95      return new DateTimeImmutable( 'now', wp_timezone() );
  96  }
  97  
  98  /**
  99   * Retrieves the timezone from site settings as a string.
 100   *
 101   * Uses the `timezone_string` option to get a proper timezone if available,
 102   * otherwise falls back to an offset.
 103   *
 104   * @since 5.3.0
 105   *
 106   * @return string PHP timezone string or a ±HH:MM offset.
 107   */
 108  function wp_timezone_string() {
 109      $timezone_string = get_option( 'timezone_string' );
 110  
 111      if ( $timezone_string ) {
 112          return $timezone_string;
 113      }
 114  
 115      $offset  = (float) get_option( 'gmt_offset' );
 116      $hours   = (int) $offset;
 117      $minutes = ( $offset - $hours );
 118  
 119      $sign      = ( $offset < 0 ) ? '-' : '+';
 120      $abs_hour  = abs( $hours );
 121      $abs_mins  = abs( $minutes * 60 );
 122      $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );
 123  
 124      return $tz_offset;
 125  }
 126  
 127  /**
 128   * Retrieves the timezone from site settings as a `DateTimeZone` object.
 129   *
 130   * Timezone can be based on a PHP timezone string or a ±HH:MM offset.
 131   *
 132   * @since 5.3.0
 133   *
 134   * @return DateTimeZone Timezone object.
 135   */
 136  function wp_timezone() {
 137      return new DateTimeZone( wp_timezone_string() );
 138  }
 139  
 140  /**
 141   * Retrieves the date in localized format, based on a sum of Unix timestamp and
 142   * timezone offset in seconds.
 143   *
 144   * If the locale specifies the locale month and weekday, then the locale will
 145   * take over the format for the date. If it isn't, then the date format string
 146   * will be used instead.
 147   *
 148   * Note that due to the way WP typically generates a sum of timestamp and offset
 149   * with `strtotime()`, it implies offset added at a _current_ time, not at the time
 150   * the timestamp represents. Storing such timestamps or calculating them differently
 151   * will lead to invalid output.
 152   *
 153   * @since 0.71
 154   * @since 5.3.0 Converted into a wrapper for wp_date().
 155   *
 156   * @global WP_Locale $wp_locale WordPress date and time locale object.
 157   *
 158   * @param string   $format                Format to display the date.
 159   * @param int|bool $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset
 160   *                                        in seconds. Default false.
 161   * @param bool     $gmt                   Optional. Whether to use GMT timezone. Only applies
 162   *                                        if timestamp is not provided. Default false.
 163   * @return string The date, translated if locale specifies it.
 164   */
 165  function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
 166      $timestamp = $timestamp_with_offset;
 167  
 168      // If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
 169      if ( ! is_numeric( $timestamp ) ) {
 170          $timestamp = current_time( 'timestamp', $gmt );
 171      }
 172  
 173      /*
 174       * This is a legacy implementation quirk that the returned timestamp is also with offset.
 175       * Ideally this function should never be used to produce a timestamp.
 176       */
 177      if ( 'U' === $format ) {
 178          $date = $timestamp;
 179      } elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
 180          $date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
 181      } elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
 182          $date = wp_date( $format );
 183      } else {
 184          /*
 185           * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
 186           * This is the best attempt to reverse that operation into a local time to use.
 187           */
 188          $local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
 189          $timezone   = wp_timezone();
 190          $datetime   = date_create( $local_time, $timezone );
 191          $date       = wp_date( $format, $datetime->getTimestamp(), $timezone );
 192      }
 193  
 194      /**
 195       * Filters the date formatted based on the locale.
 196       *
 197       * @since 2.8.0
 198       *
 199       * @param string $date      Formatted date string.
 200       * @param string $format    Format to display the date.
 201       * @param int    $timestamp A sum of Unix timestamp and timezone offset in seconds.
 202       *                          Might be without offset if input omitted timestamp but requested GMT.
 203       * @param bool   $gmt       Whether to use GMT timezone. Only applies if timestamp was not provided.
 204       *                          Default false.
 205       */
 206      $date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );
 207  
 208      return $date;
 209  }
 210  
 211  /**
 212   * Retrieves the date, in localized format.
 213   *
 214   * This is a newer function, intended to replace `date_i18n()` without legacy quirks in it.
 215   *
 216   * Note that, unlike `date_i18n()`, this function accepts a true Unix timestamp, not summed
 217   * with timezone offset.
 218   *
 219   * @since 5.3.0
 220   *
 221   * @param string       $format    PHP date format.
 222   * @param int          $timestamp Optional. Unix timestamp. Defaults to current time.
 223   * @param DateTimeZone $timezone  Optional. Timezone to output result in. Defaults to timezone
 224   *                                from site settings.
 225   * @return string|false The date, translated if locale specifies it. False on invalid timestamp input.
 226   */
 227  function wp_date( $format, $timestamp = null, $timezone = null ) {
 228      global $wp_locale;
 229  
 230      if ( null === $timestamp ) {
 231          $timestamp = time();
 232      } elseif ( ! is_numeric( $timestamp ) ) {
 233          return false;
 234      }
 235  
 236      if ( ! $timezone ) {
 237          $timezone = wp_timezone();
 238      }
 239  
 240      $datetime = date_create( '@' . $timestamp );
 241      $datetime->setTimezone( $timezone );
 242  
 243      if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) {
 244          $date = $datetime->format( $format );
 245      } else {
 246          // We need to unpack shorthand `r` format because it has parts that might be localized.
 247          $format = preg_replace( '/(?<!\\\\)r/', DATE_RFC2822, $format );
 248  
 249          $new_format    = '';
 250          $format_length = strlen( $format );
 251          $month         = $wp_locale->get_month( $datetime->format( 'm' ) );
 252          $weekday       = $wp_locale->get_weekday( $datetime->format( 'w' ) );
 253  
 254          for ( $i = 0; $i < $format_length; $i ++ ) {
 255              switch ( $format[ $i ] ) {
 256                  case 'D':
 257                      $new_format .= addcslashes( $wp_locale->get_weekday_abbrev( $weekday ), '\\A..Za..z' );
 258                      break;
 259                  case 'F':
 260                      $new_format .= addcslashes( $month, '\\A..Za..z' );
 261                      break;
 262                  case 'l':
 263                      $new_format .= addcslashes( $weekday, '\\A..Za..z' );
 264                      break;
 265                  case 'M':
 266                      $new_format .= addcslashes( $wp_locale->get_month_abbrev( $month ), '\\A..Za..z' );
 267                      break;
 268                  case 'a':
 269                      $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'a' ) ), '\\A..Za..z' );
 270                      break;
 271                  case 'A':
 272                      $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'A' ) ), '\\A..Za..z' );
 273                      break;
 274                  case '\\':
 275                      $new_format .= $format[ $i ];
 276  
 277                      // If character follows a slash, we add it without translating.
 278                      if ( $i < $format_length ) {
 279                          $new_format .= $format[ ++$i ];
 280                      }
 281                      break;
 282                  default:
 283                      $new_format .= $format[ $i ];
 284                      break;
 285              }
 286          }
 287  
 288          $date = $datetime->format( $new_format );
 289          $date = wp_maybe_decline_date( $date, $format );
 290      }
 291  
 292      /**
 293       * Filters the date formatted based on the locale.
 294       *
 295       * @since 5.3.0
 296       *
 297       * @param string       $date      Formatted date string.
 298       * @param string       $format    Format to display the date.
 299       * @param int          $timestamp Unix timestamp.
 300       * @param DateTimeZone $timezone  Timezone.
 301       */
 302      $date = apply_filters( 'wp_date', $date, $format, $timestamp, $timezone );
 303  
 304      return $date;
 305  }
 306  
 307  /**
 308   * Determines if the date should be declined.
 309   *
 310   * If the locale specifies that month names require a genitive case in certain
 311   * formats (like 'j F Y'), the month name will be replaced with a correct form.
 312   *
 313   * @since 4.4.0
 314   * @since 5.4.0 The `$format` parameter was added.
 315   *
 316   * @global WP_Locale $wp_locale WordPress date and time locale object.
 317   *
 318   * @param string $date   Formatted date string.
 319   * @param string $format Optional. Date format to check. Default empty string.
 320   * @return string The date, declined if locale specifies it.
 321   */
 322  function wp_maybe_decline_date( $date, $format = '' ) {
 323      global $wp_locale;
 324  
 325      // i18n functions are not available in SHORTINIT mode.
 326      if ( ! function_exists( '_x' ) ) {
 327          return $date;
 328      }
 329  
 330      /*
 331       * translators: If months in your language require a genitive case,
 332       * translate this to 'on'. Do not translate into your own language.
 333       */
 334      if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
 335  
 336          $months          = $wp_locale->month;
 337          $months_genitive = $wp_locale->month_genitive;
 338  
 339          /*
 340           * Match a format like 'j F Y' or 'j. F' (day of the month, followed by month name)
 341           * and decline the month.
 342           */
 343          if ( $format ) {
 344              $decline = preg_match( '#[dj]\.? F#', $format );
 345          } else {
 346              // If the format is not passed, try to guess it from the date string.
 347              $decline = preg_match( '#\b\d{1,2}\.? [^\d ]+\b#u', $date );
 348          }
 349  
 350          if ( $decline ) {
 351              foreach ( $months as $key => $month ) {
 352                  $months[ $key ] = '# ' . preg_quote( $month, '#' ) . '\b#u';
 353              }
 354  
 355              foreach ( $months_genitive as $key => $month ) {
 356                  $months_genitive[ $key ] = ' ' . $month;
 357              }
 358  
 359              $date = preg_replace( $months, $months_genitive, $date );
 360          }
 361  
 362          /*
 363           * Match a format like 'F jS' or 'F j' (month name, followed by day with an optional ordinal suffix)
 364           * and change it to declined 'j F'.
 365           */
 366          if ( $format ) {
 367              $decline = preg_match( '#F [dj]#', $format );
 368          } else {
 369              // If the format is not passed, try to guess it from the date string.
 370              $decline = preg_match( '#\b[^\d ]+ \d{1,2}(st|nd|rd|th)?\b#u', trim( $date ) );
 371          }
 372  
 373          if ( $decline ) {
 374              foreach ( $months as $key => $month ) {
 375                  $months[ $key ] = '#\b' . preg_quote( $month, '#' ) . ' (\d{1,2})(st|nd|rd|th)?([-–]\d{1,2})?(st|nd|rd|th)?\b#u';
 376              }
 377  
 378              foreach ( $months_genitive as $key => $month ) {
 379                  $months_genitive[ $key ] = '$1$3 ' . $month;
 380              }
 381  
 382              $date = preg_replace( $months, $months_genitive, $date );
 383          }
 384      }
 385  
 386      // Used for locale-specific rules.
 387      $locale = get_locale();
 388  
 389      if ( 'ca' === $locale ) {
 390          // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..."
 391          $date = preg_replace( '# de ([ao])#i', " d'\\1", $date );
 392      }
 393  
 394      return $date;
 395  }
 396  
 397  /**
 398   * Convert float number to format based on the locale.
 399   *
 400   * @since 2.3.0
 401   *
 402   * @global WP_Locale $wp_locale WordPress date and time locale object.
 403   *
 404   * @param float $number   The number to convert based on locale.
 405   * @param int   $decimals Optional. Precision of the number of decimal places. Default 0.
 406   * @return string Converted number in string format.
 407   */
 408  function number_format_i18n( $number, $decimals = 0 ) {
 409      global $wp_locale;
 410  
 411      if ( isset( $wp_locale ) ) {
 412          $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
 413      } else {
 414          $formatted = number_format( $number, absint( $decimals ) );
 415      }
 416  
 417      /**
 418       * Filters the number formatted based on the locale.
 419       *
 420       * @since 2.8.0
 421       * @since 4.9.0 The `$number` and `$decimals` parameters were added.
 422       *
 423       * @param string $formatted Converted number in string format.
 424       * @param float  $number    The number to convert based on locale.
 425       * @param int    $decimals  Precision of the number of decimal places.
 426       */
 427      return apply_filters( 'number_format_i18n', $formatted, $number, $decimals );
 428  }
 429  
 430  /**
 431   * Convert number of bytes largest unit bytes will fit into.
 432   *
 433   * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts
 434   * number of bytes to human readable number by taking the number of that unit
 435   * that the bytes will go into it. Supports TB value.
 436   *
 437   * Please note that integers in PHP are limited to 32 bits, unless they are on
 438   * 64 bit architecture, then they have 64 bit size. If you need to place the
 439   * larger size then what PHP integer type will hold, then use a string. It will
 440   * be converted to a double, which should always have 64 bit length.
 441   *
 442   * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
 443   *
 444   * @since 2.3.0
 445   *
 446   * @param int|string $bytes    Number of bytes. Note max integer size for integers.
 447   * @param int        $decimals Optional. Precision of number of decimal places. Default 0.
 448   * @return string|false Number string on success, false on failure.
 449   */
 450  function size_format( $bytes, $decimals = 0 ) {
 451      $quant = array(
 452          /* translators: Unit symbol for terabyte. */
 453          _x( 'TB', 'unit symbol' ) => TB_IN_BYTES,
 454          /* translators: Unit symbol for gigabyte. */
 455          _x( 'GB', 'unit symbol' ) => GB_IN_BYTES,
 456          /* translators: Unit symbol for megabyte. */
 457          _x( 'MB', 'unit symbol' ) => MB_IN_BYTES,
 458          /* translators: Unit symbol for kilobyte. */
 459          _x( 'KB', 'unit symbol' ) => KB_IN_BYTES,
 460          /* translators: Unit symbol for byte. */
 461          _x( 'B', 'unit symbol' )  => 1,
 462      );
 463  
 464      if ( 0 === $bytes ) {
 465          /* translators: Unit symbol for byte. */
 466          return number_format_i18n( 0, $decimals ) . ' ' . _x( 'B', 'unit symbol' );
 467      }
 468  
 469      foreach ( $quant as $unit => $mag ) {
 470          if ( doubleval( $bytes ) >= $mag ) {
 471              return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
 472          }
 473      }
 474  
 475      return false;
 476  }
 477  
 478  /**
 479   * Convert a duration to human readable format.
 480   *
 481   * @since 5.1.0
 482   *
 483   * @param string $duration Duration will be in string format (HH:ii:ss) OR (ii:ss),
 484   *                         with a possible prepended negative sign (-).
 485   * @return string|false A human readable duration string, false on failure.
 486   */
 487  function human_readable_duration( $duration = '' ) {
 488      if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
 489          return false;
 490      }
 491  
 492      $duration = trim( $duration );
 493  
 494      // Remove prepended negative sign.
 495      if ( '-' === substr( $duration, 0, 1 ) ) {
 496          $duration = substr( $duration, 1 );
 497      }
 498  
 499      // Extract duration parts.
 500      $duration_parts = array_reverse( explode( ':', $duration ) );
 501      $duration_count = count( $duration_parts );
 502  
 503      $hour   = null;
 504      $minute = null;
 505      $second = null;
 506  
 507      if ( 3 === $duration_count ) {
 508          // Validate HH:ii:ss duration format.
 509          if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
 510              return false;
 511          }
 512          // Three parts: hours, minutes & seconds.
 513          list( $second, $minute, $hour ) = $duration_parts;
 514      } elseif ( 2 === $duration_count ) {
 515          // Validate ii:ss duration format.
 516          if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
 517              return false;
 518          }
 519          // Two parts: minutes & seconds.
 520          list( $second, $minute ) = $duration_parts;
 521      } else {
 522          return false;
 523      }
 524  
 525      $human_readable_duration = array();
 526  
 527      // Add the hour part to the string.
 528      if ( is_numeric( $hour ) ) {
 529          /* translators: %s: Time duration in hour or hours. */
 530          $human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
 531      }
 532  
 533      // Add the minute part to the string.
 534      if ( is_numeric( $minute ) ) {
 535          /* translators: %s: Time duration in minute or minutes. */
 536          $human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
 537      }
 538  
 539      // Add the second part to the string.
 540      if ( is_numeric( $second ) ) {
 541          /* translators: %s: Time duration in second or seconds. */
 542          $human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
 543      }
 544  
 545      return implode( ', ', $human_readable_duration );
 546  }
 547  
 548  /**
 549   * Get the week start and end from the datetime or date string from MySQL.
 550   *
 551   * @since 0.71
 552   *
 553   * @param string     $mysqlstring   Date or datetime field type from MySQL.
 554   * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
 555   * @return array Keys are 'start' and 'end'.
 556   */
 557  function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
 558      // MySQL string year.
 559      $my = substr( $mysqlstring, 0, 4 );
 560  
 561      // MySQL string month.
 562      $mm = substr( $mysqlstring, 8, 2 );
 563  
 564      // MySQL string day.
 565      $md = substr( $mysqlstring, 5, 2 );
 566  
 567      // The timestamp for MySQL string day.
 568      $day = mktime( 0, 0, 0, $md, $mm, $my );
 569  
 570      // The day of the week from the timestamp.
 571      $weekday = gmdate( 'w', $day );
 572  
 573      if ( ! is_numeric( $start_of_week ) ) {
 574          $start_of_week = get_option( 'start_of_week' );
 575      }
 576  
 577      if ( $weekday < $start_of_week ) {
 578          $weekday += 7;
 579      }
 580  
 581      // The most recent week start day on or before $day.
 582      $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
 583  
 584      // $start + 1 week - 1 second.
 585      $end = $start + WEEK_IN_SECONDS - 1;
 586      return compact( 'start', 'end' );
 587  }
 588  
 589  /**
 590   * Serialize data, if needed.
 591   *
 592   * @since 2.0.5
 593   *
 594   * @param string|array|object $data Data that might be serialized.
 595   * @return mixed A scalar data.
 596   */
 597  function maybe_serialize( $data ) {
 598      if ( is_array( $data ) || is_object( $data ) ) {
 599          return serialize( $data );
 600      }
 601  
 602      /*
 603       * Double serialization is required for backward compatibility.
 604       * See https://core.trac.wordpress.org/ticket/12930
 605       * Also the world will end. See WP 3.6.1.
 606       */
 607      if ( is_serialized( $data, false ) ) {
 608          return serialize( $data );
 609      }
 610  
 611      return $data;
 612  }
 613  
 614  /**
 615   * Unserialize data only if it was serialized.
 616   *
 617   * @since 2.0.0
 618   *
 619   * @param string $data Data that might be unserialized.
 620   * @return mixed Unserialized data can be any type.
 621   */
 622  function maybe_unserialize( $data ) {
 623      if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
 624          return @unserialize( trim( $data ) );
 625      }
 626  
 627      return $data;
 628  }
 629  
 630  /**
 631   * Check value to find if it was serialized.
 632   *
 633   * If $data is not an string, then returned value will always be false.
 634   * Serialized data is always a string.
 635   *
 636   * @since 2.0.5
 637   *
 638   * @param string $data   Value to check to see if was serialized.
 639   * @param bool   $strict Optional. Whether to be strict about the end of the string. Default true.
 640   * @return bool False if not serialized and true if it was.
 641   */
 642  function is_serialized( $data, $strict = true ) {
 643      // If it isn't a string, it isn't serialized.
 644      if ( ! is_string( $data ) ) {
 645          return false;
 646      }
 647      $data = trim( $data );
 648      if ( 'N;' === $data ) {
 649          return true;
 650      }
 651      if ( strlen( $data ) < 4 ) {
 652          return false;
 653      }
 654      if ( ':' !== $data[1] ) {
 655          return false;
 656      }
 657      if ( $strict ) {
 658          $lastc = substr( $data, -1 );
 659          if ( ';' !== $lastc && '}' !== $lastc ) {
 660              return false;
 661          }
 662      } else {
 663          $semicolon = strpos( $data, ';' );
 664          $brace     = strpos( $data, '}' );
 665          // Either ; or } must exist.
 666          if ( false === $semicolon && false === $brace ) {
 667              return false;
 668          }
 669          // But neither must be in the first X characters.
 670          if ( false !== $semicolon && $semicolon < 3 ) {
 671              return false;
 672          }
 673          if ( false !== $brace && $brace < 4 ) {
 674              return false;
 675          }
 676      }
 677      $token = $data[0];
 678      switch ( $token ) {
 679          case 's':
 680              if ( $strict ) {
 681                  if ( '"' !== substr( $data, -2, 1 ) ) {
 682                      return false;
 683                  }
 684              } elseif ( false === strpos( $data, '"' ) ) {
 685                  return false;
 686              }
 687              // Or else fall through.
 688          case 'a':
 689          case 'O':
 690              return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
 691          case 'b':
 692          case 'i':
 693          case 'd':
 694              $end = $strict ? '$' : '';
 695              return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
 696      }
 697      return false;
 698  }
 699  
 700  /**
 701   * Check whether serialized data is of string type.
 702   *
 703   * @since 2.0.5
 704   *
 705   * @param string $data Serialized data.
 706   * @return bool False if not a serialized string, true if it is.
 707   */
 708  function is_serialized_string( $data ) {
 709      // if it isn't a string, it isn't a serialized string.
 710      if ( ! is_string( $data ) ) {
 711          return false;
 712      }
 713      $data = trim( $data );
 714      if ( strlen( $data ) < 4 ) {
 715          return false;
 716      } elseif ( ':' !== $data[1] ) {
 717          return false;
 718      } elseif ( ';' !== substr( $data, -1 ) ) {
 719          return false;
 720      } elseif ( 's' !== $data[0] ) {
 721          return false;
 722      } elseif ( '"' !== substr( $data, -2, 1 ) ) {
 723          return false;
 724      } else {
 725          return true;
 726      }
 727  }
 728  
 729  /**
 730   * Retrieve post title from XMLRPC XML.
 731   *
 732   * If the title element is not part of the XML, then the default post title from
 733   * the $post_default_title will be used instead.
 734   *
 735   * @since 0.71
 736   *
 737   * @global string $post_default_title Default XML-RPC post title.
 738   *
 739   * @param string $content XMLRPC XML Request content
 740   * @return string Post title
 741   */
 742  function xmlrpc_getposttitle( $content ) {
 743      global $post_default_title;
 744      if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
 745          $post_title = $matchtitle[1];
 746      } else {
 747          $post_title = $post_default_title;
 748      }
 749      return $post_title;
 750  }
 751  
 752  /**
 753   * Retrieve the post category or categories from XMLRPC XML.
 754   *
 755   * If the category element is not found, then the default post category will be
 756   * used. The return type then would be what $post_default_category. If the
 757   * category is found, then it will always be an array.
 758   *
 759   * @since 0.71
 760   *
 761   * @global string $post_default_category Default XML-RPC post category.
 762   *
 763   * @param string $content XMLRPC XML Request content
 764   * @return string|array List of categories or category name.
 765   */
 766  function xmlrpc_getpostcategory( $content ) {
 767      global $post_default_category;
 768      if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
 769          $post_category = trim( $matchcat[1], ',' );
 770          $post_category = explode( ',', $post_category );
 771      } else {
 772          $post_category = $post_default_category;
 773      }
 774      return $post_category;
 775  }
 776  
 777  /**
 778   * XMLRPC XML content without title and category elements.
 779   *
 780   * @since 0.71
 781   *
 782   * @param string $content XML-RPC XML Request content.
 783   * @return string XMLRPC XML Request content without title and category elements.
 784   */
 785  function xmlrpc_removepostdata( $content ) {
 786      $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
 787      $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
 788      $content = trim( $content );
 789      return $content;
 790  }
 791  
 792  /**
 793   * Use RegEx to extract URLs from arbitrary content.
 794   *
 795   * @since 3.7.0
 796   *
 797   * @param string $content Content to extract URLs from.
 798   * @return string[] Array of URLs found in passed string.
 799   */
 800  function wp_extract_urls( $content ) {
 801      preg_match_all(
 802          "#([\"']?)("
 803              . '(?:([\w-]+:)?//?)'
 804              . '[^\s()<>]+'
 805              . '[.]'
 806              . '(?:'
 807                  . '\([\w\d]+\)|'
 808                  . '(?:'
 809                      . "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
 810                      . '(?:[:]\d+)?/?'
 811                  . ')+'
 812              . ')'
 813          . ")\\1#",
 814          $content,
 815          $post_links
 816      );
 817  
 818      $post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
 819  
 820      return array_values( $post_links );
 821  }
 822  
 823  /**
 824   * Check content for video and audio links to add as enclosures.
 825   *
 826   * Will not add enclosures that have already been added and will
 827   * remove enclosures that are no longer in the post. This is called as
 828   * pingbacks and trackbacks.
 829   *
 830   * @since 1.5.0
 831   * @since 5.3.0 The `$content` parameter was made optional, and the `$post` parameter was
 832   *              updated to accept a post ID or a WP_Post object.
 833   * @since 5.6.0 The `$content` parameter is no longer optional, but passing `null` to skip it
 834   *              is still supported.
 835   *
 836   * @global wpdb $wpdb WordPress database abstraction object.
 837   *
 838   * @param string|null $content Post content. If `null`, the `post_content` field from `$post` is used.
 839   * @param int|WP_Post $post    Post ID or post object.
 840   * @return null|bool Returns false if post is not found.
 841   */
 842  function do_enclose( $content, $post ) {
 843      global $wpdb;
 844  
 845      // @todo Tidy this code and make the debug code optional.
 846      include_once  ABSPATH . WPINC . '/class-IXR.php';
 847  
 848      $post = get_post( $post );
 849      if ( ! $post ) {
 850          return false;
 851      }
 852  
 853      if ( null === $content ) {
 854          $content = $post->post_content;
 855      }
 856  
 857      $post_links = array();
 858  
 859      $pung = get_enclosed( $post->ID );
 860  
 861      $post_links_temp = wp_extract_urls( $content );
 862  
 863      foreach ( $pung as $link_test ) {
 864          // Link is no longer in post.
 865          if ( ! in_array( $link_test, $post_links_temp, true ) ) {
 866              $mids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post->ID, $wpdb->esc_like( $link_test ) . '%' ) );
 867              foreach ( $mids as $mid ) {
 868                  delete_metadata_by_mid( 'post', $mid );
 869              }
 870          }
 871      }
 872  
 873      foreach ( (array) $post_links_temp as $link_test ) {
 874          // If we haven't pung it already.
 875          if ( ! in_array( $link_test, $pung, true ) ) {
 876              $test = parse_url( $link_test );
 877              if ( false === $test ) {
 878                  continue;
 879              }
 880              if ( isset( $test['query'] ) ) {
 881                  $post_links[] = $link_test;
 882              } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
 883                  $post_links[] = $link_test;
 884              }
 885          }
 886      }
 887  
 888      /**
 889       * Filters the list of enclosure links before querying the database.
 890       *
 891       * Allows for the addition and/or removal of potential enclosures to save
 892       * to postmeta before checking the database for existing enclosures.
 893       *
 894       * @since 4.4.0
 895       *
 896       * @param string[] $post_links An array of enclosure links.
 897       * @param int      $post_ID    Post ID.
 898       */
 899      $post_links = apply_filters( 'enclosure_links', $post_links, $post->ID );
 900  
 901      foreach ( (array) $post_links as $url ) {
 902          if ( '' !== $url && ! $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post->ID, $wpdb->esc_like( $url ) . '%' ) ) ) {
 903  
 904              $headers = wp_get_http_headers( $url );
 905              if ( $headers ) {
 906                  $len           = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
 907                  $type          = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
 908                  $allowed_types = array( 'video', 'audio' );
 909  
 910                  // Check to see if we can figure out the mime type from the extension.
 911                  $url_parts = parse_url( $url );
 912                  if ( false !== $url_parts && ! empty( $url_parts['path'] ) ) {
 913                      $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
 914                      if ( ! empty( $extension ) ) {
 915                          foreach ( wp_get_mime_types() as $exts => $mime ) {
 916                              if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
 917                                  $type = $mime;
 918                                  break;
 919                              }
 920                          }
 921                      }
 922                  }
 923  
 924                  if ( in_array( substr( $type, 0, strpos( $type, '/' ) ), $allowed_types, true ) ) {
 925                      add_post_meta( $post->ID, 'enclosure', "$url\n$len\n$mime\n" );
 926                  }
 927              }
 928          }
 929      }
 930  }
 931  
 932  /**
 933   * Retrieve HTTP Headers from URL.
 934   *
 935   * @since 1.5.1
 936   *
 937   * @param string $url        URL to retrieve HTTP headers from.
 938   * @param bool   $deprecated Not Used.
 939   * @return bool|string False on failure, headers on success.
 940   */
 941  function wp_get_http_headers( $url, $deprecated = false ) {
 942      if ( ! empty( $deprecated ) ) {
 943          _deprecated_argument( __FUNCTION__, '2.7.0' );
 944      }
 945  
 946      $response = wp_safe_remote_head( $url );
 947  
 948      if ( is_wp_error( $response ) ) {
 949          return false;
 950      }
 951  
 952      return wp_remote_retrieve_headers( $response );
 953  }
 954  
 955  /**
 956   * Determines whether the publish date of the current post in the loop is different
 957   * from the publish date of the previous post in the loop.
 958   *
 959   * For more information on this and similar theme functions, check out
 960   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 961   * Conditional Tags} article in the Theme Developer Handbook.
 962   *
 963   * @since 0.71
 964   *
 965   * @global string $currentday  The day of the current post in the loop.
 966   * @global string $previousday The day of the previous post in the loop.
 967   *
 968   * @return int 1 when new day, 0 if not a new day.
 969   */
 970  function is_new_day() {
 971      global $currentday, $previousday;
 972  
 973      if ( $currentday !== $previousday ) {
 974          return 1;
 975      } else {
 976          return 0;
 977      }
 978  }
 979  
 980  /**
 981   * Build URL query based on an associative and, or indexed array.
 982   *
 983   * This is a convenient function for easily building url queries. It sets the
 984   * separator to '&' and uses _http_build_query() function.
 985   *
 986   * @since 2.3.0
 987   *
 988   * @see _http_build_query() Used to build the query
 989   * @link https://www.php.net/manual/en/function.http-build-query.php for more on what
 990   *       http_build_query() does.
 991   *
 992   * @param array $data URL-encode key/value pairs.
 993   * @return string URL-encoded string.
 994   */
 995  function build_query( $data ) {
 996      return _http_build_query( $data, null, '&', '', false );
 997  }
 998  
 999  /**
1000   * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
1001   *
1002   * @since 3.2.0
1003   * @access private
1004   *
1005   * @see https://www.php.net/manual/en/function.http-build-query.php
1006   *
1007   * @param array|object $data      An array or object of data. Converted to array.
1008   * @param string       $prefix    Optional. Numeric index. If set, start parameter numbering with it.
1009   *                                Default null.
1010   * @param string       $sep       Optional. Argument separator; defaults to 'arg_separator.output'.
1011   *                                Default null.
1012   * @param string       $key       Optional. Used to prefix key name. Default empty.
1013   * @param bool         $urlencode Optional. Whether to use urlencode() in the result. Default true.
1014   * @return string The query string.
1015   */
1016  function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
1017      $ret = array();
1018  
1019      foreach ( (array) $data as $k => $v ) {
1020          if ( $urlencode ) {
1021              $k = urlencode( $k );
1022          }
1023          if ( is_int( $k ) && null != $prefix ) {
1024              $k = $prefix . $k;
1025          }
1026          if ( ! empty( $key ) ) {
1027              $k = $key . '%5B' . $k . '%5D';
1028          }
1029          if ( null === $v ) {
1030              continue;
1031          } elseif ( false === $v ) {
1032              $v = '0';
1033          }
1034  
1035          if ( is_array( $v ) || is_object( $v ) ) {
1036              array_push( $ret, _http_build_query( $v, '', $sep, $k, $urlencode ) );
1037          } elseif ( $urlencode ) {
1038              array_push( $ret, $k . '=' . urlencode( $v ) );
1039          } else {
1040              array_push( $ret, $k . '=' . $v );
1041          }
1042      }
1043  
1044      if ( null === $sep ) {
1045          $sep = ini_get( 'arg_separator.output' );
1046      }
1047  
1048      return implode( $sep, $ret );
1049  }
1050  
1051  /**
1052   * Retrieves a modified URL query string.
1053   *
1054   * You can rebuild the URL and append query variables to the URL query by using this function.
1055   * There are two ways to use this function; either a single key and value, or an associative array.
1056   *
1057   * Using a single key and value:
1058   *
1059   *     add_query_arg( 'key', 'value', 'http://example.com' );
1060   *
1061   * Using an associative array:
1062   *
1063   *     add_query_arg( array(
1064   *         'key1' => 'value1',
1065   *         'key2' => 'value2',
1066   *     ), 'http://example.com' );
1067   *
1068   * Omitting the URL from either use results in the current URL being used
1069   * (the value of `$_SERVER['REQUEST_URI']`).
1070   *
1071   * Values are expected to be encoded appropriately with urlencode() or rawurlencode().
1072   *
1073   * Setting any query variable's value to boolean false removes the key (see remove_query_arg()).
1074   *
1075   * Important: The return value of add_query_arg() is not escaped by default. Output should be
1076   * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting
1077   * (XSS) attacks.
1078   *
1079   * @since 1.5.0
1080   * @since 5.3.0 Formalized the existing and already documented parameters
1081   *              by adding `...$args` to the function signature.
1082   *
1083   * @param string|array $key   Either a query variable key, or an associative array of query variables.
1084   * @param string       $value Optional. Either a query variable value, or a URL to act upon.
1085   * @param string       $url   Optional. A URL to act upon.
1086   * @return string New URL query string (unescaped).
1087   */
1088  function add_query_arg( ...$args ) {
1089      if ( is_array( $args[0] ) ) {
1090          if ( count( $args ) < 2 || false === $args[1] ) {
1091              $uri = $_SERVER['REQUEST_URI'];
1092          } else {
1093              $uri = $args[1];
1094          }
1095      } else {
1096          if ( count( $args ) < 3 || false === $args[2] ) {
1097              $uri = $_SERVER['REQUEST_URI'];
1098          } else {
1099              $uri = $args[2];
1100          }
1101      }
1102  
1103      $frag = strstr( $uri, '#' );
1104      if ( $frag ) {
1105          $uri = substr( $uri, 0, -strlen( $frag ) );
1106      } else {
1107          $frag = '';
1108      }
1109  
1110      if ( 0 === stripos( $uri, 'http://' ) ) {
1111          $protocol = 'http://';
1112          $uri      = substr( $uri, 7 );
1113      } elseif ( 0 === stripos( $uri, 'https://' ) ) {
1114          $protocol = 'https://';
1115          $uri      = substr( $uri, 8 );
1116      } else {
1117          $protocol = '';
1118      }
1119  
1120      if ( strpos( $uri, '?' ) !== false ) {
1121          list( $base, $query ) = explode( '?', $uri, 2 );
1122          $base                .= '?';
1123      } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
1124          $base  = $uri . '?';
1125          $query = '';
1126      } else {
1127          $base  = '';
1128          $query = $uri;
1129      }
1130  
1131      wp_parse_str( $query, $qs );
1132      $qs = urlencode_deep( $qs ); // This re-URL-encodes things that were already in the query string.
1133      if ( is_array( $args[0] ) ) {
1134          foreach ( $args[0] as $k => $v ) {
1135              $qs[ $k ] = $v;
1136          }
1137      } else {
1138          $qs[ $args[0] ] = $args[1];
1139      }
1140  
1141      foreach ( $qs as $k => $v ) {
1142          if ( false === $v ) {
1143              unset( $qs[ $k ] );
1144          }
1145      }
1146  
1147      $ret = build_query( $qs );
1148      $ret = trim( $ret, '?' );
1149      $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1150      $ret = $protocol . $base . $ret . $frag;
1151      $ret = rtrim( $ret, '?' );
1152      return $ret;
1153  }
1154  
1155  /**
1156   * Removes an item or items from a query string.
1157   *
1158   * @since 1.5.0
1159   *
1160   * @param string|array $key   Query key or keys to remove.
1161   * @param bool|string  $query Optional. When false uses the current URL. Default false.
1162   * @return string New URL query string.
1163   */
1164  function remove_query_arg( $key, $query = false ) {
1165      if ( is_array( $key ) ) { // Removing multiple keys.
1166          foreach ( $key as $k ) {
1167              $query = add_query_arg( $k, false, $query );
1168          }
1169          return $query;
1170      }
1171      return add_query_arg( $key, false, $query );
1172  }
1173  
1174  /**
1175   * Returns an array of single-use query variable names that can be removed from a URL.
1176   *
1177   * @since 4.4.0
1178   *
1179   * @return string[] An array of parameters to remove from the URL.
1180   */
1181  function wp_removable_query_args() {
1182      $removable_query_args = array(
1183          'activate',
1184          'activated',
1185          'admin_email_remind_later',
1186          'approved',
1187          'deactivate',
1188          'delete_count',
1189          'deleted',
1190          'disabled',
1191          'doing_wp_cron',
1192          'enabled',
1193          'error',
1194          'hotkeys_highlight_first',
1195          'hotkeys_highlight_last',
1196          'locked',
1197          'message',
1198          'same',
1199          'saved',
1200          'settings-updated',
1201          'skipped',
1202          'spammed',
1203          'trashed',
1204          'unspammed',
1205          'untrashed',
1206          'update',
1207          'updated',
1208          'wp-post-new-reload',
1209      );
1210  
1211      /**
1212       * Filters the list of query variables to remove.
1213       *
1214       * @since 4.2.0
1215       *
1216       * @param string[] $removable_query_args An array of query variables to remove from a URL.
1217       */
1218      return apply_filters( 'removable_query_args', $removable_query_args );
1219  }
1220  
1221  /**
1222   * Walks the array while sanitizing the contents.
1223   *
1224   * @since 0.71
1225   * @since 5.5.0 Non-string values are left untouched.
1226   *
1227   * @param array $array Array to walk while sanitizing contents.
1228   * @return array Sanitized $array.
1229   */
1230  function add_magic_quotes( $array ) {
1231      foreach ( (array) $array as $k => $v ) {
1232          if ( is_array( $v ) ) {
1233              $array[ $k ] = add_magic_quotes( $v );
1234          } elseif ( is_string( $v ) ) {
1235              $array[ $k ] = addslashes( $v );
1236          } else {
1237              continue;
1238          }
1239      }
1240  
1241      return $array;
1242  }
1243  
1244  /**
1245   * HTTP request for URI to retrieve content.
1246   *
1247   * @since 1.5.1
1248   *
1249   * @see wp_safe_remote_get()
1250   *
1251   * @param string $uri URI/URL of web page to retrieve.
1252   * @return string|false HTTP content. False on failure.
1253   */
1254  function wp_remote_fopen( $uri ) {
1255      $parsed_url = parse_url( $uri );
1256  
1257      if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
1258          return false;
1259      }
1260  
1261      $options            = array();
1262      $options['timeout'] = 10;
1263  
1264      $response = wp_safe_remote_get( $uri, $options );
1265  
1266      if ( is_wp_error( $response ) ) {
1267          return false;
1268      }
1269  
1270      return wp_remote_retrieve_body( $response );
1271  }
1272  
1273  /**
1274   * Set up the WordPress query.
1275   *
1276   * @since 2.0.0
1277   *
1278   * @global WP       $wp           Current WordPress environment instance.
1279   * @global WP_Query $wp_query     WordPress Query object.
1280   * @global WP_Query $wp_the_query Copy of the WordPress Query object.
1281   *
1282   * @param string|array $query_vars Default WP_Query arguments.
1283   */
1284  function wp( $query_vars = '' ) {
1285      global $wp, $wp_query, $wp_the_query;
1286  
1287      $wp->main( $query_vars );
1288  
1289      if ( ! isset( $wp_the_query ) ) {
1290          $wp_the_query = $wp_query;
1291      }
1292  }
1293  
1294  /**
1295   * Retrieve the description for the HTTP status.
1296   *
1297   * @since 2.3.0
1298   * @since 3.9.0 Added status codes 418, 428, 429, 431, and 511.
1299   * @since 4.5.0 Added status codes 308, 421, and 451.
1300   * @since 5.1.0 Added status code 103.
1301   *
1302   * @global array $wp_header_to_desc
1303   *
1304   * @param int $code HTTP status code.
1305   * @return string Status description if found, an empty string otherwise.
1306   */
1307  function get_status_header_desc( $code ) {
1308      global $wp_header_to_desc;
1309  
1310      $code = absint( $code );
1311  
1312      if ( ! isset( $wp_header_to_desc ) ) {
1313          $wp_header_to_desc = array(
1314              100 => 'Continue',
1315              101 => 'Switching Protocols',
1316              102 => 'Processing',
1317              103 => 'Early Hints',
1318  
1319              200 => 'OK',
1320              201 => 'Created',
1321              202 => 'Accepted',
1322              203 => 'Non-Authoritative Information',
1323              204 => 'No Content',
1324              205 => 'Reset Content',
1325              206 => 'Partial Content',
1326              207 => 'Multi-Status',
1327              226 => 'IM Used',
1328  
1329              300 => 'Multiple Choices',
1330              301 => 'Moved Permanently',
1331              302 => 'Found',
1332              303 => 'See Other',
1333              304 => 'Not Modified',
1334              305 => 'Use Proxy',
1335              306 => 'Reserved',
1336              307 => 'Temporary Redirect',
1337              308 => 'Permanent Redirect',
1338  
1339              400 => 'Bad Request',
1340              401 => 'Unauthorized',
1341              402 => 'Payment Required',
1342              403 => 'Forbidden',
1343              404 => 'Not Found',
1344              405 => 'Method Not Allowed',
1345              406 => 'Not Acceptable',
1346              407 => 'Proxy Authentication Required',
1347              408 => 'Request Timeout',
1348              409 => 'Conflict',
1349              410 => 'Gone',
1350              411 => 'Length Required',
1351              412 => 'Precondition Failed',
1352              413 => 'Request Entity Too Large',
1353              414 => 'Request-URI Too Long',
1354              415 => 'Unsupported Media Type',
1355              416 => 'Requested Range Not Satisfiable',
1356              417 => 'Expectation Failed',
1357              418 => 'I\'m a teapot',
1358              421 => 'Misdirected Request',
1359              422 => 'Unprocessable Entity',
1360              423 => 'Locked',
1361              424 => 'Failed Dependency',
1362              426 => 'Upgrade Required',
1363              428 => 'Precondition Required',
1364              429 => 'Too Many Requests',
1365              431 => 'Request Header Fields Too Large',
1366              451 => 'Unavailable For Legal Reasons',
1367  
1368              500 => 'Internal Server Error',
1369              501 => 'Not Implemented',
1370              502 => 'Bad Gateway',
1371              503 => 'Service Unavailable',
1372              504 => 'Gateway Timeout',
1373              505 => 'HTTP Version Not Supported',
1374              506 => 'Variant Also Negotiates',
1375              507 => 'Insufficient Storage',
1376              510 => 'Not Extended',
1377              511 => 'Network Authentication Required',
1378          );
1379      }
1380  
1381      if ( isset( $wp_header_to_desc[ $code ] ) ) {
1382          return $wp_header_to_desc[ $code ];
1383      } else {
1384          return '';
1385      }
1386  }
1387  
1388  /**
1389   * Set HTTP status header.
1390   *
1391   * @since 2.0.0
1392   * @since 4.4.0 Added the `$description` parameter.
1393   *
1394   * @see get_status_header_desc()
1395   *
1396   * @param int    $code        HTTP status code.
1397   * @param string $description Optional. A custom description for the HTTP status.
1398   */
1399  function status_header( $code, $description = '' ) {
1400      if ( ! $description ) {
1401          $description = get_status_header_desc( $code );
1402      }
1403  
1404      if ( empty( $description ) ) {
1405          return;
1406      }
1407  
1408      $protocol      = wp_get_server_protocol();
1409      $status_header = "$protocol $code $description";
1410      if ( function_exists( 'apply_filters' ) ) {
1411  
1412          /**
1413           * Filters an HTTP status header.
1414           *
1415           * @since 2.2.0
1416           *
1417           * @param string $status_header HTTP status header.
1418           * @param int    $code          HTTP status code.
1419           * @param string $description   Description for the status code.
1420           * @param string $protocol      Server protocol.
1421           */
1422          $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
1423      }
1424  
1425      if ( ! headers_sent() ) {
1426          header( $status_header, true, $code );
1427      }
1428  }
1429  
1430  /**
1431   * Get the header information to prevent caching.
1432   *
1433   * The several different headers cover the different ways cache prevention
1434   * is handled by different browsers
1435   *
1436   * @since 2.8.0
1437   *
1438   * @return array The associative array of header names and field values.
1439   */
1440  function wp_get_nocache_headers() {
1441      $headers = array(
1442          'Expires'       => 'Wed, 11 Jan 1984 05:00:00 GMT',
1443          'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
1444      );
1445  
1446      if ( function_exists( 'apply_filters' ) ) {
1447          /**
1448           * Filters the cache-controlling headers.
1449           *
1450           * @since 2.8.0
1451           *
1452           * @see wp_get_nocache_headers()
1453           *
1454           * @param array $headers {
1455           *     Header names and field values.
1456           *
1457           *     @type string $Expires       Expires header.
1458           *     @type string $Cache-Control Cache-Control header.
1459           * }
1460           */
1461          $headers = (array) apply_filters( 'nocache_headers', $headers );
1462      }
1463      $headers['Last-Modified'] = false;
1464      return $headers;
1465  }
1466  
1467  /**
1468   * Set the headers to prevent caching for the different browsers.
1469   *
1470   * Different browsers support different nocache headers, so several
1471   * headers must be sent so that all of them get the point that no
1472   * caching should occur.
1473   *
1474   * @since 2.0.0
1475   *
1476   * @see wp_get_nocache_headers()
1477   */
1478  function nocache_headers() {
1479      if ( headers_sent() ) {
1480          return;
1481      }
1482  
1483      $headers = wp_get_nocache_headers();
1484  
1485      unset( $headers['Last-Modified'] );
1486  
1487      header_remove( 'Last-Modified' );
1488  
1489      foreach ( $headers as $name => $field_value ) {
1490          header( "{$name}: {$field_value}" );
1491      }
1492  }
1493  
1494  /**
1495   * Set the headers for caching for 10 days with JavaScript content type.
1496   *
1497   * @since 2.1.0
1498   */
1499  function cache_javascript_headers() {
1500      $expiresOffset = 10 * DAY_IN_SECONDS;
1501  
1502      header( 'Content-Type: text/javascript; charset=' . get_bloginfo( 'charset' ) );
1503      header( 'Vary: Accept-Encoding' ); // Handle proxies.
1504      header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expiresOffset ) . ' GMT' );
1505  }
1506  
1507  /**
1508   * Retrieve the number of database queries during the WordPress execution.
1509   *
1510   * @since 2.0.0
1511   *
1512   * @global wpdb $wpdb WordPress database abstraction object.
1513   *
1514   * @return int Number of database queries.
1515   */
1516  function get_num_queries() {
1517      global $wpdb;
1518      return $wpdb->num_queries;
1519  }
1520  
1521  /**
1522   * Whether input is yes or no.
1523   *
1524   * Must be 'y' to be true.
1525   *
1526   * @since 1.0.0
1527   *
1528   * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
1529   * @return bool True if yes, false on anything else.
1530   */
1531  function bool_from_yn( $yn ) {
1532      return ( 'y' === strtolower( $yn ) );
1533  }
1534  
1535  /**
1536   * Load the feed template from the use of an action hook.
1537   *
1538   * If the feed action does not have a hook, then the function will die with a
1539   * message telling the visitor that the feed is not valid.
1540   *
1541   * It is better to only have one hook for each feed.
1542   *
1543   * @since 2.1.0
1544   *
1545   * @global WP_Query $wp_query WordPress Query object.
1546   */
1547  function do_feed() {
1548      global $wp_query;
1549  
1550      $feed = get_query_var( 'feed' );
1551  
1552      // Remove the pad, if present.
1553      $feed = preg_replace( '/^_+/', '', $feed );
1554  
1555      if ( '' === $feed || 'feed' === $feed ) {
1556          $feed = get_default_feed();
1557      }
1558  
1559      if ( ! has_action( "do_feed_{$feed}" ) ) {
1560          wp_die( __( 'Error: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
1561      }
1562  
1563      /**
1564       * Fires once the given feed is loaded.
1565       *
1566       * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
1567       * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
1568       *
1569       * @since 2.1.0
1570       * @since 4.4.0 The `$feed` parameter was added.
1571       *
1572       * @param bool   $is_comment_feed Whether the feed is a comment feed.
1573       * @param string $feed            The feed name.
1574       */
1575      do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
1576  }
1577  
1578  /**
1579   * Load the RDF RSS 0.91 Feed template.
1580   *
1581   * @since 2.1.0
1582   *
1583   * @see load_template()
1584   */
1585  function do_feed_rdf() {
1586      load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1587  }
1588  
1589  /**
1590   * Load the RSS 1.0 Feed Template.
1591   *
1592   * @since 2.1.0
1593   *
1594   * @see load_template()
1595   */
1596  function do_feed_rss() {
1597      load_template( ABSPATH . WPINC . '/feed-rss.php' );
1598  }
1599  
1600  /**
1601   * Load either the RSS2 comment feed or the RSS2 posts feed.
1602   *
1603   * @since 2.1.0
1604   *
1605   * @see load_template()
1606   *
1607   * @param bool $for_comments True for the comment feed, false for normal feed.
1608   */
1609  function do_feed_rss2( $for_comments ) {
1610      if ( $for_comments ) {
1611          load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1612      } else {
1613          load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1614      }
1615  }
1616  
1617  /**
1618   * Load either Atom comment feed or Atom posts feed.
1619   *
1620   * @since 2.1.0
1621   *
1622   * @see load_template()
1623   *
1624   * @param bool $for_comments True for the comment feed, false for normal feed.
1625   */
1626  function do_feed_atom( $for_comments ) {
1627      if ( $for_comments ) {
1628          load_template( ABSPATH . WPINC . '/feed-atom-comments.php' );
1629      } else {
1630          load_template( ABSPATH . WPINC . '/feed-atom.php' );
1631      }
1632  }
1633  
1634  /**
1635   * Displays the default robots.txt file content.
1636   *
1637   * @since 2.1.0
1638   * @since 5.3.0 Remove the "Disallow: /" output if search engine visiblity is
1639   *              discouraged in favor of robots meta HTML tag in wp_no_robots().
1640   */
1641  function do_robots() {
1642      header( 'Content-Type: text/plain; charset=utf-8' );
1643  
1644      /**
1645       * Fires when displaying the robots.txt file.
1646       *
1647       * @since 2.1.0
1648       */
1649      do_action( 'do_robotstxt' );
1650  
1651      $output = "User-agent: *\n";
1652      $public = get_option( 'blog_public' );
1653  
1654      $site_url = parse_url( site_url() );
1655      $path     = ( ! empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1656      $output  .= "Disallow: $path/wp-admin/\n";
1657      $output  .= "Allow: $path/wp-admin/admin-ajax.php\n";
1658  
1659      /**
1660       * Filters the robots.txt output.
1661       *
1662       * @since 3.0.0
1663       *
1664       * @param string $output The robots.txt output.
1665       * @param bool   $public Whether the site is considered "public".
1666       */
1667      echo apply_filters( 'robots_txt', $output, $public );
1668  }
1669  
1670  /**
1671   * Display the favicon.ico file content.
1672   *
1673   * @since 5.4.0
1674   */
1675  function do_favicon() {
1676      /**
1677       * Fires when serving the favicon.ico file.
1678       *
1679       * @since 5.4.0
1680       */
1681      do_action( 'do_faviconico' );
1682  
1683      wp_redirect( get_site_icon_url( 32, includes_url( 'images/w-logo-blue-white-bg.png' ) ) );
1684      exit;
1685  }
1686  
1687  /**
1688   * Determines whether WordPress is already installed.
1689   *
1690   * The cache will be checked first. If you have a cache plugin, which saves
1691   * the cache values, then this will work. If you use the default WordPress
1692   * cache, and the database goes away, then you might have problems.
1693   *
1694   * Checks for the 'siteurl' option for whether WordPress is installed.
1695   *
1696   * For more information on this and similar theme functions, check out
1697   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1698   * Conditional Tags} article in the Theme Developer Handbook.
1699   *
1700   * @since 2.1.0
1701   *
1702   * @global wpdb $wpdb WordPress database abstraction object.
1703   *
1704   * @return bool Whether the site is already installed.
1705   */
1706  function is_blog_installed() {
1707      global $wpdb;
1708  
1709      /*
1710       * Check cache first. If options table goes away and we have true
1711       * cached, oh well.
1712       */
1713      if ( wp_cache_get( 'is_blog_installed' ) ) {
1714          return true;
1715      }
1716  
1717      $suppress = $wpdb->suppress_errors();
1718      if ( ! wp_installing() ) {
1719          $alloptions = wp_load_alloptions();
1720      }
1721      // If siteurl is not set to autoload, check it specifically.
1722      if ( ! isset( $alloptions['siteurl'] ) ) {
1723          $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1724      } else {
1725          $installed = $alloptions['siteurl'];
1726      }
1727      $wpdb->suppress_errors( $suppress );
1728  
1729      $installed = ! empty( $installed );
1730      wp_cache_set( 'is_blog_installed', $installed );
1731  
1732      if ( $installed ) {
1733          return true;
1734      }
1735  
1736      // If visiting repair.php, return true and let it take over.
1737      if ( defined( 'WP_REPAIRING' ) ) {
1738          return true;
1739      }
1740  
1741      $suppress = $wpdb->suppress_errors();
1742  
1743      /*
1744       * Loop over the WP tables. If none exist, then scratch installation is allowed.
1745       * If one or more exist, suggest table repair since we got here because the
1746       * options table could not be accessed.
1747       */
1748      $wp_tables = $wpdb->tables();
1749      foreach ( $wp_tables as $table ) {
1750          // The existence of custom user tables shouldn't suggest an insane state or prevent a clean installation.
1751          if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table ) {
1752              continue;
1753          }
1754          if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table ) {
1755              continue;
1756          }
1757  
1758          if ( ! $wpdb->get_results( "DESCRIBE $table;" ) ) {
1759              continue;
1760          }
1761  
1762          // One or more tables exist. We are insane.
1763  
1764          wp_load_translations_early();
1765  
1766          // Die with a DB error.
1767          $wpdb->error = sprintf(
1768              /* translators: %s: Database repair URL. */
1769              __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
1770              'maint/repair.php?referrer=is_blog_installed'
1771          );
1772  
1773          dead_db();
1774      }
1775  
1776      $wpdb->suppress_errors( $suppress );
1777  
1778      wp_cache_set( 'is_blog_installed', false );
1779  
1780      return false;
1781  }
1782  
1783  /**
1784   * Retrieve URL with nonce added to URL query.
1785   *
1786   * @since 2.0.4
1787   *
1788   * @param string     $actionurl URL to add nonce action.
1789   * @param int|string $action    Optional. Nonce action name. Default -1.
1790   * @param string     $name      Optional. Nonce name. Default '_wpnonce'.
1791   * @return string Escaped URL with nonce action added.
1792   */
1793  function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
1794      $actionurl = str_replace( '&amp;', '&', $actionurl );
1795      return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
1796  }
1797  
1798  /**
1799   * Retrieve or display nonce hidden field for forms.
1800   *
1801   * The nonce field is used to validate that the contents of the form came from
1802   * the location on the current site and not somewhere else. The nonce does not
1803   * offer absolute protection, but should protect against most cases. It is very
1804   * important to use nonce field in forms.
1805   *
1806   * The $action and $name are optional, but if you want to have better security,
1807   * it is strongly suggested to set those two parameters. It is easier to just
1808   * call the function without any parameters, because validation of the nonce
1809   * doesn't require any parameters, but since crackers know what the default is
1810   * it won't be difficult for them to find a way around your nonce and cause
1811   * damage.
1812   *
1813   * The input name will be whatever $name value you gave. The input value will be
1814   * the nonce creation value.
1815   *
1816   * @since 2.0.4
1817   *
1818   * @param int|string $action  Optional. Action name. Default -1.
1819   * @param string     $name    Optional. Nonce name. Default '_wpnonce'.
1820   * @param bool       $referer Optional. Whether to set the referer field for validation. Default true.
1821   * @param bool       $echo    Optional. Whether to display or return hidden form field. Default true.
1822   * @return string Nonce field HTML markup.
1823   */
1824  function wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $echo = true ) {
1825      $name        = esc_attr( $name );
1826      $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1827  
1828      if ( $referer ) {
1829          $nonce_field .= wp_referer_field( false );
1830      }
1831  
1832      if ( $echo ) {
1833          echo $nonce_field;
1834      }
1835  
1836      return $nonce_field;
1837  }
1838  
1839  /**
1840   * Retrieve or display referer hidden field for forms.
1841   *
1842   * The referer link is the current Request URI from the server super global. The
1843   * input name is '_wp_http_referer', in case you wanted to check manually.
1844   *
1845   * @since 2.0.4
1846   *
1847   * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
1848   * @return string Referer field HTML markup.
1849   */
1850  function wp_referer_field( $echo = true ) {
1851      $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
1852  
1853      if ( $echo ) {
1854          echo $referer_field;
1855      }
1856  
1857      return $referer_field;
1858  }
1859  
1860  /**
1861   * Retrieve or display original referer hidden field for forms.
1862   *
1863   * The input name is '_wp_original_http_referer' and will be either the same
1864   * value of wp_referer_field(), if that was posted already or it will be the
1865   * current page, if it doesn't exist.
1866   *
1867   * @since 2.0.4
1868   *
1869   * @param bool   $echo         Optional. Whether to echo the original http referer. Default true.
1870   * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
1871   *                             Default 'current'.
1872   * @return string Original referer field.
1873   */
1874  function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1875      $ref = wp_get_original_referer();
1876  
1877      if ( ! $ref ) {
1878          $ref = ( 'previous' === $jump_back_to ) ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
1879      }
1880  
1881      $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
1882  
1883      if ( $echo ) {
1884          echo $orig_referer_field;
1885      }
1886  
1887      return $orig_referer_field;
1888  }
1889  
1890  /**
1891   * Retrieve referer from '_wp_http_referer' or HTTP referer.
1892   *
1893   * If it's the same as the current request URL, will return false.
1894   *
1895   * @since 2.0.4
1896   *
1897   * @return string|false Referer URL on success, false on failure.
1898   */
1899  function wp_get_referer() {
1900      if ( ! function_exists( 'wp_validate_redirect' ) ) {
1901          return false;
1902      }
1903  
1904      $ref = wp_get_raw_referer();
1905  
1906      if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref ) {
1907          return wp_validate_redirect( $ref, false );
1908      }
1909  
1910      return false;
1911  }
1912  
1913  /**
1914   * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
1915   *
1916   * Do not use for redirects, use wp_get_referer() instead.
1917   *
1918   * @since 4.5.0
1919   *
1920   * @return string|false Referer URL on success, false on failure.
1921   */
1922  function wp_get_raw_referer() {
1923      if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
1924          return wp_unslash( $_REQUEST['_wp_http_referer'] );
1925      } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
1926          return wp_unslash( $_SERVER['HTTP_REFERER'] );
1927      }
1928  
1929      return false;
1930  }
1931  
1932  /**
1933   * Retrieve original referer that was posted, if it exists.
1934   *
1935   * @since 2.0.4
1936   *
1937   * @return string|false Original referer URL on success, false on failure.
1938   */
1939  function wp_get_original_referer() {
1940      if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) ) {
1941          return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
1942      }
1943  
1944      return false;
1945  }
1946  
1947  /**
1948   * Recursive directory creation based on full path.
1949   *
1950   * Will attempt to set permissions on folders.
1951   *
1952   * @since 2.0.1
1953   *
1954   * @param string $target Full path to attempt to create.
1955   * @return bool Whether the path was created. True if path already exists.
1956   */
1957  function wp_mkdir_p( $target ) {
1958      $wrapper = null;
1959  
1960      // Strip the protocol.
1961      if ( wp_is_stream( $target ) ) {
1962          list( $wrapper, $target ) = explode( '://', $target, 2 );
1963      }
1964  
1965      // From php.net/mkdir user contributed notes.
1966      $target = str_replace( '//', '/', $target );
1967  
1968      // Put the wrapper back on the target.
1969      if ( null !== $wrapper ) {
1970          $target = $wrapper . '://' . $target;
1971      }
1972  
1973      /*
1974       * Safe mode fails with a trailing slash under certain PHP versions.
1975       * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1976       */
1977      $target = rtrim( $target, '/' );
1978      if ( empty( $target ) ) {
1979          $target = '/';
1980      }
1981  
1982      if ( file_exists( $target ) ) {
1983          return @is_dir( $target );
1984      }
1985  
1986      // Do not allow path traversals.
1987      if ( false !== strpos( $target, '../' ) || false !== strpos( $target, '..' . DIRECTORY_SEPARATOR ) ) {
1988          return false;
1989      }
1990  
1991      // We need to find the permissions of the parent folder that exists and inherit that.
1992      $target_parent = dirname( $target );
1993      while ( '.' !== $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) {
1994          $target_parent = dirname( $target_parent );
1995      }
1996  
1997      // Get the permission bits.
1998      $stat = @stat( $target_parent );
1999      if ( $stat ) {
2000          $dir_perms = $stat['mode'] & 0007777;
2001      } else {
2002          $dir_perms = 0777;
2003      }
2004  
2005      if ( @mkdir( $target, $dir_perms, true ) ) {
2006  
2007          /*
2008           * If a umask is set that modifies $dir_perms, we'll have to re-set
2009           * the $dir_perms correctly with chmod()
2010           */
2011          if ( ( $dir_perms & ~umask() ) != $dir_perms ) {
2012              $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
2013              for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
2014                  chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
2015              }
2016          }
2017  
2018          return true;
2019      }
2020  
2021      return false;
2022  }
2023  
2024  /**
2025   * Test if a given filesystem path is absolute.
2026   *
2027   * For example, '/foo/bar', or 'c:\windows'.
2028   *
2029   * @since 2.5.0
2030   *
2031   * @param string $path File path.
2032   * @return bool True if path is absolute, false is not absolute.
2033   */
2034  function path_is_absolute( $path ) {
2035      /*
2036       * Check to see if the path is a stream and check to see if its an actual
2037       * path or file as realpath() does not support stream wrappers.
2038       */
2039      if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
2040          return true;
2041      }
2042  
2043      /*
2044       * This is definitive if true but fails if $path does not exist or contains
2045       * a symbolic link.
2046       */
2047      if ( realpath( $path ) == $path ) {
2048          return true;
2049      }
2050  
2051      if ( strlen( $path ) == 0 || '.' === $path[0] ) {
2052          return false;
2053      }
2054  
2055      // Windows allows absolute paths like this.
2056      if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) {
2057          return true;
2058      }
2059  
2060      // A path starting with / or \ is absolute; anything else is relative.
2061      return ( '/' === $path[0] || '\\' === $path[0] );
2062  }
2063  
2064  /**
2065   * Join two filesystem paths together.
2066   *
2067   * For example, 'give me $path relative to $base'. If the $path is absolute,
2068   * then it the full path is returned.
2069   *
2070   * @since 2.5.0
2071   *
2072   * @param string $base Base path.
2073   * @param string $path Path relative to $base.
2074   * @return string The path with the base or absolute path.
2075   */
2076  function path_join( $base, $path ) {
2077      if ( path_is_absolute( $path ) ) {
2078          return $path;
2079      }
2080  
2081      return rtrim( $base, '/' ) . '/' . ltrim( $path, '/' );
2082  }
2083  
2084  /**
2085   * Normalize a filesystem path.
2086   *
2087   * On windows systems, replaces backslashes with forward slashes
2088   * and forces upper-case drive letters.
2089   * Allows for two leading slashes for Windows network shares, but
2090   * ensures that all other duplicate slashes are reduced to a single.
2091   *
2092   * @since 3.9.0
2093   * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
2094   * @since 4.5.0 Allows for Windows network shares.
2095   * @since 4.9.7 Allows for PHP file wrappers.
2096   *
2097   * @param string $path Path to normalize.
2098   * @return string Normalized path.
2099   */
2100  function wp_normalize_path( $path ) {
2101      $wrapper = '';
2102  
2103      if ( wp_is_stream( $path ) ) {
2104          list( $wrapper, $path ) = explode( '://', $path, 2 );
2105  
2106          $wrapper .= '://';
2107      }
2108  
2109      // Standardise all paths to use '/'.
2110      $path = str_replace( '\\', '/', $path );
2111  
2112      // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
2113      $path = preg_replace( '|(?<=.)/+|', '/', $path );
2114  
2115      // Windows paths should uppercase the drive letter.
2116      if ( ':' === substr( $path, 1, 1 ) ) {
2117          $path = ucfirst( $path );
2118      }
2119  
2120      return $wrapper . $path;
2121  }
2122  
2123  /**
2124   * Determine a writable directory for temporary files.
2125   *
2126   * Function's preference is the return value of sys_get_temp_dir(),
2127   * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
2128   * before finally defaulting to /tmp/
2129   *
2130   * In the event that this function does not find a writable location,
2131   * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
2132   *
2133   * @since 2.5.0
2134   *
2135   * @return string Writable temporary directory.
2136   */
2137  function get_temp_dir() {
2138      static $temp = '';
2139      if ( defined( 'WP_TEMP_DIR' ) ) {
2140          return trailingslashit( WP_TEMP_DIR );
2141      }
2142  
2143      if ( $temp ) {
2144          return trailingslashit( $temp );
2145      }
2146  
2147      if ( function_exists( 'sys_get_temp_dir' ) ) {
2148          $temp = sys_get_temp_dir();
2149          if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
2150              return trailingslashit( $temp );
2151          }
2152      }
2153  
2154      $temp = ini_get( 'upload_tmp_dir' );
2155      if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
2156          return trailingslashit( $temp );
2157      }
2158  
2159      $temp = WP_CONTENT_DIR . '/';
2160      if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
2161          return $temp;
2162      }
2163  
2164      return '/tmp/';
2165  }
2166  
2167  /**
2168   * Determine if a directory is writable.
2169   *
2170   * This function is used to work around certain ACL issues in PHP primarily
2171   * affecting Windows Servers.
2172   *
2173   * @since 3.6.0
2174   *
2175   * @see win_is_writable()
2176   *
2177   * @param string $path Path to check for write-ability.
2178   * @return bool Whether the path is writable.
2179   */
2180  function wp_is_writable( $path ) {
2181      if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) {
2182          return win_is_writable( $path );
2183      } else {
2184          return @is_writable( $path );
2185      }
2186  }
2187  
2188  /**
2189   * Workaround for Windows bug in is_writable() function
2190   *
2191   * PHP has issues with Windows ACL's for determine if a
2192   * directory is writable or not, this works around them by
2193   * checking the ability to open files rather than relying
2194   * upon PHP to interprate the OS ACL.
2195   *
2196   * @since 2.8.0
2197   *
2198   * @see https://bugs.php.net/bug.php?id=27609
2199   * @see https://bugs.php.net/bug.php?id=30931
2200   *
2201   * @param string $path Windows path to check for write-ability.
2202   * @return bool Whether the path is writable.
2203   */
2204  function win_is_writable( $path ) {
2205      if ( '/' === $path[ strlen( $path ) - 1 ] ) {
2206          // If it looks like a directory, check a random file within the directory.
2207          return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp' );
2208      } elseif ( is_dir( $path ) ) {
2209          // If it's a directory (and not a file), check a random file within the directory.
2210          return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
2211      }
2212  
2213      // Check tmp file for read/write capabilities.
2214      $should_delete_tmp_file = ! file_exists( $path );
2215  
2216      $f = @fopen( $path, 'a' );
2217      if ( false === $f ) {
2218          return false;
2219      }
2220      fclose( $f );
2221  
2222      if ( $should_delete_tmp_file ) {
2223          unlink( $path );
2224      }
2225  
2226      return true;
2227  }
2228  
2229  /**
2230   * Retrieves uploads directory information.
2231   *
2232   * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
2233   * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
2234   * when not uploading files.
2235   *
2236   * @since 4.5.0
2237   *
2238   * @see wp_upload_dir()
2239   *
2240   * @return array See wp_upload_dir() for description.
2241   */
2242  function wp_get_upload_dir() {
2243      return wp_upload_dir( null, false );
2244  }
2245  
2246  /**
2247   * Returns an array containing the current upload directory's path and URL.
2248   *
2249   * Checks the 'upload_path' option, which should be from the web root folder,
2250   * and if it isn't empty it will be used. If it is empty, then the path will be
2251   * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
2252   * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
2253   *
2254   * The upload URL path is set either by the 'upload_url_path' option or by using
2255   * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
2256   *
2257   * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
2258   * the administration settings panel), then the time will be used. The format
2259   * will be year first and then month.
2260   *
2261   * If the path couldn't be created, then an error will be returned with the key
2262   * 'error' containing the error message. The error suggests that the parent
2263   * directory is not writable by the server.
2264   *
2265   * @since 2.0.0
2266   * @uses _wp_upload_dir()
2267   *
2268   * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
2269   * @param bool   $create_dir Optional. Whether to check and create the uploads directory.
2270   *                           Default true for backward compatibility.
2271   * @param bool   $refresh_cache Optional. Whether to refresh the cache. Default false.
2272   * @return array {
2273   *     Array of information about the upload directory.
2274   *
2275   *     @type string       $path    Base directory and subdirectory or full path to upload directory.
2276   *     @type string       $url     Base URL and subdirectory or absolute URL to upload directory.
2277   *     @type string       $subdir  Subdirectory if uploads use year/month folders option is on.
2278   *     @type string       $basedir Path without subdir.
2279   *     @type string       $baseurl URL path without subdir.
2280   *     @type string|false $error   False or error message.
2281   * }
2282   */
2283  function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
2284      static $cache = array(), $tested_paths = array();
2285  
2286      $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
2287  
2288      if ( $refresh_cache || empty( $cache[ $key ] ) ) {
2289          $cache[ $key ] = _wp_upload_dir( $time );
2290      }
2291  
2292      /**
2293       * Filters the uploads directory data.
2294       *
2295       * @since 2.0.0
2296       *
2297       * @param array $uploads {
2298       *     Array of information about the upload directory.
2299       *
2300       *     @type string       $path    Base directory and subdirectory or full path to upload directory.
2301       *     @type string       $url     Base URL and subdirectory or absolute URL to upload directory.
2302       *     @type string       $subdir  Subdirectory if uploads use year/month folders option is on.
2303       *     @type string       $basedir Path without subdir.
2304       *     @type string       $baseurl URL path without subdir.
2305       *     @type string|false $error   False or error message.
2306       * }
2307       */
2308      $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
2309  
2310      if ( $create_dir ) {
2311          $path = $uploads['path'];
2312  
2313          if ( array_key_exists( $path, $tested_paths ) ) {
2314              $uploads['error'] = $tested_paths[ $path ];
2315          } else {
2316              if ( ! wp_mkdir_p( $path ) ) {
2317                  if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
2318                      $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
2319                  } else {
2320                      $error_path = wp_basename( $uploads['basedir'] ) . $uploads['subdir'];
2321                  }
2322  
2323                  $uploads['error'] = sprintf(
2324                      /* translators: %s: Directory path. */
2325                      __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
2326                      esc_html( $error_path )
2327                  );
2328              }
2329  
2330              $tested_paths[ $path ] = $uploads['error'];
2331          }
2332      }
2333  
2334      return $uploads;
2335  }
2336  
2337  /**
2338   * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
2339   *
2340   * @since 4.5.0
2341   * @access private
2342   *
2343   * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
2344   * @return array See wp_upload_dir()
2345   */
2346  function _wp_upload_dir( $time = null ) {
2347      $siteurl     = get_option( 'siteurl' );
2348      $upload_path = trim( get_option( 'upload_path' ) );
2349  
2350      if ( empty( $upload_path ) || 'wp-content/uploads' === $upload_path ) {
2351          $dir = WP_CONTENT_DIR . '/uploads';
2352      } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
2353          // $dir is absolute, $upload_path is (maybe) relative to ABSPATH.
2354          $dir = path_join( ABSPATH, $upload_path );
2355      } else {
2356          $dir = $upload_path;
2357      }
2358  
2359      $url = get_option( 'upload_url_path' );
2360      if ( ! $url ) {
2361          if ( empty( $upload_path ) || ( 'wp-content/uploads' === $upload_path ) || ( $upload_path == $dir ) ) {
2362              $url = WP_CONTENT_URL . '/uploads';
2363          } else {
2364              $url = trailingslashit( $siteurl ) . $upload_path;
2365          }
2366      }
2367  
2368      /*
2369       * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
2370       * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
2371       */
2372      if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
2373          $dir = ABSPATH . UPLOADS;
2374          $url = trailingslashit( $siteurl ) . UPLOADS;
2375      }
2376  
2377      // If multisite (and if not the main site in a post-MU network).
2378      if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
2379  
2380          if ( ! get_site_option( 'ms_files_rewriting' ) ) {
2381              /*
2382               * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
2383               * straightforward: Append sites/%d if we're not on the main site (for post-MU
2384               * networks). (The extra directory prevents a four-digit ID from conflicting with
2385               * a year-based directory for the main site. But if a MU-era network has disabled
2386               * ms-files rewriting manually, they don't need the extra directory, as they never
2387               * had wp-content/uploads for the main site.)
2388               */
2389  
2390              if ( defined( 'MULTISITE' ) ) {
2391                  $ms_dir = '/sites/' . get_current_blog_id();
2392              } else {
2393                  $ms_dir = '/' . get_current_blog_id();
2394              }
2395  
2396              $dir .= $ms_dir;
2397              $url .= $ms_dir;
2398  
2399          } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
2400              /*
2401               * Handle the old-form ms-files.php rewriting if the network still has that enabled.
2402               * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
2403               * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
2404               *    there, and
2405               * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
2406               *    the original blog ID.
2407               *
2408               * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
2409               * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
2410               * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
2411               * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
2412               */
2413  
2414              if ( defined( 'BLOGUPLOADDIR' ) ) {
2415                  $dir = untrailingslashit( BLOGUPLOADDIR );
2416              } else {
2417                  $dir = ABSPATH . UPLOADS;
2418              }
2419              $url = trailingslashit( $siteurl ) . 'files';
2420          }
2421      }
2422  
2423      $basedir = $dir;
2424      $baseurl = $url;
2425  
2426      $subdir = '';
2427      if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
2428          // Generate the yearly and monthly directories.
2429          if ( ! $time ) {
2430              $time = current_time( 'mysql' );
2431          }
2432          $y      = substr( $time, 0, 4 );
2433          $m      = substr( $time, 5, 2 );
2434          $subdir = "/$y/$m";
2435      }
2436  
2437      $dir .= $subdir;
2438      $url .= $subdir;
2439  
2440      return array(
2441          'path'    => $dir,
2442          'url'     => $url,
2443          'subdir'  => $subdir,
2444          'basedir' => $basedir,
2445          'baseurl' => $baseurl,
2446          'error'   => false,
2447      );
2448  }
2449  
2450  /**
2451   * Get a filename that is sanitized and unique for the given directory.
2452   *
2453   * If the filename is not unique, then a number will be added to the filename
2454   * before the extension, and will continue adding numbers until the filename
2455   * is unique.
2456   *
2457   * The callback function allows the caller to use their own method to create
2458   * unique file names. If defined, the callback should take three arguments:
2459   * - directory, base filename, and extension - and return a unique filename.
2460   *
2461   * @since 2.5.0
2462   *
2463   * @param string   $dir                      Directory.
2464   * @param string   $filename                 File name.
2465   * @param callable $unique_filename_callback Callback. Default null.
2466   * @return string New filename, if given wasn't unique.
2467   */
2468  function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
2469      // Sanitize the file name before we begin processing.
2470      $filename = sanitize_file_name( $filename );
2471      $ext2     = null;
2472  
2473      // Separate the filename into a name and extension.
2474      $ext  = pathinfo( $filename, PATHINFO_EXTENSION );
2475      $name = pathinfo( $filename, PATHINFO_BASENAME );
2476  
2477      if ( $ext ) {
2478          $ext = '.' . $ext;
2479      }
2480  
2481      // Edge case: if file is named '.ext', treat as an empty name.
2482      if ( $name === $ext ) {
2483          $name = '';
2484      }
2485  
2486      /*
2487       * Increment the file number until we have a unique file to save in $dir.
2488       * Use callback if supplied.
2489       */
2490      if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
2491          $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
2492      } else {
2493          $number = '';
2494          $fname  = pathinfo( $filename, PATHINFO_FILENAME );
2495  
2496          // Always append a number to file names that can potentially match image sub-size file names.
2497          if ( $fname && preg_match( '/-(?:\d+x\d+|scaled|rotated)$/', $fname ) ) {
2498              $number = 1;
2499  
2500              // At this point the file name may not be unique. This is tested below and the $number is incremented.
2501              $filename = str_replace( "{$fname}{$ext}", "{$fname}-{$number}{$ext}", $filename );
2502          }
2503  
2504          // Change '.ext' to lower case.
2505          if ( $ext && strtolower( $ext ) != $ext ) {
2506              $ext2      = strtolower( $ext );
2507              $filename2 = preg_replace( '|' . preg_quote( $ext ) . '$|', $ext2, $filename );
2508  
2509              // Check for both lower and upper case extension or image sub-sizes may be overwritten.
2510              while ( file_exists( $dir . "/{$filename}" ) || file_exists( $dir . "/{$filename2}" ) ) {
2511                  $new_number = (int) $number + 1;
2512                  $filename   = str_replace( array( "-{$number}{$ext}", "{$number}{$ext}" ), "-{$new_number}{$ext}", $filename );
2513                  $filename2  = str_replace( array( "-{$number}{$ext2}", "{$number}{$ext2}" ), "-{$new_number}{$ext2}", $filename2 );
2514                  $number     = $new_number;
2515              }
2516  
2517              $filename = $filename2;
2518          } else {
2519              while ( file_exists( $dir . "/{$filename}" ) ) {
2520                  $new_number = (int) $number + 1;
2521  
2522                  if ( '' === "{$number}{$ext}" ) {
2523                      $filename = "{$filename}-{$new_number}";
2524                  } else {
2525                      $filename = str_replace( array( "-{$number}{$ext}", "{$number}{$ext}" ), "-{$new_number}{$ext}", $filename );
2526                  }
2527  
2528                  $number = $new_number;
2529              }
2530          }
2531  
2532          // Prevent collisions with existing file names that contain dimension-like strings
2533          // (whether they are subsizes or originals uploaded prior to #42437).
2534          $upload_dir = wp_get_upload_dir();
2535  
2536          // The (resized) image files would have name and extension, and will be in the uploads dir.
2537          if ( $name && $ext && @is_dir( $dir ) && false !== strpos( $dir, $upload_dir['basedir'] ) ) {
2538              /**
2539               * Filters the file list used for calculating a unique filename for a newly added file.
2540               *
2541               * Returning an array from the filter will effectively short-circuit retrieval
2542               * from the filesystem and return the passed value instead.
2543               *
2544               * @since 5.5.0
2545               *
2546               * @param array|null $files    The list of files to use for filename comparisons.
2547               *                             Default null (to retrieve the list from the filesystem).
2548               * @param string     $dir      The directory for the new file.
2549               * @param string     $filename The proposed filename for the new file.
2550               */
2551              $files = apply_filters( 'pre_wp_unique_filename_file_list', null, $dir, $filename );
2552  
2553              if ( null === $files ) {
2554                  // List of all files and directories contained in $dir.
2555                  $files = @scandir( $dir );
2556              }
2557  
2558              if ( ! empty( $files ) ) {
2559                  // Remove "dot" dirs.
2560                  $files = array_diff( $files, array( '.', '..' ) );
2561              }
2562  
2563              if ( ! empty( $files ) ) {
2564                  // The extension case may have changed above.
2565                  $new_ext = ! empty( $ext2 ) ? $ext2 : $ext;
2566  
2567                  // Ensure this never goes into infinite loop
2568                  // as it uses pathinfo() and regex in the check, but string replacement for the changes.
2569                  $count = count( $files );
2570                  $i     = 0;
2571  
2572                  while ( $i <= $count && _wp_check_existing_file_names( $filename, $files ) ) {
2573                      $new_number = (int) $number + 1;
2574                      $filename   = str_replace( array( "-{$number}{$new_ext}", "{$number}{$new_ext}" ), "-{$new_number}{$new_ext}", $filename );
2575                      $number     = $new_number;
2576                      $i++;
2577                  }
2578              }
2579          }
2580      }
2581  
2582      /**
2583       * Filters the result when generating a unique file name.
2584       *
2585       * @since 4.5.0
2586       *
2587       * @param string        $filename                 Unique file name.
2588       * @param string        $ext                      File extension, eg. ".png".
2589       * @param string        $dir                      Directory path.
2590       * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
2591       */
2592      return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
2593  }
2594  
2595  /**
2596   * Helper function to check if a file name could match an existing image sub-size file name.
2597   *
2598   * @since 5.3.1
2599   * @access private
2600   *
2601   * @param string $filename The file name to check.
2602   * @param array  $files    An array of existing files in the directory.
2603   * @return bool True if the tested file name could match an existing file, false otherwise.
2604   */
2605  function _wp_check_existing_file_names( $filename, $files ) {
2606      $fname = pathinfo( $filename, PATHINFO_FILENAME );
2607      $ext   = pathinfo( $filename, PATHINFO_EXTENSION );
2608  
2609      // Edge case, file names like `.ext`.
2610      if ( empty( $fname ) ) {
2611          return false;
2612      }
2613  
2614      if ( $ext ) {
2615          $ext = ".$ext";
2616      }
2617  
2618      $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i';
2619  
2620      foreach ( $files as $file ) {
2621          if ( preg_match( $regex, $file ) ) {
2622              return true;
2623          }
2624      }
2625  
2626      return false;
2627  }
2628  
2629  /**
2630   * Create a file in the upload folder with given content.
2631   *
2632   * If there is an error, then the key 'error' will exist with the error message.
2633   * If success, then the key 'file' will have the unique file path, the 'url' key
2634   * will have the link to the new file. and the 'error' key will be set to false.
2635   *
2636   * This function will not move an uploaded file to the upload folder. It will
2637   * create a new file with the content in $bits parameter. If you move the upload
2638   * file, read the content of the uploaded file, and then you can give the
2639   * filename and content to this function, which will add it to the upload
2640   * folder.
2641   *
2642   * The permissions will be set on the new file automatically by this function.
2643   *
2644   * @since 2.0.0
2645   *
2646   * @param string      $name       Filename.
2647   * @param null|string $deprecated Never used. Set to null.
2648   * @param string      $bits       File content
2649   * @param string      $time       Optional. Time formatted in 'yyyy/mm'. Default null.
2650   * @return array {
2651   *     Information about the newly-uploaded file.
2652   *
2653   *     @type string       $file  Filename of the newly-uploaded file.
2654   *     @type string       $url   URL of the uploaded file.
2655   *     @type string       $type  File type.
2656   *     @type string|false $error Error message, if there has been an error.
2657   * }
2658   */
2659  function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
2660      if ( ! empty( $deprecated ) ) {
2661          _deprecated_argument( __FUNCTION__, '2.0.0' );
2662      }
2663  
2664      if ( empty( $name ) ) {
2665          return array( 'error' => __( 'Empty filename' ) );
2666      }
2667  
2668      $wp_filetype = wp_check_filetype( $name );
2669      if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
2670          return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.' ) );
2671      }
2672  
2673      $upload = wp_upload_dir( $time );
2674  
2675      if ( false !== $upload['error'] ) {
2676          return $upload;
2677      }
2678  
2679      /**
2680       * Filters whether to treat the upload bits as an error.
2681       *
2682       * Returning a non-array from the filter will effectively short-circuit preparing the upload bits
2683       * and return that value instead. An error message should be returned as a string.
2684       *
2685       * @since 3.0.0
2686       *
2687       * @param array|string $upload_bits_error An array of upload bits data, or error message to return.
2688       */
2689      $upload_bits_error = apply_filters(
2690          'wp_upload_bits',
2691          array(
2692              'name' => $name,
2693              'bits' => $bits,
2694              'time' => $time,
2695          )
2696      );
2697      if ( ! is_array( $upload_bits_error ) ) {
2698          $upload['error'] = $upload_bits_error;
2699          return $upload;
2700      }
2701  
2702      $filename = wp_unique_filename( $upload['path'], $name );
2703  
2704      $new_file = $upload['path'] . "/$filename";
2705      if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
2706          if ( 0 === strpos( $upload['basedir'], ABSPATH ) ) {
2707              $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
2708          } else {
2709              $error_path = wp_basename( $upload['basedir'] ) . $upload['subdir'];
2710          }
2711  
2712          $message = sprintf(
2713              /* translators: %s: Directory path. */
2714              __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
2715              $error_path
2716          );
2717          return array( 'error' => $message );
2718      }
2719  
2720      $ifp = @fopen( $new_file, 'wb' );
2721      if ( ! $ifp ) {
2722          return array(
2723              /* translators: %s: File name. */
2724              'error' => sprintf( __( 'Could not write file %s' ), $new_file ),
2725          );
2726      }
2727  
2728      fwrite( $ifp, $bits );
2729      fclose( $ifp );
2730      clearstatcache();
2731  
2732      // Set correct file permissions.
2733      $stat  = @ stat( dirname( $new_file ) );
2734      $perms = $stat['mode'] & 0007777;
2735      $perms = $perms & 0000666;
2736      chmod( $new_file, $perms );
2737      clearstatcache();
2738  
2739      // Compute the URL.
2740      $url = $upload['url'] . "/$filename";
2741  
2742      /** This filter is documented in wp-admin/includes/file.php */
2743      return apply_filters(
2744          'wp_handle_upload',
2745          array(
2746              'file'  => $new_file,
2747              'url'   => $url,
2748              'type'  => $wp_filetype['type'],
2749              'error' => false,
2750          ),
2751          'sideload'
2752      );
2753  }
2754  
2755  /**
2756   * Retrieve the file type based on the extension name.
2757   *
2758   * @since 2.5.0
2759   *
2760   * @param string $ext The extension to search.
2761   * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
2762   */
2763  function wp_ext2type( $ext ) {
2764      $ext = strtolower( $ext );
2765  
2766      $ext2type = wp_get_ext_types();
2767      foreach ( $ext2type as $type => $exts ) {
2768          if ( in_array( $ext, $exts, true ) ) {
2769              return $type;
2770          }
2771      }
2772  }
2773  
2774  /**
2775   * Retrieve the file type from the file name.
2776   *
2777   * You can optionally define the mime array, if needed.
2778   *
2779   * @since 2.0.4
2780   *
2781   * @param string   $filename File name or path.
2782   * @param string[] $mimes    Optional. Array of mime types keyed by their file extension regex.
2783   * @return array {
2784   *     Values for the extension and mime type.
2785   *
2786   *     @type string|false $ext  File extension, or false if the file doesn't match a mime type.
2787   *     @type string|false $type File mime type, or false if the file doesn't match a mime type.
2788   * }
2789   */
2790  function wp_check_filetype( $filename, $mimes = null ) {
2791      if ( empty( $mimes ) ) {
2792          $mimes = get_allowed_mime_types();
2793      }
2794      $type = false;
2795      $ext  = false;
2796  
2797      foreach ( $mimes as $ext_preg => $mime_match ) {
2798          $ext_preg = '!\.(' . $ext_preg . ')$!i';
2799          if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
2800              $type = $mime_match;
2801              $ext  = $ext_matches[1];
2802              break;
2803          }
2804      }
2805  
2806      return compact( 'ext', 'type' );
2807  }
2808  
2809  /**
2810   * Attempt to determine the real file type of a file.
2811   *
2812   * If unable to, the file name extension will be used to determine type.
2813   *
2814   * If it's determined that the extension does not match the file's real type,
2815   * then the "proper_filename" value will be set with a proper filename and extension.
2816   *
2817   * Currently this function only supports renaming images validated via wp_get_image_mime().
2818   *
2819   * @since 3.0.0
2820   *
2821   * @param string   $file     Full path to the file.
2822   * @param string   $filename The name of the file (may differ from $file due to $file being
2823   *                           in a tmp directory).
2824   * @param string[] $mimes    Optional. Array of mime types keyed by their file extension regex.
2825   * @return array {
2826   *     Values for the extension, mime type, and corrected filename.
2827   *
2828   *     @type string|false $ext             File extension, or false if the file doesn't match a mime type.
2829   *     @type string|false $type            File mime type, or false if the file doesn't match a mime type.
2830   *     @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
2831   * }
2832   */
2833  function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
2834      $proper_filename = false;
2835  
2836      // Do basic extension validation and MIME mapping.
2837      $wp_filetype = wp_check_filetype( $filename, $mimes );
2838      $ext         = $wp_filetype['ext'];
2839      $type        = $wp_filetype['type'];
2840  
2841      // We can't do any further validation without a file to work with.
2842      if ( ! file_exists( $file ) ) {
2843          return compact( 'ext', 'type', 'proper_filename' );
2844      }
2845  
2846      $real_mime = false;
2847  
2848      // Validate image types.
2849      if ( $type && 0 === strpos( $type, 'image/' ) ) {
2850  
2851          // Attempt to figure out what type of image it actually is.
2852          $real_mime = wp_get_image_mime( $file );
2853  
2854          if ( $real_mime && $real_mime != $type ) {
2855              /**
2856               * Filters the list mapping image mime types to their respective extensions.
2857               *
2858               * @since 3.0.0
2859               *
2860               * @param array $mime_to_ext Array of image mime types and their matching extensions.
2861               */
2862              $mime_to_ext = apply_filters(
2863                  'getimagesize_mimes_to_exts',
2864                  array(
2865                      'image/jpeg' => 'jpg',
2866                      'image/png'  => 'png',
2867                      'image/gif'  => 'gif',
2868                      'image/bmp'  => 'bmp',
2869                      'image/tiff' => 'tif',
2870                  )
2871              );
2872  
2873              // Replace whatever is after the last period in the filename with the correct extension.
2874              if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
2875                  $filename_parts = explode( '.', $filename );
2876                  array_pop( $filename_parts );
2877                  $filename_parts[] = $mime_to_ext[ $real_mime ];
2878                  $new_filename     = implode( '.', $filename_parts );
2879  
2880                  if ( $new_filename != $filename ) {
2881                      $proper_filename = $new_filename; // Mark that it changed.
2882                  }
2883                  // Redefine the extension / MIME.
2884                  $wp_filetype = wp_check_filetype( $new_filename, $mimes );
2885                  $ext         = $wp_filetype['ext'];
2886                  $type        = $wp_filetype['type'];
2887              } else {
2888                  // Reset $real_mime and try validating again.
2889                  $real_mime = false;
2890              }
2891          }
2892      }
2893  
2894      // Validate files that didn't get validated during previous checks.
2895      if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) {
2896          $finfo     = finfo_open( FILEINFO_MIME_TYPE );
2897          $real_mime = finfo_file( $finfo, $file );
2898          finfo_close( $finfo );
2899  
2900          // fileinfo often misidentifies obscure files as one of these types.
2901          $nonspecific_types = array(
2902              'application/octet-stream',
2903              'application/encrypted',
2904              'application/CDFV2-encrypted',
2905              'application/zip',
2906          );
2907  
2908          /*
2909           * If $real_mime doesn't match the content type we're expecting from the file's extension,
2910           * we need to do some additional vetting. Media types and those listed in $nonspecific_types are
2911           * allowed some leeway, but anything else must exactly match the real content type.
2912           */
2913          if ( in_array( $real_mime, $nonspecific_types, true ) ) {
2914              // File is a non-specific binary type. That's ok if it's a type that generally tends to be binary.
2915              if ( ! in_array( substr( $type, 0, strcspn( $type, '/' ) ), array( 'application', 'video', 'audio' ), true ) ) {
2916                  $type = false;
2917                  $ext  = false;
2918              }
2919          } elseif ( 0 === strpos( $real_mime, 'video/' ) || 0 === strpos( $real_mime, 'audio/' ) ) {
2920              /*
2921               * For these types, only the major type must match the real value.
2922               * This means that common mismatches are forgiven: application/vnd.apple.numbers is often misidentified as application/zip,
2923               * and some media files are commonly named with the wrong extension (.mov instead of .mp4)
2924               */
2925              if ( substr( $real_mime, 0, strcspn( $real_mime, '/' ) ) !== substr( $type, 0, strcspn( $type, '/' ) ) ) {
2926                  $type = false;
2927                  $ext  = false;
2928              }
2929          } elseif ( 'text/plain' === $real_mime ) {
2930              // A few common file types are occasionally detected as text/plain; allow those.
2931              if ( ! in_array(
2932                  $type,
2933                  array(
2934                      'text/plain',
2935                      'text/csv',
2936                      'text/richtext',
2937                      'text/tsv',
2938                      'text/vtt',
2939                  ),
2940                  true
2941              )
2942              ) {
2943                  $type = false;
2944                  $ext  = false;
2945              }
2946          } elseif ( 'text/rtf' === $real_mime ) {
2947              // Special casing for RTF files.
2948              if ( ! in_array(
2949                  $type,
2950                  array(
2951                      'text/rtf',
2952                      'text/plain',
2953                      'application/rtf',
2954                  ),
2955                  true
2956              )
2957              ) {
2958                  $type = false;
2959                  $ext  = false;
2960              }
2961          } else {
2962              if ( $type !== $real_mime ) {
2963                  /*
2964                   * Everything else including image/* and application/*:
2965                   * If the real content type doesn't match the file extension, assume it's dangerous.
2966                   */
2967                  $type = false;
2968                  $ext  = false;
2969              }
2970          }
2971      }
2972  
2973      // The mime type must be allowed.
2974      if ( $type ) {
2975          $allowed = get_allowed_mime_types();
2976  
2977          if ( ! in_array( $type, $allowed, true ) ) {
2978              $type = false;
2979              $ext  = false;
2980          }
2981      }
2982  
2983      /**
2984       * Filters the "real" file type of the given file.
2985       *
2986       * @since 3.0.0
2987       * @since 5.1.0 The $real_mime parameter was added.
2988       *
2989       * @param array       $wp_check_filetype_and_ext {
2990       *     Values for the extension, mime type, and corrected filename.
2991       *
2992       *     @type string|false $ext             File extension, or false if the file doesn't match a mime type.
2993       *     @type string|false $type            File mime type, or false if the file doesn't match a mime type.
2994       *     @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
2995       * }
2996       * @param string      $file                      Full path to the file.
2997       * @param string      $filename                  The name of the file (may differ from $file due to
2998       *                                               $file being in a tmp directory).
2999       * @param string[]    $mimes                     Array of mime types keyed by their file extension regex.
3000       * @param string|bool $real_mime                 The actual mime type or false if the type cannot be determined.
3001       */
3002      return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime );
3003  }
3004  
3005  /**
3006   * Returns the real mime type of an image file.
3007   *
3008   * This depends on exif_imagetype() or getimagesize() to determine real mime types.
3009   *
3010   * @since 4.7.1
3011   *
3012   * @param string $file Full path to the file.
3013   * @return string|false The actual mime type or false if the type cannot be determined.
3014   */
3015  function wp_get_image_mime( $file ) {
3016      /*
3017       * Use exif_imagetype() to check the mimetype if available or fall back to
3018       * getimagesize() if exif isn't avaialbe. If either function throws an Exception
3019       * we assume the file could not be validated.
3020       */
3021      try {
3022          if ( is_callable( 'exif_imagetype' ) ) {
3023              $imagetype = exif_imagetype( $file );
3024              $mime      = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
3025          } elseif ( function_exists( 'getimagesize' ) ) {
3026              $imagesize = @getimagesize( $file );
3027              $mime      = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
3028          } else {
3029              $mime = false;
3030          }
3031      } catch ( Exception $e ) {
3032          $mime = false;
3033      }
3034  
3035      return $mime;
3036  }
3037  
3038  /**
3039   * Retrieve list of mime types and file extensions.
3040   *
3041   * @since 3.5.0
3042   * @since 4.2.0 Support was added for GIMP (.xcf) files.
3043   * @since 4.9.2 Support was added for Flac (.flac) files.
3044   * @since 4.9.6 Support was added for AAC (.aac) files.
3045   *
3046   * @return string[] Array of mime types keyed by the file extension regex corresponding to those types.
3047   */
3048  function wp_get_mime_types() {
3049      /**
3050       * Filters the list of mime types and file extensions.
3051       *
3052       * This filter should be used to add, not remove, mime types. To remove
3053       * mime types, use the {@see 'upload_mimes'} filter.
3054       *
3055       * @since 3.5.0
3056       *
3057       * @param string[] $wp_get_mime_types Mime types keyed by the file extension regex
3058       *                                 corresponding to those types.
3059       */
3060      return apply_filters(
3061          'mime_types',
3062          array(
3063              // Image formats.
3064              'jpg|jpeg|jpe'                 => 'image/jpeg',
3065              'gif'                          => 'image/gif',
3066              'png'                          => 'image/png',
3067              'bmp'                          => 'image/bmp',
3068              'tiff|tif'                     => 'image/tiff',
3069              'ico'                          => 'image/x-icon',
3070              'heic'                         => 'image/heic',
3071              // Video formats.
3072              'asf|asx'                      => 'video/x-ms-asf',
3073              'wmv'                          => 'video/x-ms-wmv',
3074              'wmx'                          => 'video/x-ms-wmx',
3075              'wm'                           => 'video/x-ms-wm',
3076              'avi'                          => 'video/avi',
3077              'divx'                         => 'video/divx',
3078              'flv'                          => 'video/x-flv',
3079              'mov|qt'                       => 'video/quicktime',
3080              'mpeg|mpg|mpe'                 => 'video/mpeg',
3081              'mp4|m4v'                      => 'video/mp4',
3082              'ogv'                          => 'video/ogg',
3083              'webm'                         => 'video/webm',
3084              'mkv'                          => 'video/x-matroska',
3085              '3gp|3gpp'                     => 'video/3gpp',  // Can also be audio.
3086              '3g2|3gp2'                     => 'video/3gpp2', // Can also be audio.
3087              // Text formats.
3088              'txt|asc|c|cc|h|srt'           => 'text/plain',
3089              'csv'                          => 'text/csv',
3090              'tsv'                          => 'text/tab-separated-values',
3091              'ics'                          => 'text/calendar',
3092              'rtx'                          => 'text/richtext',
3093              'css'                          => 'text/css',
3094              'htm|html'                     => 'text/html',
3095              'vtt'                          => 'text/vtt',
3096              'dfxp'                         => 'application/ttaf+xml',
3097              // Audio formats.
3098              'mp3|m4a|m4b'                  => 'audio/mpeg',
3099              'aac'                          => 'audio/aac',
3100              'ra|ram'                       => 'audio/x-realaudio',
3101              'wav'                          => 'audio/wav',
3102              'ogg|oga'                      => 'audio/ogg',
3103              'flac'                         => 'audio/flac',
3104              'mid|midi'                     => 'audio/midi',
3105              'wma'                          => 'audio/x-ms-wma',
3106              'wax'                          => 'audio/x-ms-wax',
3107              'mka'                          => 'audio/x-matroska',
3108              // Misc application formats.
3109              'rtf'                          => 'application/rtf',
3110              'js'                           => 'application/javascript',
3111              'pdf'                          => 'application/pdf',
3112              'swf'                          => 'application/x-shockwave-flash',
3113              'class'                        => 'application/java',
3114              'tar'                          => 'application/x-tar',
3115              'zip'                          => 'application/zip',
3116              'gz|gzip'                      => 'application/x-gzip',
3117              'rar'                          => 'application/rar',
3118              '7z'                           => 'application/x-7z-compressed',
3119              'exe'                          => 'application/x-msdownload',
3120              'psd'                          => 'application/octet-stream',
3121              'xcf'                          => 'application/octet-stream',
3122              // MS Office formats.
3123              'doc'                          => 'application/msword',
3124              'pot|pps|ppt'                  => 'application/vnd.ms-powerpoint',
3125              'wri'                          => 'application/vnd.ms-write',
3126              'xla|xls|xlt|xlw'              => 'application/vnd.ms-excel',
3127              'mdb'                          => 'application/vnd.ms-access',
3128              'mpp'                          => 'application/vnd.ms-project',
3129              'docx'                         => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3130              'docm'                         => 'application/vnd.ms-word.document.macroEnabled.12',
3131              'dotx'                         => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
3132              'dotm'                         => 'application/vnd.ms-word.template.macroEnabled.12',
3133              'xlsx'                         => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3134              'xlsm'                         => 'application/vnd.ms-excel.sheet.macroEnabled.12',
3135              'xlsb'                         => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
3136              'xltx'                         => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
3137              'xltm'                         => 'application/vnd.ms-excel.template.macroEnabled.12',
3138              'xlam'                         => 'application/vnd.ms-excel.addin.macroEnabled.12',
3139              'pptx'                         => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
3140              'pptm'                         => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
3141              'ppsx'                         => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
3142              'ppsm'                         => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
3143              'potx'                         => 'application/vnd.openxmlformats-officedocument.presentationml.template',
3144              'potm'                         => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
3145              'ppam'                         => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
3146              'sldx'                         => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
3147              'sldm'                         => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
3148              'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
3149              'oxps'                         => 'application/oxps',
3150              'xps'                          => 'application/vnd.ms-xpsdocument',
3151              // OpenOffice formats.
3152              'odt'                          => 'application/vnd.oasis.opendocument.text',
3153              'odp'                          => 'application/vnd.oasis.opendocument.presentation',
3154              'ods'                          => 'application/vnd.oasis.opendocument.spreadsheet',
3155              'odg'                          => 'application/vnd.oasis.opendocument.graphics',
3156              'odc'                          => 'application/vnd.oasis.opendocument.chart',
3157              'odb'                          => 'application/vnd.oasis.opendocument.database',
3158              'odf'                          => 'application/vnd.oasis.opendocument.formula',
3159              // WordPerfect formats.
3160              'wp|wpd'                       => 'application/wordperfect',
3161              // iWork formats.
3162              'key'                          => 'application/vnd.apple.keynote',
3163              'numbers'                      => 'application/vnd.apple.numbers',
3164              'pages'                        => 'application/vnd.apple.pages',
3165          )
3166      );
3167  }
3168  
3169  /**
3170   * Retrieves the list of common file extensions and their types.
3171   *
3172   * @since 4.6.0
3173   *
3174   * @return array[] Multi-dimensional array of file extensions types keyed by the type of file.
3175   */
3176  function wp_get_ext_types() {
3177  
3178      /**
3179       * Filters file type based on the extension name.
3180       *
3181       * @since 2.5.0
3182       *
3183       * @see wp_ext2type()
3184       *
3185       * @param array[] $ext2type Multi-dimensional array of file extensions types keyed by the type of file.
3186       */
3187      return apply_filters(
3188          'ext2type',
3189          array(
3190              'image'       => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico', 'heic' ),
3191              'audio'       => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
3192              'video'       => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
3193              'document'    => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
3194              'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
3195              'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
3196              'text'        => array( 'asc', 'csv', 'tsv', 'txt' ),
3197              'archive'     => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
3198              'code'        => array( 'css', 'htm', 'html', 'php', 'js' ),
3199          )
3200      );
3201  }
3202  
3203  /**
3204   * Retrieve list of allowed mime types and file extensions.
3205   *
3206   * @since 2.8.6
3207   *
3208   * @param int|WP_User $user Optional. User to check. Defaults to current user.
3209   * @return string[] Array of mime types keyed by the file extension regex corresponding
3210   *                  to those types.
3211   */
3212  function get_allowed_mime_types( $user = null ) {
3213      $t = wp_get_mime_types();
3214  
3215      unset( $t['swf'], $t['exe'] );
3216      if ( function_exists( 'current_user_can' ) ) {
3217          $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
3218      }
3219  
3220      if ( empty( $unfiltered ) ) {
3221          unset( $t['htm|html'], $t['js'] );
3222      }
3223  
3224      /**
3225       * Filters list of allowed mime types and file extensions.
3226       *
3227       * @since 2.0.0
3228       *
3229       * @param array            $t    Mime types keyed by the file extension regex corresponding to those types.
3230       * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
3231       */
3232      return apply_filters( 'upload_mimes', $t, $user );
3233  }
3234  
3235  /**
3236   * Display "Are You Sure" message to confirm the action being taken.
3237   *
3238   * If the action has the nonce explain message, then it will be displayed
3239   * along with the "Are you sure?" message.
3240   *
3241   * @since 2.0.4
3242   *
3243   * @param string $action The nonce action.
3244   */
3245  function wp_nonce_ays( $action ) {
3246      if ( 'log-out' === $action ) {
3247          $html = sprintf(
3248              /* translators: %s: Site title. */
3249              __( 'You are attempting to log out of %s' ),
3250              get_bloginfo( 'name' )
3251          );
3252          $html       .= '</p><p>';
3253          $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
3254          $html       .= sprintf(
3255              /* translators: %s: Logout URL. */
3256              __( 'Do you really want to <a href="%s">log out</a>?' ),
3257              wp_logout_url( $redirect_to )
3258          );
3259      } else {
3260          $html = __( 'The link you followed has expired.' );
3261          if ( wp_get_referer() ) {
3262              $html .= '</p><p>';
3263              $html .= sprintf(
3264                  '<a href="%s">%s</a>',
3265                  esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
3266                  __( 'Please try again.' )
3267              );
3268          }
3269      }
3270  
3271      wp_die( $html, __( 'Something went wrong.' ), 403 );
3272  }
3273  
3274  /**
3275   * Kills WordPress execution and displays HTML page with an error message.
3276   *
3277   * This function complements the `die()` PHP function. The difference is that
3278   * HTML will be displayed to the user. It is recommended to use this function
3279   * only when the execution should not continue any further. It is not recommended
3280   * to call this function very often, and try to handle as many errors as possible
3281   * silently or more gracefully.
3282   *
3283   * As a shorthand, the desired HTTP response code may be passed as an integer to
3284   * the `$title` parameter (the default title would apply) or the `$args` parameter.
3285   *
3286   * @since 2.0.4
3287   * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
3288   *              an integer to be used as the response code.
3289   * @since 5.1.0 The `$link_url`, `$link_text`, and `$exit` arguments were added.
3290   * @since 5.3.0 The `$charset` argument was added.
3291   * @since 5.5.0 The `$text_direction` argument has a priority over get_language_attributes()
3292   *              in the default handler.
3293   *
3294   * @global WP_Query $wp_query WordPress Query object.
3295   *
3296   * @param string|WP_Error  $message Optional. Error message. If this is a WP_Error object,
3297   *                                  and not an Ajax or XML-RPC request, the error's messages are used.
3298   *                                  Default empty.
3299   * @param string|int       $title   Optional. Error title. If `$message` is a `WP_Error` object,
3300   *                                  error data with the key 'title' may be used to specify the title.
3301   *                                  If `$title` is an integer, then it is treated as the response
3302   *                                  code. Default empty.
3303   * @param string|array|int $args {
3304   *     Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
3305   *     as the response code. Default empty array.
3306   *
3307   *     @type int    $response       The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
3308   *     @type string $link_url       A URL to include a link to. Only works in combination with $link_text.
3309   *                                  Default empty string.
3310   *     @type string $link_text      A label for the link to include. Only works in combination with $link_url.
3311   *                                  Default empty string.
3312   *     @type bool   $back_link      Whether to include a link to go back. Default false.
3313   *     @type string $text_direction The text direction. This is only useful internally, when WordPress is still
3314   *                                  loading and the site's locale is not set up yet. Accepts 'rtl' and 'ltr'.
3315   *                                  Default is the value of is_rtl().
3316   *     @type string $charset        Character set of the HTML output. Default 'utf-8'.
3317   *     @type string $code           Error code to use. Default is 'wp_die', or the main error code if $message
3318   *                                  is a WP_Error.
3319   *     @type bool   $exit           Whether to exit the process after completion. Default true.
3320   * }
3321   */
3322  function wp_die( $message = '', $title = '', $args = array() ) {
3323      global $wp_query;
3324  
3325      if ( is_int( $args ) ) {
3326          $args = array( 'response' => $args );
3327      } elseif ( is_int( $title ) ) {
3328          $args  = array( 'response' => $title );
3329          $title = '';
3330      }
3331  
3332      if ( wp_doing_ajax() ) {
3333          /**
3334           * Filters the callback for killing WordPress execution for Ajax requests.
3335           *
3336           * @since 3.4.0
3337           *
3338           * @param callable $function Callback function name.
3339           */
3340          $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
3341      } elseif ( wp_is_json_request() ) {
3342          /**
3343           * Filters the callback for killing WordPress execution for JSON requests.
3344           *
3345           * @since 5.1.0
3346           *
3347           * @param callable $function Callback function name.
3348           */
3349          $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' );
3350      } elseif ( wp_is_jsonp_request() ) {
3351          /**
3352           * Filters the callback for killing WordPress execution for JSONP requests.
3353           *
3354           * @since 5.2.0
3355           *
3356           * @param callable $function Callback function name.
3357           */
3358          $function = apply_filters( 'wp_die_jsonp_handler', '_jsonp_wp_die_handler' );
3359      } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
3360          /**
3361           * Filters the callback for killing WordPress execution for XML-RPC requests.
3362           *
3363           * @since 3.4.0
3364           *
3365           * @param callable $function Callback function name.
3366           */
3367          $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
3368      } elseif ( wp_is_xml_request()
3369          || isset( $wp_query ) &&
3370              ( function_exists( 'is_feed' ) && is_feed()
3371              || function_exists( 'is_comment_feed' ) && is_comment_feed()
3372              || function_exists( 'is_trackback' ) && is_trackback() ) ) {
3373          /**
3374           * Filters the callback for killing WordPress execution for XML requests.
3375           *
3376           * @since 5.2.0
3377           *
3378           * @param callable $function Callback function name.
3379           */
3380          $function = apply_filters( 'wp_die_xml_handler', '_xml_wp_die_handler' );
3381      } else {
3382          /**
3383           * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests.
3384           *
3385           * @since 3.0.0
3386           *
3387           * @param callable $function Callback function name.
3388           */
3389          $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
3390      }
3391  
3392      call_user_func( $function, $message, $title, $args );
3393  }
3394  
3395  /**
3396   * Kills WordPress execution and displays HTML page with an error message.
3397   *
3398   * This is the default handler for wp_die(). If you want a custom one,
3399   * you can override this using the {@see 'wp_die_handler'} filter in wp_die().
3400   *
3401   * @since 3.0.0
3402   * @access private
3403   *
3404   * @param string|WP_Error $message Error message or WP_Error object.
3405   * @param string          $title   Optional. Error title. Default empty.
3406   * @param string|array    $args    Optional. Arguments to control behavior. Default empty array.
3407   */
3408  function _default_wp_die_handler( $message, $title = '', $args = array() ) {
3409      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3410  
3411      if ( is_string( $message ) ) {
3412          if ( ! empty( $parsed_args['additional_errors'] ) ) {
3413              $message = array_merge(
3414                  array( $message ),
3415                  wp_list_pluck( $parsed_args['additional_errors'], 'message' )
3416              );
3417              $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $message ) . "</li>\n\t</ul>";
3418          }
3419  
3420          $message = sprintf(
3421              '<div class="wp-die-message">%s</div>',
3422              $message
3423          );
3424      }
3425  
3426      $have_gettext = function_exists( '__' );
3427  
3428      if ( ! empty( $parsed_args['link_url'] ) && ! empty( $parsed_args['link_text'] ) ) {
3429          $link_url = $parsed_args['link_url'];
3430          if ( function_exists( 'esc_url' ) ) {
3431              $link_url = esc_url( $link_url );
3432          }
3433          $link_text = $parsed_args['link_text'];
3434          $message  .= "\n<p><a href='{$link_url}'>{$link_text}</a></p>";
3435      }
3436  
3437      if ( isset( $parsed_args['back_link'] ) && $parsed_args['back_link'] ) {
3438          $back_text = $have_gettext ? __( '&laquo; Back' ) : '&laquo; Back';
3439          $message  .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
3440      }
3441  
3442      if ( ! did_action( 'admin_head' ) ) :
3443          if ( ! headers_sent() ) {
3444              header( "Content-Type: text/html; charset={$parsed_args['charset']}" );
3445              status_header( $parsed_args['response'] );
3446              nocache_headers();
3447          }
3448  
3449          $text_direction = $parsed_args['text_direction'];
3450          $dir_attr       = "dir='$text_direction'";
3451  
3452          // If `text_direction` was not explicitly passed,
3453          // use get_language_attributes() if available.
3454          if ( empty( $args['text_direction'] )
3455              && function_exists( 'language_attributes' ) && function_exists( 'is_rtl' )
3456          ) {
3457              $dir_attr = get_language_attributes();
3458          }
3459          ?>
3460  <!DOCTYPE html>
3461  <html <?php echo $dir_attr; ?>>
3462  <head>
3463      <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $parsed_args['charset']; ?>" />
3464      <meta name="viewport" content="width=device-width">
3465          <?php
3466          if ( function_exists( 'wp_no_robots' ) ) {
3467              wp_no_robots();
3468          }
3469          ?>
3470      <title><?php echo $title; ?></title>
3471      <style type="text/css">
3472          html {
3473              background: #f1f1f1;
3474          }
3475          body {
3476              background: #fff;
3477              color: #444;
3478              font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
3479              margin: 2em auto;
3480              padding: 1em 2em;
3481              max-width: 700px;
3482              -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
3483              box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
3484          }
3485          h1 {
3486              border-bottom: 1px solid #dadada;
3487              clear: both;
3488              color: #666;
3489              font-size: 24px;
3490              margin: 30px 0 0 0;
3491              padding: 0;
3492              padding-bottom: 7px;
3493          }
3494          #error-page {
3495              margin-top: 50px;
3496          }
3497          #error-page p,
3498          #error-page .wp-die-message {
3499              font-size: 14px;
3500              line-height: 1.5;
3501              margin: 25px 0 20px;
3502          }
3503          #error-page code {
3504              font-family: Consolas, Monaco, monospace;
3505          }
3506          ul li {
3507              margin-bottom: 10px;
3508              font-size: 14px ;
3509          }
3510          a {
3511              color: #0073aa;
3512          }
3513          a:hover,
3514          a:active {
3515              color: #006799;
3516          }
3517          a:focus {
3518              color: #124964;
3519              -webkit-box-shadow:
3520                  0 0 0 1px #5b9dd9,
3521                  0 0 2px 1px rgba(30, 140, 190, 0.8);
3522              box-shadow:
3523                  0 0 0 1px #5b9dd9,
3524                  0 0 2px 1px rgba(30, 140, 190, 0.8);
3525              outline: none;
3526          }
3527          .button {
3528              background: #f7f7f7;
3529              border: 1px solid #ccc;
3530              color: #555;
3531              display: inline-block;
3532              text-decoration: none;
3533              font-size: 13px;
3534              line-height: 2;
3535              height: 28px;
3536              margin: 0;
3537              padding: 0 10px 1px;
3538              cursor: pointer;
3539              -webkit-border-radius: 3px;
3540              -webkit-appearance: none;
3541              border-radius: 3px;
3542              white-space: nowrap;
3543              -webkit-box-sizing: border-box;
3544              -moz-box-sizing:    border-box;
3545              box-sizing:         border-box;
3546  
3547              -webkit-box-shadow: 0 1px 0 #ccc;
3548              box-shadow: 0 1px 0 #ccc;
3549              vertical-align: top;
3550          }
3551  
3552          .button.button-large {
3553              height: 30px;
3554              line-height: 2.15384615;
3555              padding: 0 12px 2px;
3556          }
3557  
3558          .button:hover,
3559          .button:focus {
3560              background: #fafafa;
3561              border-color: #999;
3562              color: #23282d;
3563          }
3564  
3565          .button:focus {
3566              border-color: #5b9dd9;
3567              -webkit-box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
3568              box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
3569              outline: none;
3570          }
3571  
3572          .button:active {
3573              background: #eee;
3574              border-color: #999;
3575              -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
3576              box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
3577          }
3578  
3579          <?php
3580          if ( 'rtl' === $text_direction ) {
3581              echo 'body { font-family: Tahoma, Arial; }';
3582          }
3583          ?>
3584      </style>
3585  </head>
3586  <body id="error-page">
3587  <?php endif; // ! did_action( 'admin_head' ) ?>
3588      <?php echo $message; ?>
3589  </body>
3590  </html>
3591      <?php
3592      if ( $parsed_args['exit'] ) {
3593          die();
3594      }
3595  }
3596  
3597  /**
3598   * Kills WordPress execution and displays Ajax response with an error message.
3599   *
3600   * This is the handler for wp_die() when processing Ajax requests.
3601   *
3602   * @since 3.4.0
3603   * @access private
3604   *
3605   * @param string       $message Error message.
3606   * @param string       $title   Optional. Error title (unused). Default empty.
3607   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3608   */
3609  function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
3610      // Set default 'response' to 200 for Ajax requests.
3611      $args = wp_parse_args(
3612          $args,
3613          array( 'response' => 200 )
3614      );
3615  
3616      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3617  
3618      if ( ! headers_sent() ) {
3619          // This is intentional. For backward-compatibility, support passing null here.
3620          if ( null !== $args['response'] ) {
3621              status_header( $parsed_args['response'] );
3622          }
3623          nocache_headers();
3624      }
3625  
3626      if ( is_scalar( $message ) ) {
3627          $message = (string) $message;
3628      } else {
3629          $message = '0';
3630      }
3631  
3632      if ( $parsed_args['exit'] ) {
3633          die( $message );
3634      }
3635  
3636      echo $message;
3637  }
3638  
3639  /**
3640   * Kills WordPress execution and displays JSON response with an error message.
3641   *
3642   * This is the handler for wp_die() when processing JSON requests.
3643   *
3644   * @since 5.1.0
3645   * @access private
3646   *
3647   * @param string       $message Error message.
3648   * @param string       $title   Optional. Error title. Default empty.
3649   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3650   */
3651  function _json_wp_die_handler( $message, $title = '', $args = array() ) {
3652      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3653  
3654      $data = array(
3655          'code'              => $parsed_args['code'],
3656          'message'           => $message,
3657          'data'              => array(
3658              'status' => $parsed_args['response'],
3659          ),
3660          'additional_errors' => $parsed_args['additional_errors'],
3661      );
3662  
3663      if ( ! headers_sent() ) {
3664          header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
3665          if ( null !== $parsed_args['response'] ) {
3666              status_header( $parsed_args['response'] );
3667          }
3668          nocache_headers();
3669      }
3670  
3671      echo wp_json_encode( $data );
3672      if ( $parsed_args['exit'] ) {
3673          die();
3674      }
3675  }
3676  
3677  /**
3678   * Kills WordPress execution and displays JSONP response with an error message.
3679   *
3680   * This is the handler for wp_die() when processing JSONP requests.
3681   *
3682   * @since 5.2.0
3683   * @access private
3684   *
3685   * @param string       $message Error message.
3686   * @param string       $title   Optional. Error title. Default empty.
3687   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3688   */
3689  function _jsonp_wp_die_handler( $message, $title = '', $args = array() ) {
3690      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3691  
3692      $data = array(
3693          'code'              => $parsed_args['code'],
3694          'message'           => $message,
3695          'data'              => array(
3696              'status' => $parsed_args['response'],
3697          ),
3698          'additional_errors' => $parsed_args['additional_errors'],
3699      );
3700  
3701      if ( ! headers_sent() ) {
3702          header( "Content-Type: application/javascript; charset={$parsed_args['charset']}" );
3703          header( 'X-Content-Type-Options: nosniff' );
3704          header( 'X-Robots-Tag: noindex' );
3705          if ( null !== $parsed_args['response'] ) {
3706              status_header( $parsed_args['response'] );
3707          }
3708          nocache_headers();
3709      }
3710  
3711      $result         = wp_json_encode( $data );
3712      $jsonp_callback = $_GET['_jsonp'];
3713      echo '/**/' . $jsonp_callback . '(' . $result . ')';
3714      if ( $parsed_args['exit'] ) {
3715          die();
3716      }
3717  }
3718  
3719  /**
3720   * Kills WordPress execution and displays XML response with an error message.
3721   *
3722   * This is the handler for wp_die() when processing XMLRPC requests.
3723   *
3724   * @since 3.2.0
3725   * @access private
3726   *
3727   * @global wp_xmlrpc_server $wp_xmlrpc_server
3728   *
3729   * @param string       $message Error message.
3730   * @param string       $title   Optional. Error title. Default empty.
3731   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3732   */
3733  function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
3734      global $wp_xmlrpc_server;
3735  
3736      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3737  
3738      if ( ! headers_sent() ) {
3739          nocache_headers();
3740      }
3741  
3742      if ( $wp_xmlrpc_server ) {
3743          $error = new IXR_Error( $parsed_args['response'], $message );
3744          $wp_xmlrpc_server->output( $error->getXml() );
3745      }
3746      if ( $parsed_args['exit'] ) {
3747          die();
3748      }
3749  }
3750  
3751  /**
3752   * Kills WordPress execution and displays XML response with an error message.
3753   *
3754   * This is the handler for wp_die() when processing XML requests.
3755   *
3756   * @since 5.2.0
3757   * @access private
3758   *
3759   * @param string       $message Error message.
3760   * @param string       $title   Optional. Error title. Default empty.
3761   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3762   */
3763  function _xml_wp_die_handler( $message, $title = '', $args = array() ) {
3764      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3765  
3766      $message = htmlspecialchars( $message );
3767      $title   = htmlspecialchars( $title );
3768  
3769      $xml = <<<EOD
3770  <error>
3771      <code>{$parsed_args['code']}</code>
3772      <title><![CDATA[{$title}]]></title>
3773      <message><![CDATA[{$message}]]></message>
3774      <data>
3775          <status>{$parsed_args['response']}</status>
3776      </data>
3777  </error>
3778  
3779  EOD;
3780  
3781      if ( ! headers_sent() ) {
3782          header( "Content-Type: text/xml; charset={$parsed_args['charset']}" );
3783          if ( null !== $parsed_args['response'] ) {
3784              status_header( $parsed_args['response'] );
3785          }
3786          nocache_headers();
3787      }
3788  
3789      echo $xml;
3790      if ( $parsed_args['exit'] ) {
3791          die();
3792      }
3793  }
3794  
3795  /**
3796   * Kills WordPress execution and displays an error message.
3797   *
3798   * This is the handler for wp_die() when processing APP requests.
3799   *
3800   * @since 3.4.0
3801   * @since 5.1.0 Added the $title and $args parameters.
3802   * @access private
3803   *
3804   * @param string       $message Optional. Response to print. Default empty.
3805   * @param string       $title   Optional. Error title (unused). Default empty.
3806   * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
3807   */
3808  function _scalar_wp_die_handler( $message = '', $title = '', $args = array() ) {
3809      list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
3810  
3811      if ( $parsed_args['exit'] ) {
3812          if ( is_scalar( $message ) ) {
3813              die( (string) $message );
3814          }
3815          die();
3816      }
3817  
3818      if ( is_scalar( $message ) ) {
3819          echo (string) $message;
3820      }
3821  }
3822  
3823  /**
3824   * Processes arguments passed to wp_die() consistently for its handlers.
3825   *
3826   * @since 5.1.0
3827   * @access private
3828   *
3829   * @param string|WP_Error $message Error message or WP_Error object.
3830   * @param string          $title   Optional. Error title. Default empty.
3831   * @param string|array    $args    Optional. Arguments to control behavior. Default empty array.
3832   * @return array {
3833   *     Processed arguments.
3834   *
3835   *     @type string $0 Error message.
3836   *     @type string $1 Error title.
3837   *     @type array  $2 Arguments to control behavior.
3838   * }
3839   */
3840  function _wp_die_process_input( $message, $title = '', $args = array() ) {
3841      $defaults = array(
3842          'response'          => 0,
3843          'code'              => '',
3844          'exit'              => true,
3845          'back_link'         => false,
3846          'link_url'          => '',
3847          'link_text'         => '',
3848          'text_direction'    => '',
3849          'charset'           => 'utf-8',
3850          'additional_errors' => array(),
3851      );
3852  
3853      $args = wp_parse_args( $args, $defaults );
3854  
3855      if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
3856          if ( ! empty( $message->errors ) ) {
3857              $errors = array();
3858              foreach ( (array) $message->errors as $error_code => $error_messages ) {
3859                  foreach ( (array) $error_messages as $error_message ) {
3860                      $errors[] = array(
3861                          'code'    => $error_code,
3862                          'message' => $error_message,
3863                          'data'    => $message->get_error_data( $error_code ),
3864                      );
3865                  }
3866              }
3867  
3868              $message = $errors[0]['message'];
3869              if ( empty( $args['code'] ) ) {
3870                  $args['code'] = $errors[0]['code'];
3871              }
3872              if ( empty( $args['response'] ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['status'] ) ) {
3873                  $args['response'] = $errors[0]['data']['status'];
3874              }
3875              if ( empty( $title ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['title'] ) ) {
3876                  $title = $errors[0]['data']['title'];
3877              }
3878  
3879              unset( $errors[0] );
3880              $args['additional_errors'] = array_values( $errors );
3881          } else {
3882              $message = '';
3883          }
3884      }
3885  
3886      $have_gettext = function_exists( '__' );
3887  
3888      // The $title and these specific $args must always have a non-empty value.
3889      if ( empty( $args['code'] ) ) {
3890          $args['code'] = 'wp_die';
3891      }
3892      if ( empty( $args['response'] ) ) {
3893          $args['response'] = 500;
3894      }
3895      if ( empty( $title ) ) {
3896          $title = $have_gettext ? __( 'WordPress &rsaquo; Error' ) : 'WordPress &rsaquo; Error';
3897      }
3898      if ( empty( $args['text_direction'] ) || ! in_array( $args['text_direction'], array( 'ltr', 'rtl' ), true ) ) {
3899          $args['text_direction'] = 'ltr';
3900          if ( function_exists( 'is_rtl' ) && is_rtl() ) {
3901              $args['text_direction'] = 'rtl';
3902          }
3903      }
3904  
3905      if ( ! empty( $args['charset'] ) ) {
3906          $args['charset'] = _canonical_charset( $args['charset'] );
3907      }
3908  
3909      return array( $message, $title, $args );
3910  }
3911  
3912  /**
3913   * Encode a variable into JSON, with some sanity checks.
3914   *
3915   * @since 4.1.0
3916   * @since 5.3.0 No longer handles support for PHP < 5.6.
3917   *
3918   * @param mixed $data    Variable (usually an array or object) to encode as JSON.
3919   * @param int   $options Optional. Options to be passed to json_encode(). Default 0.
3920   * @param int   $depth   Optional. Maximum depth to walk through $data. Must be
3921   *                       greater than 0. Default 512.
3922   * @return string|false The JSON encoded string, or false if it cannot be encoded.
3923   */
3924  function wp_json_encode( $data, $options = 0, $depth = 512 ) {
3925      $json = json_encode( $data, $options, $depth );
3926  
3927      // If json_encode() was successful, no need to do more sanity checking.
3928      if ( false !== $json ) {
3929          return $json;
3930      }
3931  
3932      try {
3933          $data = _wp_json_sanity_check( $data, $depth );
3934      } catch ( Exception $e ) {
3935          return false;
3936      }
3937  
3938      return json_encode( $data, $options, $depth );
3939  }
3940  
3941  /**
3942   * Perform sanity checks on data that shall be encoded to JSON.
3943   *
3944   * @ignore
3945   * @since 4.1.0
3946   * @access private
3947   *
3948   * @see wp_json_encode()
3949   *
3950   * @throws Exception If depth limit is reached.
3951   *
3952   * @param mixed $data  Variable (usually an array or object) to encode as JSON.
3953   * @param int   $depth Maximum depth to walk through $data. Must be greater than 0.
3954   * @return mixed The sanitized data that shall be encoded to JSON.
3955   */
3956  function _wp_json_sanity_check( $data, $depth ) {
3957      if ( $depth < 0 ) {
3958          throw new Exception( 'Reached depth limit' );
3959      }
3960  
3961      if ( is_array( $data ) ) {
3962          $output = array();
3963          foreach ( $data as $id => $el ) {
3964              // Don't forget to sanitize the ID!
3965              if ( is_string( $id ) ) {
3966                  $clean_id = _wp_json_convert_string( $id );
3967              } else {
3968                  $clean_id = $id;
3969              }
3970  
3971              // Check the element type, so that we're only recursing if we really have to.
3972              if ( is_array( $el ) || is_object( $el ) ) {
3973                  $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
3974              } elseif ( is_string( $el ) ) {
3975                  $output[ $clean_id ] = _wp_json_convert_string( $el );
3976              } else {
3977                  $output[ $clean_id ] = $el;
3978              }
3979          }
3980      } elseif ( is_object( $data ) ) {
3981          $output = new stdClass;
3982          foreach ( $data as $id => $el ) {
3983              if ( is_string( $id ) ) {
3984                  $clean_id = _wp_json_convert_string( $id );
3985              } else {
3986                  $clean_id = $id;
3987              }
3988  
3989              if ( is_array( $el ) || is_object( $el ) ) {
3990                  $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
3991              } elseif ( is_string( $el ) ) {
3992                  $output->$clean_id = _wp_json_convert_string( $el );
3993              } else {
3994                  $output->$clean_id = $el;
3995              }
3996          }
3997      } elseif ( is_string( $data ) ) {
3998          return _wp_json_convert_string( $data );
3999      } else {
4000          return $data;
4001      }
4002  
4003      return $output;
4004  }
4005  
4006  /**
4007   * Convert a string to UTF-8, so that it can be safely encoded to JSON.
4008   *
4009   * @ignore
4010   * @since 4.1.0
4011   * @access private
4012   *
4013   * @see _wp_json_sanity_check()
4014   *
4015   * @param string $string The string which is to be converted.
4016   * @return string The checked string.
4017   */
4018  function _wp_json_convert_string( $string ) {
4019      static $use_mb = null;
4020      if ( is_null( $use_mb ) ) {
4021          $use_mb = function_exists( 'mb_convert_encoding' );
4022      }
4023  
4024      if ( $use_mb ) {
4025          $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
4026          if ( $encoding ) {
4027              return mb_convert_encoding( $string, 'UTF-8', $encoding );
4028          } else {
4029              return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
4030          }
4031      } else {
4032          return wp_check_invalid_utf8( $string, true );
4033      }
4034  }
4035  
4036  /**
4037   * Prepares response data to be serialized to JSON.
4038   *
4039   * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
4040   *
4041   * @ignore
4042   * @since 4.4.0
4043   * @deprecated 5.3.0 This function is no longer needed as support for PHP 5.2-5.3
4044   *                   has been dropped.
4045   * @access private
4046   *
4047   * @param mixed $data Native representation.
4048   * @return bool|int|float|null|string|array Data ready for `json_encode()`.
4049   */
4050  function _wp_json_prepare_data( $data ) {
4051      _deprecated_function( __FUNCTION__, '5.3.0' );
4052      return $data;
4053  }
4054  
4055  /**
4056   * Send a JSON response back to an Ajax request.
4057   *
4058   * @since 3.5.0
4059   * @since 4.7.0 The `$status_code` parameter was added.
4060   *
4061   * @param mixed $response    Variable (usually an array or object) to encode as JSON,
4062   *                           then print and die.
4063   * @param int   $status_code The HTTP status code to output.
4064   */
4065  function wp_send_json( $response, $status_code = null ) {
4066      if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
4067          _doing_it_wrong(
4068              __FUNCTION__,
4069              sprintf(
4070                  /* translators: 1: WP_REST_Response, 2: WP_Error */
4071                  __( 'Return a %1$s or %2$s object from your callback when using the REST API.' ),
4072                  'WP_REST_Response',
4073                  'WP_Error'
4074              ),
4075              '5.5.0'
4076          );
4077      }
4078  
4079      if ( ! headers_sent() ) {
4080          header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
4081          if ( null !== $status_code ) {
4082              status_header( $status_code );
4083          }
4084      }
4085  
4086      echo wp_json_encode( $response );
4087  
4088      if ( wp_doing_ajax() ) {
4089          wp_die(
4090              '',
4091              '',
4092              array(
4093                  'response' => null,
4094              )
4095          );
4096      } else {
4097          die;
4098      }
4099  }
4100  
4101  /**
4102   * Send a JSON response back to an Ajax request, indicating success.
4103   *
4104   * @since 3.5.0
4105   * @since 4.7.0 The `$status_code` parameter was added.
4106   *
4107   * @param mixed $data        Data to encode as JSON, then print and die.
4108   * @param int   $status_code The HTTP status code to output.
4109   */
4110  function wp_send_json_success( $data = null, $status_code = null ) {
4111      $response = array( 'success' => true );
4112  
4113      if ( isset( $data ) ) {
4114          $response['data'] = $data;
4115      }
4116  
4117      wp_send_json( $response, $status_code );
4118  }
4119  
4120  /**
4121   * Send a JSON response back to an Ajax request, indicating failure.
4122   *
4123   * If the `$data` parameter is a WP_Error object, the errors
4124   * within the object are processed and output as an array of error
4125   * codes and corresponding messages. All other types are output
4126   * without further processing.
4127   *
4128   * @since 3.5.0
4129   * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
4130   * @since 4.7.0 The `$status_code` parameter was added.
4131   *
4132   * @param mixed $data        Data to encode as JSON, then print and die.
4133   * @param int   $status_code The HTTP status code to output.
4134   */
4135  function wp_send_json_error( $data = null, $status_code = null ) {
4136      $response = array( 'success' => false );
4137  
4138      if ( isset( $data ) ) {
4139          if ( is_wp_error( $data ) ) {
4140              $result = array();
4141              foreach ( $data->errors as $code => $messages ) {
4142                  foreach ( $messages as $message ) {
4143                      $result[] = array(
4144                          'code'    => $code,
4145                          'message' => $message,
4146                      );
4147                  }
4148              }
4149  
4150              $response['data'] = $result;
4151          } else {
4152              $response['data'] = $data;
4153          }
4154      }
4155  
4156      wp_send_json( $response, $status_code );
4157  }
4158  
4159  /**
4160   * Checks that a JSONP callback is a valid JavaScript callback name.
4161   *
4162   * Only allows alphanumeric characters and the dot character in callback
4163   * function names. This helps to mitigate XSS attacks caused by directly
4164   * outputting user input.
4165   *
4166   * @since 4.6.0
4167   *
4168   * @param string $callback Supplied JSONP callback function name.
4169   * @return bool Whether the callback function name is valid.
4170   */
4171  function wp_check_jsonp_callback( $callback ) {
4172      if ( ! is_string( $callback ) ) {
4173          return false;
4174      }
4175  
4176      preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
4177  
4178      return 0 === $illegal_char_count;
4179  }
4180  
4181  /**
4182   * Retrieve the WordPress home page URL.
4183   *
4184   * If the constant named 'WP_HOME' exists, then it will be used and returned
4185   * by the function. This can be used to counter the redirection on your local
4186   * development environment.
4187   *
4188   * @since 2.2.0
4189   * @access private
4190   *
4191   * @see WP_HOME
4192   *
4193   * @param string $url URL for the home location.
4194   * @return string Homepage location.
4195   */
4196  function _config_wp_home( $url = '' ) {
4197      if ( defined( 'WP_HOME' ) ) {
4198          return untrailingslashit( WP_HOME );
4199      }
4200      return $url;
4201  }
4202  
4203  /**
4204   * Retrieve the WordPress site URL.
4205   *
4206   * If the constant named 'WP_SITEURL' is defined, then the value in that
4207   * constant will always be returned. This can be used for debugging a site
4208   * on your localhost while not having to change the database to your URL.
4209   *
4210   * @since 2.2.0
4211   * @access private
4212   *
4213   * @see WP_SITEURL
4214   *
4215   * @param string $url URL to set the WordPress site location.
4216   * @return string The WordPress Site URL.
4217   */
4218  function _config_wp_siteurl( $url = '' ) {
4219      if ( defined( 'WP_SITEURL' ) ) {
4220          return untrailingslashit( WP_SITEURL );
4221      }
4222      return $url;
4223  }
4224  
4225  /**
4226   * Delete the fresh site option.
4227   *
4228   * @since 4.7.0
4229   * @access private
4230   */
4231  function _delete_option_fresh_site() {
4232      update_option( 'fresh_site', '0' );
4233  }
4234  
4235  /**
4236   * Set the localized direction for MCE plugin.
4237   *
4238   * Will only set the direction to 'rtl', if the WordPress locale has
4239   * the text direction set to 'rtl'.
4240   *
4241   * Fills in the 'directionality' setting, enables the 'directionality'
4242   * plugin, and adds the 'ltr' button to 'toolbar1', formerly
4243   * 'theme_advanced_buttons1' array keys. These keys are then returned
4244   * in the $mce_init (TinyMCE settings) array.
4245   *
4246   * @since 2.1.0
4247   * @access private
4248   *
4249   * @param array $mce_init MCE settings array.
4250   * @return array Direction set for 'rtl', if needed by locale.
4251   */
4252  function _mce_set_direction( $mce_init ) {
4253      if ( is_rtl() ) {
4254          $mce_init['directionality'] = 'rtl';
4255          $mce_init['rtl_ui']         = true;
4256  
4257          if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
4258              $mce_init['plugins'] .= ',directionality';
4259          }
4260  
4261          if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
4262              $mce_init['toolbar1'] .= ',ltr';
4263          }
4264      }
4265  
4266      return $mce_init;
4267  }
4268  
4269  
4270  /**
4271   * Convert smiley code to the icon graphic file equivalent.
4272   *
4273   * You can turn off smilies, by going to the write setting screen and unchecking
4274   * the box, or by setting 'use_smilies' option to false or removing the option.
4275   *
4276   * Plugins may override the default smiley list by setting the $wpsmiliestrans
4277   * to an array, with the key the code the blogger types in and the value the
4278   * image file.
4279   *
4280   * The $wp_smiliessearch global is for the regular expression and is set each
4281   * time the function is called.
4282   *
4283   * The full list of smilies can be found in the function and won't be listed in
4284   * the description. Probably should create a Codex page for it, so that it is
4285   * available.
4286   *
4287   * @global array $wpsmiliestrans
4288   * @global array $wp_smiliessearch
4289   *
4290   * @since 2.2.0
4291   */
4292  function smilies_init() {
4293      global $wpsmiliestrans, $wp_smiliessearch;
4294  
4295      // Don't bother setting up smilies if they are disabled.
4296      if ( ! get_option( 'use_smilies' ) ) {
4297          return;
4298      }
4299  
4300      if ( ! isset( $wpsmiliestrans ) ) {
4301          $wpsmiliestrans = array(
4302              ':mrgreen:' => 'mrgreen.png',
4303              ':neutral:' => "\xf0\x9f\x98\x90",
4304              ':twisted:' => "\xf0\x9f\x98\x88",
4305              ':arrow:'   => "\xe2\x9e\xa1",
4306              ':shock:'   => "\xf0\x9f\x98\xaf",
4307              ':smile:'   => "\xf0\x9f\x99\x82",
4308              ':???:'     => "\xf0\x9f\x98\x95",
4309              ':cool:'    => "\xf0\x9f\x98\x8e",
4310              ':evil:'    => "\xf0\x9f\x91\xbf",
4311              ':grin:'    => "\xf0\x9f\x98\x80",
4312              ':idea:'    => "\xf0\x9f\x92\xa1",
4313              ':oops:'    => "\xf0\x9f\x98\xb3",
4314              ':razz:'    => "\xf0\x9f\x98\x9b",
4315              ':roll:'    => "\xf0\x9f\x99\x84",
4316              ':wink:'    => "\xf0\x9f\x98\x89",
4317              ':cry:'     => "\xf0\x9f\x98\xa5",
4318              ':eek:'     => "\xf0\x9f\x98\xae",
4319              ':lol:'     => "\xf0\x9f\x98\x86",
4320              ':mad:'     => "\xf0\x9f\x98\xa1",
4321              ':sad:'     => "\xf0\x9f\x99\x81",
4322              '8-)'       => "\xf0\x9f\x98\x8e",
4323              '8-O'       => "\xf0\x9f\x98\xaf",
4324              ':-('       => "\xf0\x9f\x99\x81",
4325              ':-)'       => "\xf0\x9f\x99\x82",
4326              ':-?'       => "\xf0\x9f\x98\x95",
4327              ':-D'       => "\xf0\x9f\x98\x80",
4328              ':-P'       => "\xf0\x9f\x98\x9b",
4329              ':-o'       => "\xf0\x9f\x98\xae",
4330              ':-x'       => "\xf0\x9f\x98\xa1",
4331              ':-|'       => "\xf0\x9f\x98\x90",
4332              ';-)'       => "\xf0\x9f\x98\x89",
4333              // This one transformation breaks regular text with frequency.
4334              //     '8)' => "\xf0\x9f\x98\x8e",
4335              '8O'        => "\xf0\x9f\x98\xaf",
4336              ':('        => "\xf0\x9f\x99\x81",
4337              ':)'        => "\xf0\x9f\x99\x82",
4338              ':?'        => "\xf0\x9f\x98\x95",
4339              ':D'        => "\xf0\x9f\x98\x80",
4340              ':P'        => "\xf0\x9f\x98\x9b",
4341              ':o'        => "\xf0\x9f\x98\xae",
4342              ':x'        => "\xf0\x9f\x98\xa1",
4343              ':|'        => "\xf0\x9f\x98\x90",
4344              ';)'        => "\xf0\x9f\x98\x89",
4345              ':!:'       => "\xe2\x9d\x97",
4346              ':?:'       => "\xe2\x9d\x93",
4347          );
4348      }
4349  
4350      /**
4351       * Filters all the smilies.
4352       *
4353       * This filter must be added before `smilies_init` is run, as
4354       * it is normally only run once to setup the smilies regex.
4355       *
4356       * @since 4.7.0
4357       *
4358       * @param string[] $wpsmiliestrans List of the smilies' hexadecimal representations, keyed by their smily code.
4359       */
4360      $wpsmiliestrans = apply_filters( 'smilies', $wpsmiliestrans );
4361  
4362      if ( count( $wpsmiliestrans ) == 0 ) {
4363          return;
4364      }
4365  
4366      /*
4367       * NOTE: we sort the smilies in reverse key order. This is to make sure
4368       * we match the longest possible smilie (:???: vs :?) as the regular
4369       * expression used below is first-match
4370       */
4371      krsort( $wpsmiliestrans );
4372  
4373      $spaces = wp_spaces_regexp();
4374  
4375      // Begin first "subpattern".
4376      $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
4377  
4378      $subchar = '';
4379      foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
4380          $firstchar = substr( $smiley, 0, 1 );
4381          $rest      = substr( $smiley, 1 );
4382  
4383          // New subpattern?
4384          if ( $firstchar != $subchar ) {
4385              if ( '' !== $subchar ) {
4386                  $wp_smiliessearch .= ')(?=' . $spaces . '|$)';  // End previous "subpattern".
4387                  $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern".
4388              }
4389              $subchar           = $firstchar;
4390              $wp_smiliessearch .= preg_quote( $firstchar, '/' ) . '(?:';
4391          } else {
4392              $wp_smiliessearch .= '|';
4393          }
4394          $wp_smiliessearch .= preg_quote( $rest, '/' );
4395      }
4396  
4397      $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
4398  
4399  }
4400  
4401  /**
4402   * Merge user defined arguments into defaults array.
4403   *
4404   * This function is used throughout WordPress to allow for both string or array
4405   * to be merged into another array.
4406   *
4407   * @since 2.2.0
4408   * @since 2.3.0 `$args` can now also be an object.
4409   *
4410   * @param string|array|object $args     Value to merge with $defaults.
4411   * @param array               $defaults Optional. Array that serves as the defaults.
4412   *                                      Default empty array.
4413   * @return array Merged user defined values with defaults.
4414   */
4415  function wp_parse_args( $args, $defaults = array() ) {
4416      if ( is_object( $args ) ) {
4417          $parsed_args = get_object_vars( $args );
4418      } elseif ( is_array( $args ) ) {
4419          $parsed_args =& $args;
4420      } else {
4421          wp_parse_str( $args, $parsed_args );
4422      }
4423  
4424      if ( is_array( $defaults ) && $defaults ) {
4425          return array_merge( $defaults, $parsed_args );
4426      }
4427      return $parsed_args;
4428  }
4429  
4430  /**
4431   * Cleans up an array, comma- or space-separated list of scalar values.
4432   *
4433   * @since 5.1.0
4434   *
4435   * @param array|string $list List of values.
4436   * @return array Sanitized array of values.
4437   */
4438  function wp_parse_list( $list ) {
4439      if ( ! is_array( $list ) ) {
4440          return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
4441      }
4442  
4443      return $list;
4444  }
4445  
4446  /**
4447   * Clean up an array, comma- or space-separated list of IDs.
4448   *
4449   * @since 3.0.0
4450   *
4451   * @param array|string $list List of IDs.
4452   * @return int[] Sanitized array of IDs.
4453   */
4454  function wp_parse_id_list( $list ) {
4455      $list = wp_parse_list( $list );
4456  
4457      return array_unique( array_map( 'absint', $list ) );
4458  }
4459  
4460  /**
4461   * Clean up an array, comma- or space-separated list of slugs.
4462   *
4463   * @since 4.7.0
4464   *
4465   * @param array|string $list List of slugs.
4466   * @return string[] Sanitized array of slugs.
4467   */
4468  function wp_parse_slug_list( $list ) {
4469      $list = wp_parse_list( $list );
4470  
4471      return array_unique( array_map( 'sanitize_title', $list ) );
4472  }
4473  
4474  /**
4475   * Extract a slice of an array, given a list of keys.
4476   *
4477   * @since 3.1.0
4478   *
4479   * @param array $array The original array.
4480   * @param array $keys  The list of keys.
4481   * @return array The array slice.
4482   */
4483  function wp_array_slice_assoc( $array, $keys ) {
4484      $slice = array();
4485      foreach ( $keys as $key ) {
4486          if ( isset( $array[ $key ] ) ) {
4487              $slice[ $key ] = $array[ $key ];
4488          }
4489      }
4490  
4491      return $slice;
4492  }
4493  
4494  /**
4495   * Determines if the variable is a numeric-indexed array.
4496   *
4497   * @since 4.4.0
4498   *
4499   * @param mixed $data Variable to check.
4500   * @return bool Whether the variable is a list.
4501   */
4502  function wp_is_numeric_array( $data ) {
4503      if ( ! is_array( $data ) ) {
4504          return false;
4505      }
4506  
4507      $keys        = array_keys( $data );
4508      $string_keys = array_filter( $keys, 'is_string' );
4509      return count( $string_keys ) === 0;
4510  }
4511  
4512  /**
4513   * Filters a list of objects, based on a set of key => value arguments.
4514   *
4515   * @since 3.0.0
4516   * @since 4.7.0 Uses `WP_List_Util` class.
4517   *
4518   * @param array       $list     An array of objects to filter
4519   * @param array       $args     Optional. An array of key => value arguments to match
4520   *                              against each object. Default empty array.
4521   * @param string      $operator Optional. The logical operation to perform. 'or' means
4522   *                              only one element from the array needs to match; 'and'
4523   *                              means all elements must match; 'not' means no elements may
4524   *                              match. Default 'and'.
4525   * @param bool|string $field    A field from the object to place instead of the entire object.
4526   *                              Default false.
4527   * @return array A list of objects or object fields.
4528   */
4529  function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
4530      if ( ! is_array( $list ) ) {
4531          return array();
4532      }
4533  
4534      $util = new WP_List_Util( $list );
4535  
4536      $util->filter( $args, $operator );
4537  
4538      if ( $field ) {
4539          $util->pluck( $field );
4540      }
4541  
4542      return $util->get_output();
4543  }
4544  
4545  /**
4546   * Filters a list of objects, based on a set of key => value arguments.
4547   *
4548   * @since 3.1.0
4549   * @since 4.7.0 Uses `WP_List_Util` class.
4550   *
4551   * @param array  $list     An array of objects to filter.
4552   * @param array  $args     Optional. An array of key => value arguments to match
4553   *                         against each object. Default empty array.
4554   * @param string $operator Optional. The logical operation to perform. 'AND' means
4555   *                         all elements from the array must match. 'OR' means only
4556   *                         one element needs to match. 'NOT' means no elements may
4557   *                         match. Default 'AND'.
4558   * @return array Array of found values.
4559   */
4560  function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
4561      if ( ! is_array( $list ) ) {
4562          return array();
4563      }
4564  
4565      $util = new WP_List_Util( $list );
4566      return $util->filter( $args, $operator );
4567  }
4568  
4569  /**
4570   * Pluck a certain field out of each object in a list.
4571   *
4572   * This has the same functionality and prototype of
4573   * array_column() (PHP 5.5) but also supports objects.
4574   *
4575   * @since 3.1.0
4576   * @since 4.0.0 $index_key parameter added.
4577   * @since 4.7.0 Uses `WP_List_Util` class.
4578   *
4579   * @param array      $list      List of objects or arrays
4580   * @param int|string $field     Field from the object to place instead of the entire object
4581   * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
4582   *                              Default null.
4583   * @return array Array of found values. If `$index_key` is set, an array of found values with keys
4584   *               corresponding to `$index_key`. If `$index_key` is null, array keys from the original
4585   *               `$list` will be preserved in the results.
4586   */
4587  function wp_list_pluck( $list, $field, $index_key = null ) {
4588      $util = new WP_List_Util( $list );
4589      return $util->pluck( $field, $index_key );
4590  }
4591  
4592  /**
4593   * Sorts a list of objects, based on one or more orderby arguments.
4594   *
4595   * @since 4.7.0
4596   *
4597   * @param array        $list          An array of objects to sort.
4598   * @param string|array $orderby       Optional. Either the field name to order by or an array
4599   *                                    of multiple orderby fields as $orderby => $order.
4600   * @param string       $order         Optional. Either 'ASC' or 'DESC'. Only used if $orderby
4601   *                                    is a string.
4602   * @param bool         $preserve_keys Optional. Whether to preserve keys. Default false.
4603   * @return array The sorted array.
4604   */
4605  function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
4606      if ( ! is_array( $list ) ) {
4607          return array();
4608      }
4609  
4610      $util = new WP_List_Util( $list );
4611      return $util->sort( $orderby, $order, $preserve_keys );
4612  }
4613  
4614  /**
4615   * Determines if Widgets library should be loaded.
4616   *
4617   * Checks to make sure that the widgets library hasn't already been loaded.
4618   * If it hasn't, then it will load the widgets library and run an action hook.
4619   *
4620   * @since 2.2.0
4621   */
4622  function wp_maybe_load_widgets() {
4623      /**
4624       * Filters whether to load the Widgets library.
4625       *
4626       * Returning a falsey value from the filter will effectively short-circuit
4627       * the Widgets library from loading.
4628       *
4629       * @since 2.8.0
4630       *
4631       * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
4632       *                                    Default true.
4633       */
4634      if ( ! apply_filters( 'load_default_widgets', true ) ) {
4635          return;
4636      }
4637  
4638      require_once  ABSPATH . WPINC . '/default-widgets.php';
4639  
4640      add_action( '_admin_menu', 'wp_widgets_add_menu' );
4641  }
4642  
4643  /**
4644   * Append the Widgets menu to the themes main menu.
4645   *
4646   * @since 2.2.0
4647   *
4648   * @global array $submenu
4649   */
4650  function wp_widgets_add_menu() {
4651      global $submenu;
4652  
4653      if ( ! current_theme_supports( 'widgets' ) ) {
4654          return;
4655      }
4656  
4657      $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
4658      ksort( $submenu['themes.php'], SORT_NUMERIC );
4659  }
4660  
4661  /**
4662   * Flush all output buffers for PHP 5.2.
4663   *
4664   * Make sure all output buffers are flushed before our singletons are destroyed.
4665   *
4666   * @since 2.2.0
4667   */
4668  function wp_ob_end_flush_all() {
4669      $levels = ob_get_level();
4670      for ( $i = 0; $i < $levels; $i++ ) {
4671          ob_end_flush();
4672      }
4673  }
4674  
4675  /**
4676   * Load custom DB error or display WordPress DB error.
4677   *
4678   * If a file exists in the wp-content directory named db-error.php, then it will
4679   * be loaded instead of displaying the WordPress DB error. If it is not found,
4680   * then the WordPress DB error will be displayed instead.
4681   *
4682   * The WordPress DB error sets the HTTP status header to 500 to try to prevent
4683   * search engines from caching the message. Custom DB messages should do the
4684   * same.
4685   *
4686   * This function was backported to WordPress 2.3.2, but originally was added
4687   * in WordPress 2.5.0.
4688   *
4689   * @since 2.3.2
4690   *
4691   * @global wpdb $wpdb WordPress database abstraction object.
4692   */
4693  function dead_db() {
4694      global $wpdb;
4695  
4696      wp_load_translations_early();
4697  
4698      // Load custom DB error template, if present.
4699      if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
4700          require_once WP_CONTENT_DIR . '/db-error.php';
4701          die();
4702      }
4703  
4704      // If installing or in the admin, provide the verbose message.
4705      if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
4706          wp_die( $wpdb->error );
4707      }
4708  
4709      // Otherwise, be terse.
4710      wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) );
4711  }
4712  
4713  /**
4714   * Convert a value to non-negative integer.
4715   *
4716   * @since 2.5.0
4717   *
4718   * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
4719   * @return int A non-negative integer.
4720   */
4721  function absint( $maybeint ) {
4722      return abs( intval( $maybeint ) );
4723  }
4724  
4725  /**
4726   * Mark a function as deprecated and inform when it has been used.
4727   *
4728   * There is a {@see 'hook deprecated_function_run'} that will be called that can be used
4729   * to get the backtrace up to what file and function called the deprecated
4730   * function.
4731   *
4732   * The current behavior is to trigger a user error if `WP_DEBUG` is true.
4733   *
4734   * This function is to be used in every function that is deprecated.
4735   *
4736   * @since 2.5.0
4737   * @since 5.4.0 This function is no longer marked as "private".
4738   * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
4739   *
4740   * @param string $function    The function that was called.
4741   * @param string $version     The version of WordPress that deprecated the function.
4742   * @param string $replacement Optional. The function that should have been called. Default empty.
4743   */
4744  function _deprecated_function( $function, $version, $replacement = '' ) {
4745  
4746      /**
4747       * Fires when a deprecated function is called.
4748       *
4749       * @since 2.5.0
4750       *
4751       * @param string $function    The function that was called.
4752       * @param string $replacement The function that should have been called.
4753       * @param string $version     The version of WordPress that deprecated the function.
4754       */
4755      do_action( 'deprecated_function_run', $function, $replacement, $version );
4756  
4757      /**
4758       * Filters whether to trigger an error for deprecated functions.
4759       *
4760       * @since 2.5.0
4761       *
4762       * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
4763       */
4764      if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
4765          if ( function_exists( '__' ) ) {
4766              if ( $replacement ) {
4767                  trigger_error(
4768                      sprintf(
4769                          /* translators: 1: PHP function name, 2: Version number, 3: Alternative function name. */
4770                          __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
4771                          $function,
4772                          $version,
4773                          $replacement
4774                      ),
4775                      E_USER_DEPRECATED
4776                  );
4777              } else {
4778                  trigger_error(
4779                      sprintf(
4780                          /* translators: 1: PHP function name, 2: Version number. */
4781                          __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
4782                          $function,
4783                          $version
4784                      ),
4785                      E_USER_DEPRECATED
4786                  );
4787              }
4788          } else {
4789              if ( $replacement ) {
4790                  trigger_error(
4791                      sprintf(
4792                          '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
4793                          $function,
4794                          $version,
4795                          $replacement
4796                      ),
4797                      E_USER_DEPRECATED
4798                  );
4799              } else {
4800                  trigger_error(
4801                      sprintf(
4802                          '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
4803                          $function,
4804                          $version
4805                      ),
4806                      E_USER_DEPRECATED
4807                  );
4808              }
4809          }
4810      }
4811  }
4812  
4813  /**
4814   * Marks a constructor as deprecated and informs when it has been used.
4815   *
4816   * Similar to _deprecated_function(), but with different strings. Used to
4817   * remove PHP4 style constructors.
4818   *
4819   * The current behavior is to trigger a user error if `WP_DEBUG` is true.
4820   *
4821   * This function is to be used in every PHP4 style constructor method that is deprecated.
4822   *
4823   * @since 4.3.0
4824   * @since 4.5.0 Added the `$parent_class` parameter.
4825   * @since 5.4.0 This function is no longer marked as "private".
4826   * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
4827   *
4828   * @param string $class        The class containing the deprecated constructor.
4829   * @param string $version      The version of WordPress that deprecated the function.
4830   * @param string $parent_class Optional. The parent class calling the deprecated constructor.
4831   *                             Default empty string.
4832   */
4833  function _deprecated_constructor( $class, $version, $parent_class = '' ) {
4834  
4835      /**
4836       * Fires when a deprecated constructor is called.
4837       *
4838       * @since 4.3.0
4839       * @since 4.5.0 Added the `$parent_class` parameter.
4840       *
4841       * @param string $class        The class containing the deprecated constructor.
4842       * @param string $version      The version of WordPress that deprecated the function.
4843       * @param string $parent_class The parent class calling the deprecated constructor.
4844       */
4845      do_action( 'deprecated_constructor_run', $class, $version, $parent_class );
4846  
4847      /**
4848       * Filters whether to trigger an error for deprecated functions.
4849       *
4850       * `WP_DEBUG` must be true in addition to the filter evaluating to true.
4851       *
4852       * @since 4.3.0
4853       *
4854       * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
4855       */
4856      if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
4857          if ( function_exists( '__' ) ) {
4858              if ( $parent_class ) {
4859                  trigger_error(
4860                      sprintf(
4861                          /* translators: 1: PHP class name, 2: PHP parent class name, 3: Version number, 4: __construct() method. */
4862                          __( 'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.' ),
4863                          $class,
4864                          $parent_class,
4865                          $version,
4866                          '<code>__construct()</code>'
4867                      ),
4868                      E_USER_DEPRECATED
4869                  );
4870              } else {
4871                  trigger_error(
4872                      sprintf(
4873                          /* translators: 1: PHP class name, 2: Version number, 3: __construct() method. */
4874                          __( 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
4875                          $class,
4876                          $version,
4877                          '<code>__construct()</code>'
4878                      ),
4879                      E_USER_DEPRECATED
4880                  );
4881              }
4882          } else {
4883              if ( $parent_class ) {
4884                  trigger_error(
4885                      sprintf(
4886                          'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.',
4887                          $class,
4888                          $parent_class,
4889                          $version,
4890                          '<code>__construct()</code>'
4891                      ),
4892                      E_USER_DEPRECATED
4893                  );
4894              } else {
4895                  trigger_error(
4896                      sprintf(
4897                          'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
4898                          $class,
4899                          $version,
4900                          '<code>__construct()</code>'
4901                      ),
4902                      E_USER_DEPRECATED
4903                  );
4904              }
4905          }
4906      }
4907  
4908  }
4909  
4910  /**
4911   * Mark a file as deprecated and inform when it has been used.
4912   *
4913   * There is a hook {@see 'deprecated_file_included'} that will be called that can be used
4914   * to get the backtrace up to what file and function included the deprecated
4915   * file.
4916   *
4917   * The current behavior is to trigger a user error if `WP_DEBUG` is true.
4918   *
4919   * This function is to be used in every file that is deprecated.
4920   *
4921   * @since 2.5.0
4922   * @since 5.4.0 This function is no longer marked as "private".
4923   * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
4924   *
4925   * @param string $file        The file that was included.
4926   * @param string $version     The version of WordPress that deprecated the file.
4927   * @param string $replacement Optional. The file that should have been included based on ABSPATH.
4928   *                            Default empty.
4929   * @param string $message     Optional. A message regarding the change. Default empty.
4930   */
4931  function _deprecated_file( $file, $version, $replacement = '', $message = '' ) {
4932  
4933      /**
4934       * Fires when a deprecated file is called.
4935       *
4936       * @since 2.5.0
4937       *
4938       * @param string $file        The file that was called.
4939       * @param string $replacement The file that should have been included based on ABSPATH.
4940       * @param string $version     The version of WordPress that deprecated the file.
4941       * @param string $message     A message regarding the change.
4942       */
4943      do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
4944  
4945      /**
4946       * Filters whether to trigger an error for deprecated files.
4947       *
4948       * @since 2.5.0
4949       *
4950       * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
4951       */
4952      if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
4953          $message = empty( $message ) ? '' : ' ' . $message;
4954  
4955          if ( function_exists( '__' ) ) {
4956              if ( $replacement ) {
4957                  trigger_error(
4958                      sprintf(
4959                          /* translators: 1: PHP file name, 2: Version number, 3: Alternative file name. */
4960                          __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
4961                          $file,
4962                          $version,
4963                          $replacement
4964                      ) . $message,
4965                      E_USER_DEPRECATED
4966                  );
4967              } else {
4968                  trigger_error(
4969                      sprintf(
4970                          /* translators: 1: PHP file name, 2: Version number. */
4971                          __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
4972                          $file,
4973                          $version
4974                      ) . $message,
4975                      E_USER_DEPRECATED
4976                  );
4977              }
4978          } else {
4979              if ( $replacement ) {
4980                  trigger_error(
4981                      sprintf(
4982                          '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
4983                          $file,
4984                          $version,
4985                          $replacement
4986                      ) . $message,
4987                      E_USER_DEPRECATED
4988                  );
4989              } else {
4990                  trigger_error(
4991                      sprintf(
4992                          '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
4993                          $file,
4994                          $version
4995                      ) . $message,
4996                      E_USER_DEPRECATED
4997                  );
4998              }
4999          }
5000      }
5001  }
5002  /**
5003   * Mark a function argument as deprecated and inform when it has been used.
5004   *
5005   * This function is to be used whenever a deprecated function argument is used.
5006   * Before this function is called, the argument must be checked for whether it was
5007   * used by comparing it to its default value or evaluating whether it is empty.
5008   * For example:
5009   *
5010   *     if ( ! empty( $deprecated ) ) {
5011   *         _deprecated_argument( __FUNCTION__, '3.0.0' );
5012   *     }
5013   *
5014   * There is a hook deprecated_argument_run that will be called that can be used
5015   * to get the backtrace up to what file and function used the deprecated
5016   * argument.
5017   *
5018   * The current behavior is to trigger a user error if WP_DEBUG is true.
5019   *
5020   * @since 3.0.0
5021   * @since 5.4.0 This function is no longer marked as "private".
5022   * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
5023   *
5024   * @param string $function The function that was called.
5025   * @param string $version  The version of WordPress that deprecated the argument used.
5026   * @param string $message  Optional. A message regarding the change. Default empty.
5027   */
5028  function _deprecated_argument( $function, $version, $message = '' ) {
5029  
5030      /**
5031       * Fires when a deprecated argument is called.
5032       *
5033       * @since 3.0.0
5034       *
5035       * @param string $function The function that was called.
5036       * @param string $message  A message regarding the change.
5037       * @param string $version  The version of WordPress that deprecated the argument used.
5038       */
5039      do_action( 'deprecated_argument_run', $function, $message, $version );
5040  
5041      /**
5042       * Filters whether to trigger an error for deprecated arguments.
5043       *
5044       * @since 3.0.0
5045       *
5046       * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
5047       */
5048      if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
5049          if ( function_exists( '__' ) ) {
5050              if ( $message ) {
5051                  trigger_error(
5052                      sprintf(
5053                          /* translators: 1: PHP function name, 2: Version number, 3: Optional message regarding the change. */
5054                          __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s' ),
5055                          $function,
5056                          $version,
5057                          $message
5058                      ),
5059                      E_USER_DEPRECATED
5060                  );
5061              } else {
5062                  trigger_error(
5063                      sprintf(
5064                          /* translators: 1: PHP function name, 2: Version number. */
5065                          __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
5066                          $function,
5067                          $version
5068                      ),
5069                      E_USER_DEPRECATED
5070                  );
5071              }
5072          } else {
5073              if ( $message ) {
5074                  trigger_error(
5075                      sprintf(
5076                          '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s',
5077                          $function,
5078                          $version,
5079                          $message
5080                      ),
5081                      E_USER_DEPRECATED
5082                  );
5083              } else {
5084                  trigger_error(
5085                      sprintf(
5086                          '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.',
5087                          $function,
5088                          $version
5089                      ),
5090                      E_USER_DEPRECATED
5091                  );
5092              }
5093          }
5094      }
5095  }
5096  
5097  /**
5098   * Marks a deprecated action or filter hook as deprecated and throws a notice.
5099   *
5100   * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where
5101   * the deprecated hook was called.
5102   *
5103   * Default behavior is to trigger a user error if `WP_DEBUG` is true.
5104   *
5105   * This function is called by the do_action_deprecated() and apply_filters_deprecated()
5106   * functions, and so generally does not need to be called directly.
5107   *
5108   * @since 4.6.0
5109   * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
5110   * @access private
5111   *
5112   * @param string $hook        The hook that was used.
5113   * @param string $version     The version of WordPress that deprecated the hook.
5114   * @param string $replacement Optional. The hook that should have been used. Default empty.
5115   * @param string $message     Optional. A message regarding the change. Default empty.
5116   */
5117  function _deprecated_hook( $hook, $version, $replacement = '', $message = '' ) {
5118      /**
5119       * Fires when a deprecated hook is called.
5120       *
5121       * @since 4.6.0
5122       *
5123       * @param string $hook        The hook that was called.
5124       * @param string $replacement The hook that should be used as a replacement.
5125       * @param string $version     The version of WordPress that deprecated the argument used.
5126       * @param string $message     A message regarding the change.
5127       */
5128      do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
5129  
5130      /**
5131       * Filters whether to trigger deprecated hook errors.
5132       *
5133       * @since 4.6.0
5134       *
5135       * @param bool $trigger Whether to trigger deprecated hook errors. Requires
5136       *                      `WP_DEBUG` to be defined true.
5137       */
5138      if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
5139          $message = empty( $message ) ? '' : ' ' . $message;
5140  
5141          if ( $replacement ) {
5142              trigger_error(
5143                  sprintf(
5144                      /* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
5145                      __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
5146                      $hook,
5147                      $version,
5148                      $replacement
5149                  ) . $message,
5150                  E_USER_DEPRECATED
5151              );
5152          } else {
5153              trigger_error(
5154                  sprintf(
5155                      /* translators: 1: WordPress hook name, 2: Version number. */
5156                      __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
5157                      $hook,
5158                      $version
5159                  ) . $message,
5160                  E_USER_DEPRECATED
5161              );
5162          }
5163      }
5164  }
5165  
5166  /**
5167   * Mark something as being incorrectly called.
5168   *
5169   * There is a hook {@see 'doing_it_wrong_run'} that will be called that can be used
5170   * to get the backtrace up to what file and function called the deprecated
5171   * function.
5172   *
5173   * The current behavior is to trigger a user error if `WP_DEBUG` is true.
5174   *
5175   * @since 3.1.0
5176   * @since 5.4.0 This function is no longer marked as "private".
5177   *
5178   * @param string $function The function that was called.
5179   * @param string $message  A message explaining what has been done incorrectly.
5180   * @param string $version  The version of WordPress where the message was added.
5181   */
5182  function _doing_it_wrong( $function, $message, $version ) {
5183  
5184      /**
5185       * Fires when the given function is being used incorrectly.
5186       *
5187       * @since 3.1.0
5188       *
5189       * @param string $function The function that was called.
5190       * @param string $message  A message explaining what has been done incorrectly.
5191       * @param string $version  The version of WordPress where the message was added.
5192       */
5193      do_action( 'doing_it_wrong_run', $function, $message, $version );
5194  
5195      /**
5196       * Filters whether to trigger an error for _doing_it_wrong() calls.
5197       *
5198       * @since 3.1.0
5199       * @since 5.1.0 Added the $function, $message and $version parameters.
5200       *
5201       * @param bool   $trigger  Whether to trigger the error for _doing_it_wrong() calls. Default true.
5202       * @param string $function The function that was called.
5203       * @param string $message  A message explaining what has been done incorrectly.
5204       * @param string $version  The version of WordPress where the message was added.
5205       */
5206      if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true, $function, $message, $version ) ) {
5207          if ( function_exists( '__' ) ) {
5208              if ( $version ) {
5209                  /* translators: %s: Version number. */
5210                  $version = sprintf( __( '(This message was added in version %s.)' ), $version );
5211              }
5212  
5213              $message .= ' ' . sprintf(
5214                  /* translators: %s: Documentation URL. */
5215                  __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ),
5216                  __( 'https://wordpress.org/support/article/debugging-in-wordpress/' )
5217              );
5218  
5219              trigger_error(
5220                  sprintf(
5221                      /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: WordPress version number. */
5222                      __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
5223                      $function,
5224                      $message,
5225                      $version
5226                  ),
5227                  E_USER_NOTICE
5228              );
5229          } else {
5230              if ( $version ) {
5231                  $version = sprintf( '(This message was added in version %s.)', $version );
5232              }
5233  
5234              $message .= sprintf(
5235                  ' Please see <a href="%s">Debugging in WordPress</a> for more information.',
5236                  'https://wordpress.org/support/article/debugging-in-wordpress/'
5237              );
5238  
5239              trigger_error(
5240                  sprintf(
5241                      '%1$s was called <strong>incorrectly</strong>. %2$s %3$s',
5242                      $function,
5243                      $message,
5244                      $version
5245                  ),
5246                  E_USER_NOTICE
5247              );
5248          }
5249      }
5250  }
5251  
5252  /**
5253   * Is the server running earlier than 1.5.0 version of lighttpd?
5254   *
5255   * @since 2.5.0
5256   *
5257   * @return bool Whether the server is running lighttpd < 1.5.0.
5258   */
5259  function is_lighttpd_before_150() {
5260      $server_parts    = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : '' );
5261      $server_parts[1] = isset( $server_parts[1] ) ? $server_parts[1] : '';
5262  
5263      return ( 'lighttpd' === $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' ) );
5264  }
5265  
5266  /**
5267   * Does the specified module exist in the Apache config?
5268   *
5269   * @since 2.5.0
5270   *
5271   * @global bool $is_apache
5272   *
5273   * @param string $mod     The module, e.g. mod_rewrite.
5274   * @param bool   $default Optional. The default return value if the module is not found. Default false.
5275   * @return bool Whether the specified module is loaded.
5276   */
5277  function apache_mod_loaded( $mod, $default = false ) {
5278      global $is_apache;
5279  
5280      if ( ! $is_apache ) {
5281          return false;
5282      }
5283  
5284      if ( function_exists( 'apache_get_modules' ) ) {
5285          $mods = apache_get_modules();
5286          if ( in_array( $mod, $mods, true ) ) {
5287              return true;
5288          }
5289      } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
5290              ob_start();
5291              phpinfo( 8 );
5292              $phpinfo = ob_get_clean();
5293          if ( false !== strpos( $phpinfo, $mod ) ) {
5294              return true;
5295          }
5296      }
5297  
5298      return $default;
5299  }
5300  
5301  /**
5302   * Check if IIS 7+ supports pretty permalinks.
5303   *
5304   * @since 2.8.0
5305   *
5306   * @global bool $is_iis7
5307   *
5308   * @return bool Whether IIS7 supports permalinks.
5309   */
5310  function iis7_supports_permalinks() {
5311      global $is_iis7;
5312  
5313      $supports_permalinks = false;
5314      if ( $is_iis7 ) {
5315          /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
5316           * easily update the xml configuration file, hence we just bail out and tell user that
5317           * pretty permalinks cannot be used.
5318           *
5319           * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
5320           * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
5321           * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
5322           * via ISAPI then pretty permalinks will not work.
5323           */
5324          $supports_permalinks = class_exists( 'DOMDocument', false ) && isset( $_SERVER['IIS_UrlRewriteModule'] ) && ( 'cgi-fcgi' === PHP_SAPI );
5325      }
5326  
5327      /**
5328       * Filters whether IIS 7+ supports pretty permalinks.
5329       *
5330       * @since 2.8.0
5331       *
5332       * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
5333       */
5334      return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
5335  }
5336  
5337  /**
5338   * Validates a file name and path against an allowed set of rules.
5339   *
5340   * A return value of `1` means the file path contains directory traversal.
5341   *
5342   * A return value of `2` means the file path contains a Windows drive path.
5343   *
5344   * A return value of `3` means the file is not in the allowed files list.
5345   *
5346   * @since 1.2.0
5347   *
5348   * @param string   $file          File path.
5349   * @param string[] $allowed_files Optional. Array of allowed files.
5350   * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
5351   */
5352  function validate_file( $file, $allowed_files = array() ) {
5353      // `../` on its own is not allowed:
5354      if ( '../' === $file ) {
5355          return 1;
5356      }
5357  
5358      // More than one occurence of `../` is not allowed:
5359      if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
5360          return 1;
5361      }
5362  
5363      // `../` which does not occur at the end of the path is not allowed:
5364      if ( false !== strpos( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
5365          return 1;
5366      }
5367  
5368      // Files not in the allowed file list are not allowed:
5369      if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files, true ) ) {
5370          return 3;
5371      }
5372  
5373      // Absolute Windows drive paths are not allowed:
5374      if ( ':' === substr( $file, 1, 1 ) ) {
5375          return 2;
5376      }
5377  
5378      return 0;
5379  }
5380  
5381  /**
5382   * Whether to force SSL used for the Administration Screens.
5383   *
5384   * @since 2.6.0
5385   *
5386   * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
5387   * @return bool True if forced, false if not forced.
5388   */
5389  function force_ssl_admin( $force = null ) {
5390      static $forced = false;
5391  
5392      if ( ! is_null( $force ) ) {
5393          $old_forced = $forced;
5394          $forced     = $force;
5395          return $old_forced;
5396      }
5397  
5398      return $forced;
5399  }
5400  
5401  /**
5402   * Guess the URL for the site.
5403   *
5404   * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
5405   * directory.
5406   *
5407   * @since 2.6.0
5408   *
5409   * @return string The guessed URL.
5410   */
5411  function wp_guess_url() {
5412      if ( defined( 'WP_SITEURL' ) && '' !== WP_SITEURL ) {
5413          $url = WP_SITEURL;
5414      } else {
5415          $abspath_fix         = str_replace( '\\', '/', ABSPATH );
5416          $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
5417  
5418          // The request is for the admin.
5419          if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
5420              $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
5421  
5422              // The request is for a file in ABSPATH.
5423          } elseif ( $script_filename_dir . '/' === $abspath_fix ) {
5424              // Strip off any file/query params in the path.
5425              $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
5426  
5427          } else {
5428              if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
5429                  // Request is hitting a file inside ABSPATH.
5430                  $directory = str_replace( ABSPATH, '', $script_filename_dir );
5431                  // Strip off the subdirectory, and any file/query params.
5432                  $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '', $_SERVER['REQUEST_URI'] );
5433              } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
5434                  // Request is hitting a file above ABSPATH.
5435                  $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
5436                  // Strip off any file/query params from the path, appending the subdirectory to the installation.
5437                  $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ) . $subdirectory;
5438              } else {
5439                  $path = $_SERVER['REQUEST_URI'];
5440              }
5441          }
5442  
5443          $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet.
5444          $url    = $schema . $_SERVER['HTTP_HOST'] . $path;
5445      }
5446  
5447      return rtrim( $url, '/' );
5448  }
5449  
5450  /**
5451   * Temporarily suspend cache additions.
5452   *
5453   * Stops more data being added to the cache, but still allows cache retrieval.
5454   * This is useful for actions, such as imports, when a lot of data would otherwise
5455   * be almost uselessly added to the cache.
5456   *
5457   * Suspension lasts for a single page load at most. Remember to call this
5458   * function again if you wish to re-enable cache adds earlier.
5459   *
5460   * @since 3.3.0
5461   *
5462   * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
5463   * @return bool The current suspend setting
5464   */
5465  function wp_suspend_cache_addition( $suspend = null ) {
5466      static $_suspend = false;
5467  
5468      if ( is_bool( $suspend ) ) {
5469          $_suspend = $suspend;
5470      }
5471  
5472      return $_suspend;
5473  }
5474  
5475  /**
5476   * Suspend cache invalidation.
5477   *
5478   * Turns cache invalidation on and off. Useful during imports where you don't want to do
5479   * invalidations every time a post is inserted. Callers must be sure that what they are
5480   * doing won't lead to an inconsistent cache when invalidation is suspended.
5481   *
5482   * @since 2.7.0
5483   *
5484   * @global bool $_wp_suspend_cache_invalidation
5485   *
5486   * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
5487   * @return bool The current suspend setting.
5488   */
5489  function wp_suspend_cache_invalidation( $suspend = true ) {
5490      global $_wp_suspend_cache_invalidation;
5491  
5492      $current_suspend                = $_wp_suspend_cache_invalidation;
5493      $_wp_suspend_cache_invalidation = $suspend;
5494      return $current_suspend;
5495  }
5496  
5497  /**
5498   * Determine whether a site is the main site of the current network.
5499   *
5500   * @since 3.0.0
5501   * @since 4.9.0 The `$network_id` parameter was added.
5502   *
5503   * @param int $site_id    Optional. Site ID to test. Defaults to current site.
5504   * @param int $network_id Optional. Network ID of the network to check for.
5505   *                        Defaults to current network.
5506   * @return bool True if $site_id is the main site of the network, or if not
5507   *              running Multisite.
5508   */
5509  function is_main_site( $site_id = null, $network_id = null ) {
5510      if ( ! is_multisite() ) {
5511          return true;
5512      }
5513  
5514      if ( ! $site_id ) {
5515          $site_id = get_current_blog_id();
5516      }
5517  
5518      $site_id = (int) $site_id;
5519  
5520      return get_main_site_id( $network_id ) === $site_id;
5521  }
5522  
5523  /**
5524   * Gets the main site ID.
5525   *
5526   * @since 4.9.0
5527   *
5528   * @param int $network_id Optional. The ID of the network for which to get the main site.
5529   *                        Defaults to the current network.
5530   * @return int The ID of the main site.
5531   */
5532  function get_main_site_id( $network_id = null ) {
5533      if ( ! is_multisite() ) {
5534          return get_current_blog_id();
5535      }
5536  
5537      $network = get_network( $network_id );
5538      if ( ! $network ) {
5539          return 0;
5540      }
5541  
5542      return $network->site_id;
5543  }
5544  
5545  /**
5546   * Determine whether a network is the main network of the Multisite installation.
5547   *
5548   * @since 3.7.0
5549   *
5550   * @param int $network_id Optional. Network ID to test. Defaults to current network.
5551   * @return bool True if $network_id is the main network, or if not running Multisite.
5552   */
5553  function is_main_network( $network_id = null ) {
5554      if ( ! is_multisite() ) {
5555          return true;
5556      }
5557  
5558      if ( null === $network_id ) {
5559          $network_id = get_current_network_id();
5560      }
5561  
5562      $network_id = (int) $network_id;
5563  
5564      return ( get_main_network_id() === $network_id );
5565  }
5566  
5567  /**
5568   * Get the main network ID.
5569   *
5570   * @since 4.3.0
5571   *
5572   * @return int The ID of the main network.
5573   */
5574  function get_main_network_id() {
5575      if ( ! is_multisite() ) {
5576          return 1;
5577      }
5578  
5579      $current_network = get_network();
5580  
5581      if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
5582          $main_network_id = PRIMARY_NETWORK_ID;
5583      } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
5584          // If the current network has an ID of 1, assume it is the main network.
5585          $main_network_id = 1;
5586      } else {
5587          $_networks       = get_networks(
5588              array(
5589                  'fields' => 'ids',
5590                  'number' => 1,
5591              )
5592          );
5593          $main_network_id =