[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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