Make WordPress Core

Ticket #19552: 19552.diff

File 19552.diff, 149.6 KB (added by ryan, 12 years ago)
  • wp-includes/functions.php

     
    55 * @package WordPress
    66 */
    77
     8require( ABSPATH . WPINC . '/option.php' );
     9
    810/**
    911 * Converts MySQL DATETIME field to user specified date format.
    1012 *
     
    304306}
    305307
    306308/**
    307  * Retrieve option value based on name of option.
    308  *
    309  * If the option does not exist or does not have a value, then the return value
    310  * will be false. This is useful to check whether you need to install an option
    311  * and is commonly used during installation of plugin options and to test
    312  * whether upgrading is required.
    313  *
    314  * If the option was serialized then it will be unserialized when it is returned.
    315  *
    316  * @since 1.5.0
    317  * @package WordPress
    318  * @subpackage Option
    319  * @uses apply_filters() Calls 'pre_option_$option' before checking the option.
    320  *      Any value other than false will "short-circuit" the retrieval of the option
    321  *      and return the returned value. You should not try to override special options,
    322  *      but you will not be prevented from doing so.
    323  * @uses apply_filters() Calls 'option_$option', after checking the option, with
    324  *      the option value.
    325  *
    326  * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
    327  * @param mixed $default Optional. Default value to return if the option does not exist.
    328  * @return mixed Value set for the option.
    329  */
    330 function get_option( $option, $default = false ) {
    331         global $wpdb;
    332 
    333         // Allow plugins to short-circuit options.
    334         $pre = apply_filters( 'pre_option_' . $option, false );
    335         if ( false !== $pre )
    336                 return $pre;
    337 
    338         $option = trim($option);
    339         if ( empty($option) )
    340                 return false;
    341 
    342         if ( defined( 'WP_SETUP_CONFIG' ) )
    343                 return false;
    344 
    345         if ( ! defined( 'WP_INSTALLING' ) ) {
    346                 // prevent non-existent options from triggering multiple queries
    347                 $notoptions = wp_cache_get( 'notoptions', 'options' );
    348                 if ( isset( $notoptions[$option] ) )
    349                         return $default;
    350 
    351                 $alloptions = wp_load_alloptions();
    352 
    353                 if ( isset( $alloptions[$option] ) ) {
    354                         $value = $alloptions[$option];
    355                 } else {
    356                         $value = wp_cache_get( $option, 'options' );
    357 
    358                         if ( false === $value ) {
    359                                 $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
    360 
    361                                 // Has to be get_row instead of get_var because of funkiness with 0, false, null values
    362                                 if ( is_object( $row ) ) {
    363                                         $value = $row->option_value;
    364                                         wp_cache_add( $option, $value, 'options' );
    365                                 } else { // option does not exist, so we must cache its non-existence
    366                                         $notoptions[$option] = true;
    367                                         wp_cache_set( 'notoptions', $notoptions, 'options' );
    368                                         return $default;
    369                                 }
    370                         }
    371                 }
    372         } else {
    373                 $suppress = $wpdb->suppress_errors();
    374                 $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
    375                 $wpdb->suppress_errors( $suppress );
    376                 if ( is_object( $row ) )
    377                         $value = $row->option_value;
    378                 else
    379                         return $default;
    380         }
    381 
    382         // If home is not set use siteurl.
    383         if ( 'home' == $option && '' == $value )
    384                 return get_option( 'siteurl' );
    385 
    386         if ( in_array( $option, array('siteurl', 'home', 'category_base', 'tag_base') ) )
    387                 $value = untrailingslashit( $value );
    388 
    389         return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
    390 }
    391 
    392 /**
    393  * Protect WordPress special option from being modified.
    394  *
    395  * Will die if $option is in protected list. Protected options are 'alloptions'
    396  * and 'notoptions' options.
    397  *
    398  * @since 2.2.0
    399  * @package WordPress
    400  * @subpackage Option
    401  *
    402  * @param string $option Option name.
    403  */
    404 function wp_protect_special_option( $option ) {
    405         $protected = array( 'alloptions', 'notoptions' );
    406         if ( in_array( $option, $protected ) )
    407                 wp_die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
    408 }
    409 
    410 /**
    411  * Print option value after sanitizing for forms.
    412  *
    413  * @uses attr Sanitizes value.
    414  * @since 1.5.0
    415  * @package WordPress
    416  * @subpackage Option
    417  *
    418  * @param string $option Option name.
    419  */
    420 function form_option( $option ) {
    421         echo esc_attr( get_option( $option ) );
    422 }
    423 
    424 /**
    425  * Loads and caches all autoloaded options, if available or all options.
    426  *
    427  * @since 2.2.0
    428  * @package WordPress
    429  * @subpackage Option
    430  *
    431  * @return array List of all options.
    432  */
    433 function wp_load_alloptions() {
    434         global $wpdb;
    435 
    436         if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
    437                 $alloptions = wp_cache_get( 'alloptions', 'options' );
    438         else
    439                 $alloptions = false;
    440 
    441         if ( !$alloptions ) {
    442                 $suppress = $wpdb->suppress_errors();
    443                 if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
    444                         $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
    445                 $wpdb->suppress_errors($suppress);
    446                 $alloptions = array();
    447                 foreach ( (array) $alloptions_db as $o ) {
    448                         $alloptions[$o->option_name] = $o->option_value;
    449                 }
    450                 if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
    451                         wp_cache_add( 'alloptions', $alloptions, 'options' );
    452         }
    453 
    454         return $alloptions;
    455 }
    456 
    457 /**
    458  * Loads and caches certain often requested site options if is_multisite() and a persistent cache is not being used.
    459  *
    460  * @since 3.0.0
    461  * @package WordPress
    462  * @subpackage Option
    463  *
    464  * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
    465  */
    466 function wp_load_core_site_options( $site_id = null ) {
    467         global $wpdb, $_wp_using_ext_object_cache;
    468 
    469         if ( !is_multisite() || $_wp_using_ext_object_cache || defined( 'WP_INSTALLING' ) )
    470                 return;
    471 
    472         if ( empty($site_id) )
    473                 $site_id = $wpdb->siteid;
    474 
    475         $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled' );
    476 
    477         $core_options_in = "'" . implode("', '", $core_options) . "'";
    478         $options = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->sitemeta WHERE meta_key IN ($core_options_in) AND site_id = %d", $site_id) );
    479 
    480         foreach ( $options as $option ) {
    481                 $key = $option->meta_key;
    482                 $cache_key = "{$site_id}:$key";
    483                 $option->meta_value = maybe_unserialize( $option->meta_value );
    484 
    485                 wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
    486         }
    487 }
    488 
    489 /**
    490  * Update the value of an option that was already added.
    491  *
    492  * You do not need to serialize values. If the value needs to be serialized, then
    493  * it will be serialized before it is inserted into the database. Remember,
    494  * resources can not be serialized or added as an option.
    495  *
    496  * If the option does not exist, then the option will be added with the option
    497  * value, but you will not be able to set whether it is autoloaded. If you want
    498  * to set whether an option is autoloaded, then you need to use the add_option().
    499  *
    500  * @since 1.0.0
    501  * @package WordPress
    502  * @subpackage Option
    503  *
    504  * @uses apply_filters() Calls 'pre_update_option_$option' hook to allow overwriting the
    505  *      option value to be stored.
    506  * @uses do_action() Calls 'update_option' hook before updating the option.
    507  * @uses do_action() Calls 'update_option_$option' and 'updated_option' hooks on success.
    508  *
    509  * @param string $option Option name. Expected to not be SQL-escaped.
    510  * @param mixed $newvalue Option value. Expected to not be SQL-escaped.
    511  * @return bool False if value was not updated and true if value was updated.
    512  */
    513 function update_option( $option, $newvalue ) {
    514         global $wpdb;
    515 
    516         $option = trim($option);
    517         if ( empty($option) )
    518                 return false;
    519 
    520         wp_protect_special_option( $option );
    521 
    522         if ( is_object($newvalue) )
    523                 $newvalue = clone $newvalue;
    524 
    525         $newvalue = sanitize_option( $option, $newvalue );
    526         $oldvalue = get_option( $option );
    527         $newvalue = apply_filters( 'pre_update_option_' . $option, $newvalue, $oldvalue );
    528 
    529         // If the new and old values are the same, no need to update.
    530         if ( $newvalue === $oldvalue )
    531                 return false;
    532 
    533         if ( false === $oldvalue )
    534                 return add_option( $option, $newvalue );
    535 
    536         $notoptions = wp_cache_get( 'notoptions', 'options' );
    537         if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
    538                 unset( $notoptions[$option] );
    539                 wp_cache_set( 'notoptions', $notoptions, 'options' );
    540         }
    541 
    542         $_newvalue = $newvalue;
    543         $newvalue = maybe_serialize( $newvalue );
    544 
    545         do_action( 'update_option', $option, $oldvalue, $_newvalue );
    546         if ( ! defined( 'WP_INSTALLING' ) ) {
    547                 $alloptions = wp_load_alloptions();
    548                 if ( isset( $alloptions[$option] ) ) {
    549                         $alloptions[$option] = $_newvalue;
    550                         wp_cache_set( 'alloptions', $alloptions, 'options' );
    551                 } else {
    552                         wp_cache_set( $option, $_newvalue, 'options' );
    553                 }
    554         }
    555 
    556         $result = $wpdb->update( $wpdb->options, array( 'option_value' => $newvalue ), array( 'option_name' => $option ) );
    557 
    558         if ( $result ) {
    559                 do_action( "update_option_{$option}", $oldvalue, $_newvalue );
    560                 do_action( 'updated_option', $option, $oldvalue, $_newvalue );
    561                 return true;
    562         }
    563         return false;
    564 }
    565 
    566 /**
    567  * Add a new option.
    568  *
    569  * You do not need to serialize values. If the value needs to be serialized, then
    570  * it will be serialized before it is inserted into the database. Remember,
    571  * resources can not be serialized or added as an option.
    572  *
    573  * You can create options without values and then update the values later.
    574  * Existing options will not be updated and checks are performed to ensure that you
    575  * aren't adding a protected WordPress option. Care should be taken to not name
    576  * options the same as the ones which are protected.
    577  *
    578  * @package WordPress
    579  * @subpackage Option
    580  * @since 1.0.0
    581  *
    582  * @uses do_action() Calls 'add_option' hook before adding the option.
    583  * @uses do_action() Calls 'add_option_$option' and 'added_option' hooks on success.
    584  *
    585  * @param string $option Name of option to add. Expected to not be SQL-escaped.
    586  * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
    587  * @param mixed $deprecated Optional. Description. Not used anymore.
    588  * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
    589  * @return bool False if option was not added and true if option was added.
    590  */
    591 function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
    592         global $wpdb;
    593 
    594         if ( !empty( $deprecated ) )
    595                 _deprecated_argument( __FUNCTION__, '2.3' );
    596 
    597         $option = trim($option);
    598         if ( empty($option) )
    599                 return false;
    600 
    601         wp_protect_special_option( $option );
    602 
    603         if ( is_object($value) )
    604                 $value = clone $value;
    605 
    606         $value = sanitize_option( $option, $value );
    607 
    608         // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
    609         $notoptions = wp_cache_get( 'notoptions', 'options' );
    610         if ( !is_array( $notoptions ) || !isset( $notoptions[$option] ) )
    611                 if ( false !== get_option( $option ) )
    612                         return false;
    613 
    614         $_value = $value;
    615         $value = maybe_serialize( $value );
    616         $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
    617         do_action( 'add_option', $option, $_value );
    618         if ( ! defined( 'WP_INSTALLING' ) ) {
    619                 if ( 'yes' == $autoload ) {
    620                         $alloptions = wp_load_alloptions();
    621                         $alloptions[$option] = $value;
    622                         wp_cache_set( 'alloptions', $alloptions, 'options' );
    623                 } else {
    624                         wp_cache_set( $option, $value, 'options' );
    625                 }
    626         }
    627 
    628         // This option exists now
    629         $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
    630         if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
    631                 unset( $notoptions[$option] );
    632                 wp_cache_set( 'notoptions', $notoptions, 'options' );
    633         }
    634 
    635         $result = $wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", $option, $value, $autoload ) );
    636 
    637         if ( $result ) {
    638                 do_action( "add_option_{$option}", $option, $_value );
    639                 do_action( 'added_option', $option, $_value );
    640                 return true;
    641         }
    642         return false;
    643 }
    644 
    645 /**
    646  * Removes option by name. Prevents removal of protected WordPress options.
    647  *
    648  * @package WordPress
    649  * @subpackage Option
    650  * @since 1.2.0
    651  *
    652  * @uses do_action() Calls 'delete_option' hook before option is deleted.
    653  * @uses do_action() Calls 'deleted_option' and 'delete_option_$option' hooks on success.
    654  *
    655  * @param string $option Name of option to remove. Expected to not be SQL-escaped.
    656  * @return bool True, if option is successfully deleted. False on failure.
    657  */
    658 function delete_option( $option ) {
    659         global $wpdb;
    660 
    661         wp_protect_special_option( $option );
    662 
    663         // Get the ID, if no ID then return
    664         $row = $wpdb->get_row( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option ) );
    665         if ( is_null( $row ) )
    666                 return false;
    667         do_action( 'delete_option', $option );
    668         $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name = %s", $option) );
    669         if ( ! defined( 'WP_INSTALLING' ) ) {
    670                 if ( 'yes' == $row->autoload ) {
    671                         $alloptions = wp_load_alloptions();
    672                         if ( is_array( $alloptions ) && isset( $alloptions[$option] ) ) {
    673                                 unset( $alloptions[$option] );
    674                                 wp_cache_set( 'alloptions', $alloptions, 'options' );
    675                         }
    676                 } else {
    677                         wp_cache_delete( $option, 'options' );
    678                 }
    679         }
    680         if ( $result ) {
    681                 do_action( "delete_option_$option", $option );
    682                 do_action( 'deleted_option', $option );
    683                 return true;
    684         }
    685         return false;
    686 }
    687 
    688 /**
    689  * Delete a transient.
    690  *
    691  * @since 2.8.0
    692  * @package WordPress
    693  * @subpackage Transient
    694  *
    695  * @uses do_action() Calls 'delete_transient_$transient' hook before transient is deleted.
    696  * @uses do_action() Calls 'deleted_transient' hook on success.
    697  *
    698  * @param string $transient Transient name. Expected to not be SQL-escaped.
    699  * @return bool true if successful, false otherwise
    700  */
    701 function delete_transient( $transient ) {
    702         global $_wp_using_ext_object_cache;
    703 
    704         do_action( 'delete_transient_' . $transient, $transient );
    705 
    706         if ( $_wp_using_ext_object_cache ) {
    707                 $result = wp_cache_delete( $transient, 'transient' );
    708         } else {
    709                 $option_timeout = '_transient_timeout_' . $transient;
    710                 $option = '_transient_' . $transient;
    711                 $result = delete_option( $option );
    712                 if ( $result )
    713                         delete_option( $option_timeout );
    714         }
    715 
    716         if ( $result )
    717                 do_action( 'deleted_transient', $transient );
    718         return $result;
    719 }
    720 
    721 /**
    722  * Get the value of a transient.
    723  *
    724  * If the transient does not exist or does not have a value, then the return value
    725  * will be false.
    726  *
    727  * @uses apply_filters() Calls 'pre_transient_$transient' hook before checking the transient.
    728  *      Any value other than false will "short-circuit" the retrieval of the transient
    729  *      and return the returned value.
    730  * @uses apply_filters() Calls 'transient_$option' hook, after checking the transient, with
    731  *      the transient value.
    732  *
    733  * @since 2.8.0
    734  * @package WordPress
    735  * @subpackage Transient
    736  *
    737  * @param string $transient Transient name. Expected to not be SQL-escaped
    738  * @return mixed Value of transient
    739  */
    740 function get_transient( $transient ) {
    741         global $_wp_using_ext_object_cache;
    742 
    743         $pre = apply_filters( 'pre_transient_' . $transient, false );
    744         if ( false !== $pre )
    745                 return $pre;
    746 
    747         if ( $_wp_using_ext_object_cache ) {
    748                 $value = wp_cache_get( $transient, 'transient' );
    749         } else {
    750                 $transient_option = '_transient_' . $transient;
    751                 if ( ! defined( 'WP_INSTALLING' ) ) {
    752                         // If option is not in alloptions, it is not autoloaded and thus has a timeout
    753                         $alloptions = wp_load_alloptions();
    754                         if ( !isset( $alloptions[$transient_option] ) ) {
    755                                 $transient_timeout = '_transient_timeout_' . $transient;
    756                                 if ( get_option( $transient_timeout ) < time() ) {
    757                                         delete_option( $transient_option  );
    758                                         delete_option( $transient_timeout );
    759                                         return false;
    760                                 }
    761                         }
    762                 }
    763 
    764                 $value = get_option( $transient_option );
    765         }
    766 
    767         return apply_filters( 'transient_' . $transient, $value );
    768 }
    769 
    770 /**
    771  * Set/update the value of a transient.
    772  *
    773  * You do not need to serialize values. If the value needs to be serialized, then
    774  * it will be serialized before it is set.
    775  *
    776  * @since 2.8.0
    777  * @package WordPress
    778  * @subpackage Transient
    779  *
    780  * @uses apply_filters() Calls 'pre_set_transient_$transient' hook to allow overwriting the
    781  *      transient value to be stored.
    782  * @uses do_action() Calls 'set_transient_$transient' and 'setted_transient' hooks on success.
    783  *
    784  * @param string $transient Transient name. Expected to not be SQL-escaped.
    785  * @param mixed $value Transient value. Expected to not be SQL-escaped.
    786  * @param int $expiration Time until expiration in seconds, default 0
    787  * @return bool False if value was not set and true if value was set.
    788  */
    789 function set_transient( $transient, $value, $expiration = 0 ) {
    790         global $_wp_using_ext_object_cache;
    791 
    792         $value = apply_filters( 'pre_set_transient_' . $transient, $value );
    793 
    794         if ( $_wp_using_ext_object_cache ) {
    795                 $result = wp_cache_set( $transient, $value, 'transient', $expiration );
    796         } else {
    797                 $transient_timeout = '_transient_timeout_' . $transient;
    798                 $transient = '_transient_' . $transient;
    799                 if ( false === get_option( $transient ) ) {
    800                         $autoload = 'yes';
    801                         if ( $expiration ) {
    802                                 $autoload = 'no';
    803                                 add_option( $transient_timeout, time() + $expiration, '', 'no' );
    804                         }
    805                         $result = add_option( $transient, $value, '', $autoload );
    806                 } else {
    807                         if ( $expiration )
    808                                 update_option( $transient_timeout, time() + $expiration );
    809                         $result = update_option( $transient, $value );
    810                 }
    811         }
    812         if ( $result ) {
    813                 do_action( 'set_transient_' . $transient );
    814                 do_action( 'setted_transient', $transient );
    815         }
    816         return $result;
    817 }
    818 
    819 /**
    820  * Saves and restores user interface settings stored in a cookie.
    821  *
    822  * Checks if the current user-settings cookie is updated and stores it. When no
    823  * cookie exists (different browser used), adds the last saved cookie restoring
    824  * the settings.
    825  *
    826  * @package WordPress
    827  * @subpackage Option
    828  * @since 2.7.0
    829  */
    830 function wp_user_settings() {
    831 
    832         if ( ! is_admin() )
    833                 return;
    834 
    835         if ( defined('DOING_AJAX') )
    836                 return;
    837 
    838         if ( ! $user = wp_get_current_user() )
    839                 return;
    840 
    841         $settings = get_user_option( 'user-settings', $user->ID );
    842 
    843         if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
    844                 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
    845 
    846                 if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
    847                         if ( $cookie == $settings )
    848                                 return;
    849 
    850                         $last_time = (int) get_user_option( 'user-settings-time', $user->ID );
    851                         $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
    852 
    853                         if ( $saved > $last_time ) {
    854                                 update_user_option( $user->ID, 'user-settings', $cookie, false );
    855                                 update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
    856                                 return;
    857                         }
    858                 }
    859         }
    860 
    861         setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
    862         setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
    863         $_COOKIE['wp-settings-' . $user->ID] = $settings;
    864 }
    865 
    866 /**
    867  * Retrieve user interface setting value based on setting name.
    868  *
    869  * @package WordPress
    870  * @subpackage Option
    871  * @since 2.7.0
    872  *
    873  * @param string $name The name of the setting.
    874  * @param string $default Optional default value to return when $name is not set.
    875  * @return mixed the last saved user setting or the default value/false if it doesn't exist.
    876  */
    877 function get_user_setting( $name, $default = false ) {
    878 
    879         $all = get_all_user_settings();
    880 
    881         return isset($all[$name]) ? $all[$name] : $default;
    882 }
    883 
    884 /**
    885  * Add or update user interface setting.
    886  *
    887  * Both $name and $value can contain only ASCII letters, numbers and underscores.
    888  * This function has to be used before any output has started as it calls setcookie().
    889  *
    890  * @package WordPress
    891  * @subpackage Option
    892  * @since 2.8.0
    893  *
    894  * @param string $name The name of the setting.
    895  * @param string $value The value for the setting.
    896  * @return bool true if set successfully/false if not.
    897  */
    898 function set_user_setting( $name, $value ) {
    899 
    900         if ( headers_sent() )
    901                 return false;
    902 
    903         $all = get_all_user_settings();
    904         $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
    905 
    906         if ( empty($name) )
    907                 return false;
    908 
    909         $all[$name] = $value;
    910 
    911         return wp_set_all_user_settings($all);
    912 }
    913 
    914 /**
    915  * Delete user interface settings.
    916  *
    917  * Deleting settings would reset them to the defaults.
    918  * This function has to be used before any output has started as it calls setcookie().
    919  *
    920  * @package WordPress
    921  * @subpackage Option
    922  * @since 2.7.0
    923  *
    924  * @param mixed $names The name or array of names of the setting to be deleted.
    925  * @return bool true if deleted successfully/false if not.
    926  */
    927 function delete_user_setting( $names ) {
    928 
    929         if ( headers_sent() )
    930                 return false;
    931 
    932         $all = get_all_user_settings();
    933         $names = (array) $names;
    934 
    935         foreach ( $names as $name ) {
    936                 if ( isset($all[$name]) ) {
    937                         unset($all[$name]);
    938                         $deleted = true;
    939                 }
    940         }
    941 
    942         if ( isset($deleted) )
    943                 return wp_set_all_user_settings($all);
    944 
    945         return false;
    946 }
    947 
    948 /**
    949  * Retrieve all user interface settings.
    950  *
    951  * @package WordPress
    952  * @subpackage Option
    953  * @since 2.7.0
    954  *
    955  * @return array the last saved user settings or empty array.
    956  */
    957 function get_all_user_settings() {
    958         global $_updated_user_settings;
    959 
    960         if ( ! $user = wp_get_current_user() )
    961                 return array();
    962 
    963         if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
    964                 return $_updated_user_settings;
    965 
    966         $all = array();
    967         if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
    968                 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
    969 
    970                 if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
    971                         parse_str($cookie, $all);
    972 
    973         } else {
    974                 $option = get_user_option('user-settings', $user->ID);
    975                 if ( $option && is_string($option) )
    976                         parse_str( $option, $all );
    977         }
    978 
    979         return $all;
    980 }
    981 
    982 /**
    983  * Private. Set all user interface settings.
    984  *
    985  * @package WordPress
    986  * @subpackage Option
    987  * @since 2.8.0
    988  *
    989  * @param unknown $all
    990  * @return bool
    991  */
    992 function wp_set_all_user_settings($all) {
    993         global $_updated_user_settings;
    994 
    995         if ( ! $user = wp_get_current_user() )
    996                 return false;
    997 
    998         $_updated_user_settings = $all;
    999         $settings = '';
    1000         foreach ( $all as $k => $v ) {
    1001                 $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
    1002                 $settings .= $k . '=' . $v . '&';
    1003         }
    1004 
    1005         $settings = rtrim($settings, '&');
    1006 
    1007         update_user_option( $user->ID, 'user-settings', $settings, false );
    1008         update_user_option( $user->ID, 'user-settings-time', time(), false );
    1009 
    1010         return true;
    1011 }
    1012 
    1013 /**
    1014  * Delete the user settings of the current user.
    1015  *
    1016  * @package WordPress
    1017  * @subpackage Option
    1018  * @since 2.7.0
    1019  */
    1020 function delete_all_user_settings() {
    1021         if ( ! $user = wp_get_current_user() )
    1022                 return;
    1023 
    1024         update_user_option( $user->ID, 'user-settings', '', false );
    1025         setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
    1026 }
    1027 
    1028 /**
    1029309 * Serialize data, if needed.
    1030310 *
    1031311 * @since 2.0.5
     
    38033083}
    38043084
    38053085/**
    3806  * Retrieve site option value based on name of option.
    3807  *
    3808  * @see get_option()
    3809  * @package WordPress
    3810  * @subpackage Option
    3811  * @since 2.8.0
    3812  *
    3813  * @uses apply_filters() Calls 'pre_site_option_$option' before checking the option.
    3814  *      Any value other than false will "short-circuit" the retrieval of the option
    3815  *      and return the returned value.
    3816  * @uses apply_filters() Calls 'site_option_$option', after checking the  option, with
    3817  *      the option value.
    3818  *
    3819  * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
    3820  * @param mixed $default Optional value to return if option doesn't exist. Default false.
    3821  * @param bool $use_cache Whether to use cache. Multisite only. Default true.
    3822  * @return mixed Value set for the option.
    3823  */
    3824 function get_site_option( $option, $default = false, $use_cache = true ) {
    3825         global $wpdb;
    3826 
    3827         // Allow plugins to short-circuit site options.
    3828         $pre = apply_filters( 'pre_site_option_' . $option, false );
    3829         if ( false !== $pre )
    3830                 return $pre;
    3831 
    3832         if ( !is_multisite() ) {
    3833                 $value = get_option($option, $default);
    3834         } else {
    3835                 $cache_key = "{$wpdb->siteid}:$option";
    3836                 if ( $use_cache )
    3837                         $value = wp_cache_get($cache_key, 'site-options');
    3838 
    3839                 if ( !isset($value) || (false === $value) ) {
    3840                         $row = $wpdb->get_row( $wpdb->prepare("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
    3841 
    3842                         // Has to be get_row instead of get_var because of funkiness with 0, false, null values
    3843                         if ( is_object( $row ) ) {
    3844                                 $value = $row->meta_value;
    3845                                 $value = maybe_unserialize( $value );
    3846                                 wp_cache_set( $cache_key, $value, 'site-options' );
    3847                         } else {
    3848                                 $value = $default;
    3849                         }
    3850                 }
    3851         }
    3852 
    3853         return apply_filters( 'site_option_' . $option, $value );
    3854 }
    3855 
    3856 /**
    3857  * Add a new site option.
    3858  *
    3859  * Existing options will not be updated. Note that prior to 3.3 this wasn't the case.
    3860  *
    3861  * @see add_option()
    3862  * @package WordPress
    3863  * @subpackage Option
    3864  * @since 2.8.0
    3865  *
    3866  * @uses apply_filters() Calls 'pre_add_site_option_$option' hook to allow overwriting the
    3867  *      option value to be stored.
    3868  * @uses do_action() Calls 'add_site_option_$option' and 'add_site_option' hooks on success.
    3869  *
    3870  * @param string $option Name of option to add. Expected to not be SQL-escaped.
    3871  * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
    3872  * @return bool False if option was not added and true if option was added.
    3873  */
    3874 function add_site_option( $option, $value ) {
    3875         global $wpdb;
    3876 
    3877         $value = apply_filters( 'pre_add_site_option_' . $option, $value );
    3878 
    3879         if ( !is_multisite() ) {
    3880                 $result = add_option( $option, $value );
    3881         } else {
    3882                 $cache_key = "{$wpdb->siteid}:$option";
    3883 
    3884                 if ( false !== get_site_option( $option ) )
    3885                         return false;
    3886 
    3887                 $value = sanitize_option( $option, $value );
    3888                 wp_cache_set( $cache_key, $value, 'site-options' );
    3889 
    3890                 $_value = $value;
    3891                 $value = maybe_serialize( $value );
    3892                 $result = $wpdb->insert( $wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $value ) );
    3893                 $value = $_value;
    3894         }
    3895 
    3896         if ( $result ) {
    3897                 do_action( "add_site_option_{$option}", $option, $value );
    3898                 do_action( "add_site_option", $option, $value );
    3899                 return true;
    3900         }
    3901         return false;
    3902 }
    3903 
    3904 /**
    3905  * Removes site option by name.
    3906  *
    3907  * @see delete_option()
    3908  * @package WordPress
    3909  * @subpackage Option
    3910  * @since 2.8.0
    3911  *
    3912  * @uses do_action() Calls 'pre_delete_site_option_$option' hook before option is deleted.
    3913  * @uses do_action() Calls 'delete_site_option' and 'delete_site_option_$option'
    3914  *      hooks on success.
    3915  *
    3916  * @param string $option Name of option to remove. Expected to not be SQL-escaped.
    3917  * @return bool True, if succeed. False, if failure.
    3918  */
    3919 function delete_site_option( $option ) {
    3920         global $wpdb;
    3921 
    3922         // ms_protect_special_option( $option ); @todo
    3923 
    3924         do_action( 'pre_delete_site_option_' . $option );
    3925 
    3926         if ( !is_multisite() ) {
    3927                 $result = delete_option( $option );
    3928         } else {
    3929                 $row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
    3930                 if ( is_null( $row ) || !$row->meta_id )
    3931                         return false;
    3932                 $cache_key = "{$wpdb->siteid}:$option";
    3933                 wp_cache_delete( $cache_key, 'site-options' );
    3934 
    3935                 $result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
    3936         }
    3937 
    3938         if ( $result ) {
    3939                 do_action( "delete_site_option_{$option}", $option );
    3940                 do_action( "delete_site_option", $option );
    3941                 return true;
    3942         }
    3943         return false;
    3944 }
    3945 
    3946 /**
    3947  * Update the value of a site option that was already added.
    3948  *
    3949  * @see update_option()
    3950  * @since 2.8.0
    3951  * @package WordPress
    3952  * @subpackage Option
    3953  *
    3954  * @uses apply_filters() Calls 'pre_update_site_option_$option' hook to allow overwriting the
    3955  *      option value to be stored.
    3956  * @uses do_action() Calls 'update_site_option_$option' and 'update_site_option' hooks on success.
    3957  *
    3958  * @param string $option Name of option. Expected to not be SQL-escaped.
    3959  * @param mixed $value Option value. Expected to not be SQL-escaped.
    3960  * @return bool False if value was not updated and true if value was updated.
    3961  */
    3962 function update_site_option( $option, $value ) {
    3963         global $wpdb;
    3964 
    3965         $oldvalue = get_site_option( $option );
    3966         $value = apply_filters( 'pre_update_site_option_' . $option, $value, $oldvalue );
    3967 
    3968         if ( $value === $oldvalue )
    3969                 return false;
    3970 
    3971         if ( false === $oldvalue )
    3972                 return add_site_option( $option, $value );
    3973 
    3974         if ( !is_multisite() ) {
    3975                 $result = update_option( $option, $value );
    3976         } else {
    3977                 $value = sanitize_option( $option, $value );
    3978                 $cache_key = "{$wpdb->siteid}:$option";
    3979                 wp_cache_set( $cache_key, $value, 'site-options' );
    3980 
    3981                 $_value = $value;
    3982                 $value = maybe_serialize( $value );
    3983                 $result = $wpdb->update( $wpdb->sitemeta, array( 'meta_value' => $value ), array( 'site_id' => $wpdb->siteid, 'meta_key' => $option ) );
    3984                 $value = $_value;
    3985         }
    3986 
    3987         if ( $result ) {
    3988                 do_action( "update_site_option_{$option}", $option, $value, $oldvalue );
    3989                 do_action( "update_site_option", $option, $value, $oldvalue );
    3990                 return true;
    3991         }
    3992         return false;
    3993 }
    3994 
    3995 /**
    3996  * Delete a site transient.
    3997  *
    3998  * @since 2.9.0
    3999  * @package WordPress
    4000  * @subpackage Transient
    4001  *
    4002  * @uses do_action() Calls 'delete_site_transient_$transient' hook before transient is deleted.
    4003  * @uses do_action() Calls 'deleted_site_transient' hook on success.
    4004  *
    4005  * @param string $transient Transient name. Expected to not be SQL-escaped.
    4006  * @return bool True if successful, false otherwise
    4007  */
    4008 function delete_site_transient( $transient ) {
    4009         global $_wp_using_ext_object_cache;
    4010 
    4011         do_action( 'delete_site_transient_' . $transient, $transient );
    4012         if ( $_wp_using_ext_object_cache ) {
    4013                 $result = wp_cache_delete( $transient, 'site-transient' );
    4014         } else {
    4015                 $option_timeout = '_site_transient_timeout_' . $transient;
    4016                 $option = '_site_transient_' . $transient;
    4017                 $result = delete_site_option( $option );
    4018                 if ( $result )
    4019                         delete_site_option( $option_timeout );
    4020         }
    4021         if ( $result )
    4022                 do_action( 'deleted_site_transient', $transient );
    4023         return $result;
    4024 }
    4025 
    4026 /**
    4027  * Get the value of a site transient.
    4028  *
    4029  * If the transient does not exist or does not have a value, then the return value
    4030  * will be false.
    4031  *
    4032  * @see get_transient()
    4033  * @since 2.9.0
    4034  * @package WordPress
    4035  * @subpackage Transient
    4036  *
    4037  * @uses apply_filters() Calls 'pre_site_transient_$transient' hook before checking the transient.
    4038  *      Any value other than false will "short-circuit" the retrieval of the transient
    4039  *      and return the returned value.
    4040  * @uses apply_filters() Calls 'site_transient_$option' hook, after checking the transient, with
    4041  *      the transient value.
    4042  *
    4043  * @param string $transient Transient name. Expected to not be SQL-escaped.
    4044  * @return mixed Value of transient
    4045  */
    4046 function get_site_transient( $transient ) {
    4047         global $_wp_using_ext_object_cache;
    4048 
    4049         $pre = apply_filters( 'pre_site_transient_' . $transient, false );
    4050         if ( false !== $pre )
    4051                 return $pre;
    4052 
    4053         if ( $_wp_using_ext_object_cache ) {
    4054                 $value = wp_cache_get( $transient, 'site-transient' );
    4055         } else {
    4056                 // Core transients that do not have a timeout. Listed here so querying timeouts can be avoided.
    4057                 $no_timeout = array('update_core', 'update_plugins', 'update_themes');
    4058                 $transient_option = '_site_transient_' . $transient;
    4059                 if ( ! in_array( $transient, $no_timeout ) ) {
    4060                         $transient_timeout = '_site_transient_timeout_' . $transient;
    4061                         $timeout = get_site_option( $transient_timeout );
    4062                         if ( false !== $timeout && $timeout < time() ) {
    4063                                 delete_site_option( $transient_option  );
    4064                                 delete_site_option( $transient_timeout );
    4065                                 return false;
    4066                         }
    4067                 }
    4068 
    4069                 $value = get_site_option( $transient_option );
    4070         }
    4071 
    4072         return apply_filters( 'site_transient_' . $transient, $value );
    4073 }
    4074 
    4075 /**
    4076  * Set/update the value of a site transient.
    4077  *
    4078  * You do not need to serialize values, if the value needs to be serialize, then
    4079  * it will be serialized before it is set.
    4080  *
    4081  * @see set_transient()
    4082  * @since 2.9.0
    4083  * @package WordPress
    4084  * @subpackage Transient
    4085  *
    4086  * @uses apply_filters() Calls 'pre_set_site_transient_$transient' hook to allow overwriting the
    4087  *      transient value to be stored.
    4088  * @uses do_action() Calls 'set_site_transient_$transient' and 'setted_site_transient' hooks on success.
    4089  *
    4090  * @param string $transient Transient name. Expected to not be SQL-escaped.
    4091  * @param mixed $value Transient value. Expected to not be SQL-escaped.
    4092  * @param int $expiration Time until expiration in seconds, default 0
    4093  * @return bool False if value was not set and true if value was set.
    4094  */
    4095 function set_site_transient( $transient, $value, $expiration = 0 ) {
    4096         global $_wp_using_ext_object_cache;
    4097 
    4098         $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
    4099 
    4100         if ( $_wp_using_ext_object_cache ) {
    4101                 $result = wp_cache_set( $transient, $value, 'site-transient', $expiration );
    4102         } else {
    4103                 $transient_timeout = '_site_transient_timeout_' . $transient;
    4104                 $transient = '_site_transient_' . $transient;
    4105                 if ( false === get_site_option( $transient ) ) {
    4106                         if ( $expiration )
    4107                                 add_site_option( $transient_timeout, time() + $expiration );
    4108                         $result = add_site_option( $transient, $value );
    4109                 } else {
    4110                         if ( $expiration )
    4111                                 update_site_option( $transient_timeout, time() + $expiration );
    4112                         $result = update_site_option( $transient, $value );
    4113                 }
    4114         }
    4115         if ( $result ) {
    4116                 do_action( 'set_site_transient_' . $transient );
    4117                 do_action( 'setted_site_transient', $transient );
    4118         }
    4119         return $result;
    4120 }
    4121 
    4122 /**
    41233086 * Is main site?
    41243087 *
    41253088 *
  • wp-includes/option.php

     
    11<?php
    22/**
    3  * Main WordPress API
     3 * Option API
    44 *
    55 * @package WordPress
    66 */
    77
    88/**
    9  * Converts MySQL DATETIME field to user specified date format.
    10  *
    11  * If $dateformatstring has 'G' value, then gmmktime() function will be used to
    12  * make the time. If $dateformatstring is set to 'U', then mktime() function
    13  * will be used to make the time.
    14  *
    15  * The $translate will only be used, if it is set to true and it is by default
    16  * and if the $wp_locale object has the month and weekday set.
    17  *
    18  * @since 0.71
    19  *
    20  * @param string $dateformatstring Either 'G', 'U', or php date format.
    21  * @param string $mysqlstring Time from mysql DATETIME field.
    22  * @param bool $translate Optional. Default is true. Will switch format to locale.
    23  * @return string Date formatted by $dateformatstring or locale (if available).
    24  */
    25 function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
    26         $m = $mysqlstring;
    27         if ( empty( $m ) )
    28                 return false;
    29 
    30         if ( 'G' == $dateformatstring )
    31                 return strtotime( $m . ' +0000' );
    32 
    33         $i = strtotime( $m );
    34 
    35         if ( 'U' == $dateformatstring )
    36                 return $i;
    37 
    38         if ( $translate )
    39                 return date_i18n( $dateformatstring, $i );
    40         else
    41                 return date( $dateformatstring, $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  *
    50  * If $gmt is set to either '1' or 'true', then both types will use GMT time.
    51  * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
    52  *
    53  * @since 1.0.0
    54  *
    55  * @param string $type Either 'mysql' or 'timestamp'.
    56  * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
    57  * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
    58  */
    59 function current_time( $type, $gmt = 0 ) {
    60         switch ( $type ) {
    61                 case 'mysql':
    62                         return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
    63                         break;
    64                 case 'timestamp':
    65                         return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
    66                         break;
    67         }
    68 }
    69 
    70 /**
    71  * Retrieve the date in localized format, based on timestamp.
    72  *
    73  * If the locale specifies the locale month and weekday, then the locale will
    74  * take over the format for the date. If it isn't, then the date format string
    75  * will be used instead.
    76  *
    77  * @since 0.71
    78  *
    79  * @param string $dateformatstring Format to display the date.
    80  * @param int $unixtimestamp Optional. Unix timestamp.
    81  * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
    82  * @return string The date, translated if locale specifies it.
    83  */
    84 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
    85         global $wp_locale;
    86         $i = $unixtimestamp;
    87 
    88         if ( false === $i ) {
    89                 if ( ! $gmt )
    90                         $i = current_time( 'timestamp' );
    91                 else
    92                         $i = time();
    93                 // we should not let date() interfere with our
    94                 // specially computed timestamp
    95                 $gmt = true;
    96         }
    97 
    98         // store original value for language with untypical grammars
    99         // see http://core.trac.wordpress.org/ticket/9396
    100         $req_format = $dateformatstring;
    101 
    102         $datefunc = $gmt? 'gmdate' : 'date';
    103 
    104         if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
    105                 $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
    106                 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
    107                 $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
    108                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
    109                 $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
    110                 $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
    111                 $dateformatstring = ' '.$dateformatstring;
    112                 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
    113                 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
    114                 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
    115                 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
    116                 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
    117                 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
    118 
    119                 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
    120         }
    121         $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
    122         $timezone_formats_re = implode( '|', $timezone_formats );
    123         if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
    124                 $timezone_string = get_option( 'timezone_string' );
    125                 if ( $timezone_string ) {
    126                         $timezone_object = timezone_open( $timezone_string );
    127                         $date_object = date_create( null, $timezone_object );
    128                         foreach( $timezone_formats as $timezone_format ) {
    129                                 if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
    130                                         $formatted = date_format( $date_object, $timezone_format );
    131                                         $dateformatstring = ' '.$dateformatstring;
    132                                         $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
    133                                         $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
    134                                 }
    135                         }
    136                 }
    137         }
    138         $j = @$datefunc( $dateformatstring, $i );
    139         // allow plugins to redo this entirely for languages with untypical grammars
    140         $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
    141         return $j;
    142 }
    143 
    144 /**
    145  * Convert integer number to format based on the locale.
    146  *
    147  * @since 2.3.0
    148  *
    149  * @param int $number The number to convert based on locale.
    150  * @param int $decimals Precision of the number of decimal places.
    151  * @return string Converted number in string format.
    152  */
    153 function number_format_i18n( $number, $decimals = 0 ) {
    154         global $wp_locale;
    155         $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
    156         return apply_filters( 'number_format_i18n', $formatted );
    157 }
    158 
    159 /**
    160  * Convert number of bytes largest unit bytes will fit into.
    161  *
    162  * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
    163  * number of bytes to human readable number by taking the number of that unit
    164  * that the bytes will go into it. Supports TB value.
    165  *
    166  * Please note that integers in PHP are limited to 32 bits, unless they are on
    167  * 64 bit architecture, then they have 64 bit size. If you need to place the
    168  * larger size then what PHP integer type will hold, then use a string. It will
    169  * be converted to a double, which should always have 64 bit length.
    170  *
    171  * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
    172  * @link http://en.wikipedia.org/wiki/Byte
    173  *
    174  * @since 2.3.0
    175  *
    176  * @param int|string $bytes Number of bytes. Note max integer size for integers.
    177  * @param int $decimals Precision of number of decimal places. Deprecated.
    178  * @return bool|string False on failure. Number string on success.
    179  */
    180 function size_format( $bytes, $decimals = 0 ) {
    181         $quant = array(
    182                 // ========================= Origin ====
    183                 'TB' => 1099511627776,  // pow( 1024, 4)
    184                 'GB' => 1073741824,     // pow( 1024, 3)
    185                 'MB' => 1048576,        // pow( 1024, 2)
    186                 'kB' => 1024,           // pow( 1024, 1)
    187                 'B ' => 1,              // pow( 1024, 0)
    188         );
    189         foreach ( $quant as $unit => $mag )
    190                 if ( doubleval($bytes) >= $mag )
    191                         return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
    192 
    193         return false;
    194 }
    195 
    196 /**
    197  * Get the week start and end from the datetime or date string from mysql.
    198  *
    199  * @since 0.71
    200  *
    201  * @param string $mysqlstring Date or datetime field type from mysql.
    202  * @param int $start_of_week Optional. Start of the week as an integer.
    203  * @return array Keys are 'start' and 'end'.
    204  */
    205 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
    206         $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
    207         $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
    208         $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
    209         $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
    210         $weekday = date( 'w', $day ); // The day of the week from the timestamp
    211         if ( !is_numeric($start_of_week) )
    212                 $start_of_week = get_option( 'start_of_week' );
    213 
    214         if ( $weekday < $start_of_week )
    215                 $weekday += 7;
    216 
    217         $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
    218         $end = $start + 604799; // $start + 7 days - 1 second
    219         return compact( 'start', 'end' );
    220 }
    221 
    222 /**
    223  * Unserialize value only if it was serialized.
    224  *
    225  * @since 2.0.0
    226  *
    227  * @param string $original Maybe unserialized original, if is needed.
    228  * @return mixed Unserialized data can be any type.
    229  */
    230 function maybe_unserialize( $original ) {
    231         if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
    232                 return @unserialize( $original );
    233         return $original;
    234 }
    235 
    236 /**
    237  * Check value to find if it was serialized.
    238  *
    239  * If $data is not an string, then returned value will always be false.
    240  * Serialized data is always a string.
    241  *
    242  * @since 2.0.5
    243  *
    244  * @param mixed $data Value to check to see if was serialized.
    245  * @return bool False if not serialized and true if it was.
    246  */
    247 function is_serialized( $data ) {
    248         // if it isn't a string, it isn't serialized
    249         if ( ! is_string( $data ) )
    250                 return false;
    251         $data = trim( $data );
    252         if ( 'N;' == $data )
    253                 return true;
    254         $length = strlen( $data );
    255         if ( $length < 4 )
    256                 return false;
    257         if ( ':' !== $data[1] )
    258                 return false;
    259         $lastc = $data[$length-1];
    260         if ( ';' !== $lastc && '}' !== $lastc )
    261                 return false;
    262         $token = $data[0];
    263         switch ( $token ) {
    264                 case 's' :
    265                         if ( '"' !== $data[$length-2] )
    266                                 return false;
    267                 case 'a' :
    268                 case 'O' :
    269                         return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
    270                 case 'b' :
    271                 case 'i' :
    272                 case 'd' :
    273                         return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
    274         }
    275         return false;
    276 }
    277 
    278 /**
    279  * Check whether serialized data is of string type.
    280  *
    281  * @since 2.0.5
    282  *
    283  * @param mixed $data Serialized data
    284  * @return bool False if not a serialized string, true if it is.
    285  */
    286 function is_serialized_string( $data ) {
    287         // if it isn't a string, it isn't a serialized string
    288         if ( !is_string( $data ) )
    289                 return false;
    290         $data = trim( $data );
    291         $length = strlen( $data );
    292         if ( $length < 4 )
    293                 return false;
    294         elseif ( ':' !== $data[1] )
    295                 return false;
    296         elseif ( ';' !== $data[$length-1] )
    297                 return false;
    298         elseif ( $data[0] !== 's' )
    299                 return false;
    300         elseif ( '"' !== $data[$length-2] )
    301                 return false;
    302         else
    303                 return true;
    304 }
    305 
    306 /**
    3079 * Retrieve option value based on name of option.
    30810 *
    30911 * If the option does not exist or does not have a value, then the return value
     
    1026728}
    1027729
    1028730/**
    1029  * Serialize data, if needed.
    1030  *
    1031  * @since 2.0.5
    1032  *
    1033  * @param mixed $data Data that might be serialized.
    1034  * @return mixed A scalar data
    1035  */
    1036 function maybe_serialize( $data ) {
    1037         if ( is_array( $data ) || is_object( $data ) )
    1038                 return serialize( $data );
    1039 
    1040         // Double serialization is required for backward compatibility.
    1041         // See http://core.trac.wordpress.org/ticket/12930
    1042         if ( is_serialized( $data ) )
    1043                 return serialize( $data );
    1044 
    1045         return $data;
    1046 }
    1047 
    1048 /**
    1049  * Retrieve post title from XMLRPC XML.
    1050  *
    1051  * If the title element is not part of the XML, then the default post title from
    1052  * the $post_default_title will be used instead.
    1053  *
    1054  * @package WordPress
    1055  * @subpackage XMLRPC
    1056  * @since 0.71
    1057  *
    1058  * @global string $post_default_title Default XMLRPC post title.
    1059  *
    1060  * @param string $content XMLRPC XML Request content
    1061  * @return string Post title
    1062  */
    1063 function xmlrpc_getposttitle( $content ) {
    1064         global $post_default_title;
    1065         if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
    1066                 $post_title = $matchtitle[1];
    1067         } else {
    1068                 $post_title = $post_default_title;
    1069         }
    1070         return $post_title;
    1071 }
    1072 
    1073 /**
    1074  * Retrieve the post category or categories from XMLRPC XML.
    1075  *
    1076  * If the category element is not found, then the default post category will be
    1077  * used. The return type then would be what $post_default_category. If the
    1078  * category is found, then it will always be an array.
    1079  *
    1080  * @package WordPress
    1081  * @subpackage XMLRPC
    1082  * @since 0.71
    1083  *
    1084  * @global string $post_default_category Default XMLRPC post category.
    1085  *
    1086  * @param string $content XMLRPC XML Request content
    1087  * @return string|array List of categories or category name.
    1088  */
    1089 function xmlrpc_getpostcategory( $content ) {
    1090         global $post_default_category;
    1091         if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
    1092                 $post_category = trim( $matchcat[1], ',' );
    1093                 $post_category = explode( ',', $post_category );
    1094         } else {
    1095                 $post_category = $post_default_category;
    1096         }
    1097         return $post_category;
    1098 }
    1099 
    1100 /**
    1101  * XMLRPC XML content without title and category elements.
    1102  *
    1103  * @package WordPress
    1104  * @subpackage XMLRPC
    1105  * @since 0.71
    1106  *
    1107  * @param string $content XMLRPC XML Request content
    1108  * @return string XMLRPC XML Request content without title and category elements.
    1109  */
    1110 function xmlrpc_removepostdata( $content ) {
    1111         $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
    1112         $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
    1113         $content = trim( $content );
    1114         return $content;
    1115 }
    1116 
    1117 /**
    1118  * Open the file handle for debugging.
    1119  *
    1120  * This function is used for XMLRPC feature, but it is general purpose enough
    1121  * to be used in anywhere.
    1122  *
    1123  * @see fopen() for mode options.
    1124  * @package WordPress
    1125  * @subpackage Debug
    1126  * @since 0.71
    1127  * @uses $debug Used for whether debugging is enabled.
    1128  *
    1129  * @param string $filename File path to debug file.
    1130  * @param string $mode Same as fopen() mode parameter.
    1131  * @return bool|resource File handle. False on failure.
    1132  */
    1133 function debug_fopen( $filename, $mode ) {
    1134         global $debug;
    1135         if ( 1 == $debug ) {
    1136                 $fp = fopen( $filename, $mode );
    1137                 return $fp;
    1138         } else {
    1139                 return false;
    1140         }
    1141 }
    1142 
    1143 /**
    1144  * Write contents to the file used for debugging.
    1145  *
    1146  * Technically, this can be used to write to any file handle when the global
    1147  * $debug is set to 1 or true.
    1148  *
    1149  * @package WordPress
    1150  * @subpackage Debug
    1151  * @since 0.71
    1152  * @uses $debug Used for whether debugging is enabled.
    1153  *
    1154  * @param resource $fp File handle for debugging file.
    1155  * @param string $string Content to write to debug file.
    1156  */
    1157 function debug_fwrite( $fp, $string ) {
    1158         global $debug;
    1159         if ( 1 == $debug )
    1160                 fwrite( $fp, $string );
    1161 }
    1162 
    1163 /**
    1164  * Close the debugging file handle.
    1165  *
    1166  * Technically, this can be used to close any file handle when the global $debug
    1167  * is set to 1 or true.
    1168  *
    1169  * @package WordPress
    1170  * @subpackage Debug
    1171  * @since 0.71
    1172  * @uses $debug Used for whether debugging is enabled.
    1173  *
    1174  * @param resource $fp Debug File handle.
    1175  */
    1176 function debug_fclose( $fp ) {
    1177         global $debug;
    1178         if ( 1 == $debug )
    1179                 fclose( $fp );
    1180 }
    1181 
    1182 /**
    1183  * Check content for video and audio links to add as enclosures.
    1184  *
    1185  * Will not add enclosures that have already been added and will
    1186  * remove enclosures that are no longer in the post. This is called as
    1187  * pingbacks and trackbacks.
    1188  *
    1189  * @package WordPress
    1190  * @since 1.5.0
    1191  *
    1192  * @uses $wpdb
    1193  *
    1194  * @param string $content Post Content
    1195  * @param int $post_ID Post ID
    1196  */
    1197 function do_enclose( $content, $post_ID ) {
    1198         global $wpdb;
    1199 
    1200         //TODO: Tidy this ghetto code up and make the debug code optional
    1201         include_once( ABSPATH . WPINC . '/class-IXR.php' );
    1202 
    1203         $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
    1204         $post_links = array();
    1205         debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
    1206 
    1207         $pung = get_enclosed( $post_ID );
    1208 
    1209         $ltrs = '\w';
    1210         $gunk = '/#~:.?+=&%@!\-';
    1211         $punc = '.:?\-';
    1212         $any = $ltrs . $gunk . $punc;
    1213 
    1214         preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
    1215 
    1216         debug_fwrite( $log, 'Post contents:' );
    1217         debug_fwrite( $log, $content . "\n" );
    1218 
    1219         foreach ( $pung as $link_test ) {
    1220                 if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
    1221                         $mid = $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, like_escape( $link_test ) . '%') );
    1222                         do_action( 'delete_postmeta', $mid );
    1223                         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN(%s)", implode( ',', $mid ) ) );
    1224                         do_action( 'deleted_postmeta', $mid );
    1225                 }
    1226         }
    1227 
    1228         foreach ( (array) $post_links_temp[0] as $link_test ) {
    1229                 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
    1230                         $test = @parse_url( $link_test );
    1231                         if ( false === $test )
    1232                                 continue;
    1233                         if ( isset( $test['query'] ) )
    1234                                 $post_links[] = $link_test;
    1235                         elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
    1236                                 $post_links[] = $link_test;
    1237                 }
    1238         }
    1239 
    1240         foreach ( (array) $post_links as $url ) {
    1241                 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, like_escape( $url ) . '%' ) ) ) {
    1242 
    1243                         if ( $headers = wp_get_http_headers( $url) ) {
    1244                                 $len = (int) $headers['content-length'];
    1245                                 $type = $headers['content-type'];
    1246                                 $allowed_types = array( 'video', 'audio' );
    1247 
    1248                                 // Check to see if we can figure out the mime type from
    1249                                 // the extension
    1250                                 $url_parts = @parse_url( $url );
    1251                                 if ( false !== $url_parts ) {
    1252                                         $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
    1253                                         if ( !empty( $extension ) ) {
    1254                                                 foreach ( get_allowed_mime_types( ) as $exts => $mime ) {
    1255                                                         if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
    1256                                                                 $type = $mime;
    1257                                                                 break;
    1258                                                         }
    1259                                                 }
    1260                                         }
    1261                                 }
    1262 
    1263                                 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
    1264                                         $meta_value = "$url\n$len\n$type\n";
    1265                                         $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
    1266                                         do_action( 'added_postmeta', $wpdb->insert_id, $post_ID, 'enclosure', $meta_value );
    1267                                 }
    1268                         }
    1269                 }
    1270         }
    1271 }
    1272 
    1273 /**
    1274  * Perform a HTTP HEAD or GET request.
    1275  *
    1276  * If $file_path is a writable filename, this will do a GET request and write
    1277  * the file to that path.
    1278  *
    1279  * @since 2.5.0
    1280  *
    1281  * @param string $url URL to fetch.
    1282  * @param string|bool $file_path Optional. File path to write request to.
    1283  * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
    1284  * @return bool|string False on failure and string of headers if HEAD request.
    1285  */
    1286 function wp_get_http( $url, $file_path = false, $red = 1 ) {
    1287         @set_time_limit( 60 );
    1288 
    1289         if ( $red > 5 )
    1290                 return false;
    1291 
    1292         $options = array();
    1293         $options['redirection'] = 5;
    1294 
    1295         if ( false == $file_path )
    1296                 $options['method'] = 'HEAD';
    1297         else
    1298                 $options['method'] = 'GET';
    1299 
    1300         $response = wp_remote_request($url, $options);
    1301 
    1302         if ( is_wp_error( $response ) )
    1303                 return false;
    1304 
    1305         $headers = wp_remote_retrieve_headers( $response );
    1306         $headers['response'] = wp_remote_retrieve_response_code( $response );
    1307 
    1308         // WP_HTTP no longer follows redirects for HEAD requests.
    1309         if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
    1310                 return wp_get_http( $headers['location'], $file_path, ++$red );
    1311         }
    1312 
    1313         if ( false == $file_path )
    1314                 return $headers;
    1315 
    1316         // GET request - write it to the supplied filename
    1317         $out_fp = fopen($file_path, 'w');
    1318         if ( !$out_fp )
    1319                 return $headers;
    1320 
    1321         fwrite( $out_fp,  wp_remote_retrieve_body( $response ) );
    1322         fclose($out_fp);
    1323         clearstatcache();
    1324 
    1325         return $headers;
    1326 }
    1327 
    1328 /**
    1329  * Retrieve HTTP Headers from URL.
    1330  *
    1331  * @since 1.5.1
    1332  *
    1333  * @param string $url
    1334  * @param bool $deprecated Not Used.
    1335  * @return bool|string False on failure, headers on success.
    1336  */
    1337 function wp_get_http_headers( $url, $deprecated = false ) {
    1338         if ( !empty( $deprecated ) )
    1339                 _deprecated_argument( __FUNCTION__, '2.7' );
    1340 
    1341         $response = wp_remote_head( $url );
    1342 
    1343         if ( is_wp_error( $response ) )
    1344                 return false;
    1345 
    1346         return wp_remote_retrieve_headers( $response );
    1347 }
    1348 
    1349 /**
    1350  * Whether today is a new day.
    1351  *
    1352  * @since 0.71
    1353  * @uses $day Today
    1354  * @uses $previousday Previous day
    1355  *
    1356  * @return int 1 when new day, 0 if not a new day.
    1357  */
    1358 function is_new_day() {
    1359         global $currentday, $previousday;
    1360         if ( $currentday != $previousday )
    1361                 return 1;
    1362         else
    1363                 return 0;
    1364 }
    1365 
    1366 /**
    1367  * Build URL query based on an associative and, or indexed array.
    1368  *
    1369  * This is a convenient function for easily building url queries. It sets the
    1370  * separator to '&' and uses _http_build_query() function.
    1371  *
    1372  * @see _http_build_query() Used to build the query
    1373  * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
    1374  *              http_build_query() does.
    1375  *
    1376  * @since 2.3.0
    1377  *
    1378  * @param array $data URL-encode key/value pairs.
    1379  * @return string URL encoded string
    1380  */
    1381 function build_query( $data ) {
    1382         return _http_build_query( $data, null, '&', '', false );
    1383 }
    1384 
    1385 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
    1386 function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
    1387         $ret = array();
    1388 
    1389         foreach ( (array) $data as $k => $v ) {
    1390                 if ( $urlencode)
    1391                         $k = urlencode($k);
    1392                 if ( is_int($k) && $prefix != null )
    1393                         $k = $prefix.$k;
    1394                 if ( !empty($key) )
    1395                         $k = $key . '%5B' . $k . '%5D';
    1396                 if ( $v === NULL )
    1397                         continue;
    1398                 elseif ( $v === FALSE )
    1399                         $v = '0';
    1400 
    1401                 if ( is_array($v) || is_object($v) )
    1402                         array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
    1403                 elseif ( $urlencode )
    1404                         array_push($ret, $k.'='.urlencode($v));
    1405                 else
    1406                         array_push($ret, $k.'='.$v);
    1407         }
    1408 
    1409         if ( NULL === $sep )
    1410                 $sep = ini_get('arg_separator.output');
    1411 
    1412         return implode($sep, $ret);
    1413 }
    1414 
    1415 /**
    1416  * Retrieve a modified URL query string.
    1417  *
    1418  * You can rebuild the URL and append a new query variable to the URL query by
    1419  * using this function. You can also retrieve the full URL with query data.
    1420  *
    1421  * Adding a single key & value or an associative array. Setting a key value to
    1422  * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
    1423  * value. Additional values provided are expected to be encoded appropriately
    1424  * with urlencode() or rawurlencode().
    1425  *
    1426  * @since 1.5.0
    1427  *
    1428  * @param mixed $param1 Either newkey or an associative_array
    1429  * @param mixed $param2 Either newvalue or oldquery or uri
    1430  * @param mixed $param3 Optional. Old query or uri
    1431  * @return string New URL query string.
    1432  */
    1433 function add_query_arg() {
    1434         $ret = '';
    1435         if ( is_array( func_get_arg(0) ) ) {
    1436                 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
    1437                         $uri = $_SERVER['REQUEST_URI'];
    1438                 else
    1439                         $uri = @func_get_arg( 1 );
    1440         } else {
    1441                 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
    1442                         $uri = $_SERVER['REQUEST_URI'];
    1443                 else
    1444                         $uri = @func_get_arg( 2 );
    1445         }
    1446 
    1447         if ( $frag = strstr( $uri, '#' ) )
    1448                 $uri = substr( $uri, 0, -strlen( $frag ) );
    1449         else
    1450                 $frag = '';
    1451 
    1452         if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
    1453                 $protocol = $matches[0];
    1454                 $uri = substr( $uri, strlen( $protocol ) );
    1455         } else {
    1456                 $protocol = '';
    1457         }
    1458 
    1459         if ( strpos( $uri, '?' ) !== false ) {
    1460                 $parts = explode( '?', $uri, 2 );
    1461                 if ( 1 == count( $parts ) ) {
    1462                         $base = '?';
    1463                         $query = $parts[0];
    1464                 } else {
    1465                         $base = $parts[0] . '?';
    1466                         $query = $parts[1];
    1467                 }
    1468         } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
    1469                 $base = $uri . '?';
    1470                 $query = '';
    1471         } else {
    1472                 $base = '';
    1473                 $query = $uri;
    1474         }
    1475 
    1476         wp_parse_str( $query, $qs );
    1477         $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
    1478         if ( is_array( func_get_arg( 0 ) ) ) {
    1479                 $kayvees = func_get_arg( 0 );
    1480                 $qs = array_merge( $qs, $kayvees );
    1481         } else {
    1482                 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
    1483         }
    1484 
    1485         foreach ( (array) $qs as $k => $v ) {
    1486                 if ( $v === false )
    1487                         unset( $qs[$k] );
    1488         }
    1489 
    1490         $ret = build_query( $qs );
    1491         $ret = trim( $ret, '?' );
    1492         $ret = preg_replace( '#=(&|$)#', '$1', $ret );
    1493         $ret = $protocol . $base . $ret . $frag;
    1494         $ret = rtrim( $ret, '?' );
    1495         return $ret;
    1496 }
    1497 
    1498 /**
    1499  * Removes an item or list from the query string.
    1500  *
    1501  * @since 1.5.0
    1502  *
    1503  * @param string|array $key Query key or keys to remove.
    1504  * @param bool $query When false uses the $_SERVER value.
    1505  * @return string New URL query string.
    1506  */
    1507 function remove_query_arg( $key, $query=false ) {
    1508         if ( is_array( $key ) ) { // removing multiple keys
    1509                 foreach ( $key as $k )
    1510                         $query = add_query_arg( $k, false, $query );
    1511                 return $query;
    1512         }
    1513         return add_query_arg( $key, false, $query );
    1514 }
    1515 
    1516 /**
    1517  * Walks the array while sanitizing the contents.
    1518  *
    1519  * @since 0.71
    1520  *
    1521  * @param array $array Array to used to walk while sanitizing contents.
    1522  * @return array Sanitized $array.
    1523  */
    1524 function add_magic_quotes( $array ) {
    1525         foreach ( (array) $array as $k => $v ) {
    1526                 if ( is_array( $v ) ) {
    1527                         $array[$k] = add_magic_quotes( $v );
    1528                 } else {
    1529                         $array[$k] = addslashes( $v );
    1530                 }
    1531         }
    1532         return $array;
    1533 }
    1534 
    1535 /**
    1536  * HTTP request for URI to retrieve content.
    1537  *
    1538  * @since 1.5.1
    1539  * @uses wp_remote_get()
    1540  *
    1541  * @param string $uri URI/URL of web page to retrieve.
    1542  * @return bool|string HTTP content. False on failure.
    1543  */
    1544 function wp_remote_fopen( $uri ) {
    1545         $parsed_url = @parse_url( $uri );
    1546 
    1547         if ( !$parsed_url || !is_array( $parsed_url ) )
    1548                 return false;
    1549 
    1550         $options = array();
    1551         $options['timeout'] = 10;
    1552 
    1553         $response = wp_remote_get( $uri, $options );
    1554 
    1555         if ( is_wp_error( $response ) )
    1556                 return false;
    1557 
    1558         return wp_remote_retrieve_body( $response );
    1559 }
    1560 
    1561 /**
    1562  * Set up the WordPress query.
    1563  *
    1564  * @since 2.0.0
    1565  *
    1566  * @param string $query_vars Default WP_Query arguments.
    1567  */
    1568 function wp( $query_vars = '' ) {
    1569         global $wp, $wp_query, $wp_the_query;
    1570         $wp->main( $query_vars );
    1571 
    1572         if ( !isset($wp_the_query) )
    1573                 $wp_the_query = $wp_query;
    1574 }
    1575 
    1576 /**
    1577  * Retrieve the description for the HTTP status.
    1578  *
    1579  * @since 2.3.0
    1580  *
    1581  * @param int $code HTTP status code.
    1582  * @return string Empty string if not found, or description if found.
    1583  */
    1584 function get_status_header_desc( $code ) {
    1585         global $wp_header_to_desc;
    1586 
    1587         $code = absint( $code );
    1588 
    1589         if ( !isset( $wp_header_to_desc ) ) {
    1590                 $wp_header_to_desc = array(
    1591                         100 => 'Continue',
    1592                         101 => 'Switching Protocols',
    1593                         102 => 'Processing',
    1594 
    1595                         200 => 'OK',
    1596                         201 => 'Created',
    1597                         202 => 'Accepted',
    1598                         203 => 'Non-Authoritative Information',
    1599                         204 => 'No Content',
    1600                         205 => 'Reset Content',
    1601                         206 => 'Partial Content',
    1602                         207 => 'Multi-Status',
    1603                         226 => 'IM Used',
    1604 
    1605                         300 => 'Multiple Choices',
    1606                         301 => 'Moved Permanently',
    1607                         302 => 'Found',
    1608                         303 => 'See Other',
    1609                         304 => 'Not Modified',
    1610                         305 => 'Use Proxy',
    1611                         306 => 'Reserved',
    1612                         307 => 'Temporary Redirect',
    1613 
    1614                         400 => 'Bad Request',
    1615                         401 => 'Unauthorized',
    1616                         402 => 'Payment Required',
    1617                         403 => 'Forbidden',
    1618                         404 => 'Not Found',
    1619                         405 => 'Method Not Allowed',
    1620                         406 => 'Not Acceptable',
    1621                         407 => 'Proxy Authentication Required',
    1622                         408 => 'Request Timeout',
    1623                         409 => 'Conflict',
    1624                         410 => 'Gone',
    1625                         411 => 'Length Required',
    1626                         412 => 'Precondition Failed',
    1627                         413 => 'Request Entity Too Large',
    1628                         414 => 'Request-URI Too Long',
    1629                         415 => 'Unsupported Media Type',
    1630                         416 => 'Requested Range Not Satisfiable',
    1631                         417 => 'Expectation Failed',
    1632                         422 => 'Unprocessable Entity',
    1633                         423 => 'Locked',
    1634                         424 => 'Failed Dependency',
    1635                         426 => 'Upgrade Required',
    1636 
    1637                         500 => 'Internal Server Error',
    1638                         501 => 'Not Implemented',
    1639                         502 => 'Bad Gateway',
    1640                         503 => 'Service Unavailable',
    1641                         504 => 'Gateway Timeout',
    1642                         505 => 'HTTP Version Not Supported',
    1643                         506 => 'Variant Also Negotiates',
    1644                         507 => 'Insufficient Storage',
    1645                         510 => 'Not Extended'
    1646                 );
    1647         }
    1648 
    1649         if ( isset( $wp_header_to_desc[$code] ) )
    1650                 return $wp_header_to_desc[$code];
    1651         else
    1652                 return '';
    1653 }
    1654 
    1655 /**
    1656  * Set HTTP status header.
    1657  *
    1658  * @since 2.0.0
    1659  * @uses apply_filters() Calls 'status_header' on status header string, HTTP
    1660  *              HTTP code, HTTP code description, and protocol string as separate
    1661  *              parameters.
    1662  *
    1663  * @param int $header HTTP status code
    1664  * @return unknown
    1665  */
    1666 function status_header( $header ) {
    1667         $text = get_status_header_desc( $header );
    1668 
    1669         if ( empty( $text ) )
    1670                 return false;
    1671 
    1672         $protocol = $_SERVER["SERVER_PROTOCOL"];
    1673         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
    1674                 $protocol = 'HTTP/1.0';
    1675         $status_header = "$protocol $header $text";
    1676         if ( function_exists( 'apply_filters' ) )
    1677                 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
    1678 
    1679         return @header( $status_header, true, $header );
    1680 }
    1681 
    1682 /**
    1683  * Gets the header information to prevent caching.
    1684  *
    1685  * The several different headers cover the different ways cache prevention is handled
    1686  * by different browsers
    1687  *
    1688  * @since 2.8.0
    1689  *
    1690  * @uses apply_filters()
    1691  * @return array The associative array of header names and field values.
    1692  */
    1693 function wp_get_nocache_headers() {
    1694         $headers = array(
    1695                 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
    1696                 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
    1697                 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
    1698                 'Pragma' => 'no-cache',
    1699         );
    1700 
    1701         if ( function_exists('apply_filters') ) {
    1702                 $headers = (array) apply_filters('nocache_headers', $headers);
    1703         }
    1704         return $headers;
    1705 }
    1706 
    1707 /**
    1708  * Sets the headers to prevent caching for the different browsers.
    1709  *
    1710  * Different browsers support different nocache headers, so several headers must
    1711  * be sent so that all of them get the point that no caching should occur.
    1712  *
    1713  * @since 2.0.0
    1714  * @uses wp_get_nocache_headers()
    1715  */
    1716 function nocache_headers() {
    1717         $headers = wp_get_nocache_headers();
    1718         foreach( $headers as $name => $field_value )
    1719                 @header("{$name}: {$field_value}");
    1720 }
    1721 
    1722 /**
    1723  * Set the headers for caching for 10 days with JavaScript content type.
    1724  *
    1725  * @since 2.1.0
    1726  */
    1727 function cache_javascript_headers() {
    1728         $expiresOffset = 864000; // 10 days
    1729         header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
    1730         header( "Vary: Accept-Encoding" ); // Handle proxies
    1731         header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
    1732 }
    1733 
    1734 /**
    1735  * Retrieve the number of database queries during the WordPress execution.
    1736  *
    1737  * @since 2.0.0
    1738  *
    1739  * @return int Number of database queries
    1740  */
    1741 function get_num_queries() {
    1742         global $wpdb;
    1743         return $wpdb->num_queries;
    1744 }
    1745 
    1746 /**
    1747  * Whether input is yes or no. Must be 'y' to be true.
    1748  *
    1749  * @since 1.0.0
    1750  *
    1751  * @param string $yn Character string containing either 'y' or 'n'
    1752  * @return bool True if yes, false on anything else
    1753  */
    1754 function bool_from_yn( $yn ) {
    1755         return ( strtolower( $yn ) == 'y' );
    1756 }
    1757 
    1758 /**
    1759  * Loads the feed template from the use of an action hook.
    1760  *
    1761  * If the feed action does not have a hook, then the function will die with a
    1762  * message telling the visitor that the feed is not valid.
    1763  *
    1764  * It is better to only have one hook for each feed.
    1765  *
    1766  * @since 2.1.0
    1767  * @uses $wp_query Used to tell if the use a comment feed.
    1768  * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
    1769  */
    1770 function do_feed() {
    1771         global $wp_query;
    1772 
    1773         $feed = get_query_var( 'feed' );
    1774 
    1775         // Remove the pad, if present.
    1776         $feed = preg_replace( '/^_+/', '', $feed );
    1777 
    1778         if ( $feed == '' || $feed == 'feed' )
    1779                 $feed = get_default_feed();
    1780 
    1781         $hook = 'do_feed_' . $feed;
    1782         if ( !has_action($hook) ) {
    1783                 $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
    1784                 wp_die( $message, '', array( 'response' => 404 ) );
    1785         }
    1786 
    1787         do_action( $hook, $wp_query->is_comment_feed );
    1788 }
    1789 
    1790 /**
    1791  * Load the RDF RSS 0.91 Feed template.
    1792  *
    1793  * @since 2.1.0
    1794  */
    1795 function do_feed_rdf() {
    1796         load_template( ABSPATH . WPINC . '/feed-rdf.php' );
    1797 }
    1798 
    1799 /**
    1800  * Load the RSS 1.0 Feed Template.
    1801  *
    1802  * @since 2.1.0
    1803  */
    1804 function do_feed_rss() {
    1805         load_template( ABSPATH . WPINC . '/feed-rss.php' );
    1806 }
    1807 
    1808 /**
    1809  * Load either the RSS2 comment feed or the RSS2 posts feed.
    1810  *
    1811  * @since 2.1.0
    1812  *
    1813  * @param bool $for_comments True for the comment feed, false for normal feed.
    1814  */
    1815 function do_feed_rss2( $for_comments ) {
    1816         if ( $for_comments )
    1817                 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
    1818         else
    1819                 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
    1820 }
    1821 
    1822 /**
    1823  * Load either Atom comment feed or Atom posts feed.
    1824  *
    1825  * @since 2.1.0
    1826  *
    1827  * @param bool $for_comments True for the comment feed, false for normal feed.
    1828  */
    1829 function do_feed_atom( $for_comments ) {
    1830         if ($for_comments)
    1831                 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
    1832         else
    1833                 load_template( ABSPATH . WPINC . '/feed-atom.php' );
    1834 }
    1835 
    1836 /**
    1837  * Display the robots.txt file content.
    1838  *
    1839  * The echo content should be with usage of the permalinks or for creating the
    1840  * robots.txt file.
    1841  *
    1842  * @since 2.1.0
    1843  * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
    1844  */
    1845 function do_robots() {
    1846         header( 'Content-Type: text/plain; charset=utf-8' );
    1847 
    1848         do_action( 'do_robotstxt' );
    1849 
    1850         $output = "User-agent: *\n";
    1851         $public = get_option( 'blog_public' );
    1852         if ( '0' == $public ) {
    1853                 $output .= "Disallow: /\n";
    1854         } else {
    1855                 $site_url = parse_url( site_url() );
    1856                 $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
    1857                 $output .= "Disallow: $path/wp-admin/\n";
    1858                 $output .= "Disallow: $path/wp-includes/\n";
    1859         }
    1860 
    1861         echo apply_filters('robots_txt', $output, $public);
    1862 }
    1863 
    1864 /**
    1865  * Test whether blog is already installed.
    1866  *
    1867  * The cache will be checked first. If you have a cache plugin, which saves the
    1868  * cache values, then this will work. If you use the default WordPress cache,
    1869  * and the database goes away, then you might have problems.
    1870  *
    1871  * Checks for the option siteurl for whether WordPress is installed.
    1872  *
    1873  * @since 2.1.0
    1874  * @uses $wpdb
    1875  *
    1876  * @return bool Whether blog is already installed.
    1877  */
    1878 function is_blog_installed() {
    1879         global $wpdb;
    1880 
    1881         // Check cache first. If options table goes away and we have true cached, oh well.
    1882         if ( wp_cache_get( 'is_blog_installed' ) )
    1883                 return true;
    1884 
    1885         $suppress = $wpdb->suppress_errors();
    1886         if ( ! defined( 'WP_INSTALLING' ) ) {
    1887                 $alloptions = wp_load_alloptions();
    1888         }
    1889         // If siteurl is not set to autoload, check it specifically
    1890         if ( !isset( $alloptions['siteurl'] ) )
    1891                 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
    1892         else
    1893                 $installed = $alloptions['siteurl'];
    1894         $wpdb->suppress_errors( $suppress );
    1895 
    1896         $installed = !empty( $installed );
    1897         wp_cache_set( 'is_blog_installed', $installed );
    1898 
    1899         if ( $installed )
    1900                 return true;
    1901 
    1902         // If visiting repair.php, return true and let it take over.
    1903         if ( defined( 'WP_REPAIRING' ) )
    1904                 return true;
    1905 
    1906         $suppress = $wpdb->suppress_errors();
    1907 
    1908         // Loop over the WP tables. If none exist, then scratch install is allowed.
    1909         // If one or more exist, suggest table repair since we got here because the options
    1910         // table could not be accessed.
    1911         $wp_tables = $wpdb->tables();
    1912         foreach ( $wp_tables as $table ) {
    1913                 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
    1914                 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
    1915                         continue;
    1916                 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
    1917                         continue;
    1918 
    1919                 if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
    1920                         continue;
    1921 
    1922                 // One or more tables exist. We are insane.
    1923 
    1924                 // Die with a DB error.
    1925                 $wpdb->error = sprintf( /*WP_I18N_NO_TABLES*/'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.'/*/WP_I18N_NO_TABLES*/, 'maint/repair.php?referrer=is_blog_installed' );
    1926                 dead_db();
    1927         }
    1928 
    1929         $wpdb->suppress_errors( $suppress );
    1930 
    1931         wp_cache_set( 'is_blog_installed', false );
    1932 
    1933         return false;
    1934 }
    1935 
    1936 /**
    1937  * Retrieve URL with nonce added to URL query.
    1938  *
    1939  * @package WordPress
    1940  * @subpackage Security
    1941  * @since 2.0.4
    1942  *
    1943  * @param string $actionurl URL to add nonce action
    1944  * @param string $action Optional. Nonce action name
    1945  * @return string URL with nonce action added.
    1946  */
    1947 function wp_nonce_url( $actionurl, $action = -1 ) {
    1948         $actionurl = str_replace( '&amp;', '&', $actionurl );
    1949         return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
    1950 }
    1951 
    1952 /**
    1953  * Retrieve or display nonce hidden field for forms.
    1954  *
    1955  * The nonce field is used to validate that the contents of the form came from
    1956  * the location on the current site and not somewhere else. The nonce does not
    1957  * offer absolute protection, but should protect against most cases. It is very
    1958  * important to use nonce field in forms.
    1959  *
    1960  * The $action and $name are optional, but if you want to have better security,
    1961  * it is strongly suggested to set those two parameters. It is easier to just
    1962  * call the function without any parameters, because validation of the nonce
    1963  * doesn't require any parameters, but since crackers know what the default is
    1964  * it won't be difficult for them to find a way around your nonce and cause
    1965  * damage.
    1966  *
    1967  * The input name will be whatever $name value you gave. The input value will be
    1968  * the nonce creation value.
    1969  *
    1970  * @package WordPress
    1971  * @subpackage Security
    1972  * @since 2.0.4
    1973  *
    1974  * @param string $action Optional. Action name.
    1975  * @param string $name Optional. Nonce name.
    1976  * @param bool $referer Optional, default true. Whether to set the referer field for validation.
    1977  * @param bool $echo Optional, default true. Whether to display or return hidden form field.
    1978  * @return string Nonce field.
    1979  */
    1980 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
    1981         $name = esc_attr( $name );
    1982         $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
    1983 
    1984         if ( $referer )
    1985                 $nonce_field .= wp_referer_field( false );
    1986 
    1987         if ( $echo )
    1988                 echo $nonce_field;
    1989 
    1990         return $nonce_field;
    1991 }
    1992 
    1993 /**
    1994  * Retrieve or display referer hidden field for forms.
    1995  *
    1996  * The referer link is the current Request URI from the server super global. The
    1997  * input name is '_wp_http_referer', in case you wanted to check manually.
    1998  *
    1999  * @package WordPress
    2000  * @subpackage Security
    2001  * @since 2.0.4
    2002  *
    2003  * @param bool $echo Whether to echo or return the referer field.
    2004  * @return string Referer field.
    2005  */
    2006 function wp_referer_field( $echo = true ) {
    2007         $ref = esc_attr( $_SERVER['REQUEST_URI'] );
    2008         $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
    2009 
    2010         if ( $echo )
    2011                 echo $referer_field;
    2012         return $referer_field;
    2013 }
    2014 
    2015 /**
    2016  * Retrieve or display original referer hidden field for forms.
    2017  *
    2018  * The input name is '_wp_original_http_referer' and will be either the same
    2019  * value of {@link wp_referer_field()}, if that was posted already or it will
    2020  * be the current page, if it doesn't exist.
    2021  *
    2022  * @package WordPress
    2023  * @subpackage Security
    2024  * @since 2.0.4
    2025  *
    2026  * @param bool $echo Whether to echo the original http referer
    2027  * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
    2028  * @return string Original referer field.
    2029  */
    2030 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
    2031         $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
    2032         $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
    2033         $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
    2034         if ( $echo )
    2035                 echo $orig_referer_field;
    2036         return $orig_referer_field;
    2037 }
    2038 
    2039 /**
    2040  * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
    2041  * as the current request URL, will return false.
    2042  *
    2043  * @package WordPress
    2044  * @subpackage Security
    2045  * @since 2.0.4
    2046  *
    2047  * @return string|bool False on failure. Referer URL on success.
    2048  */
    2049 function wp_get_referer() {
    2050         $ref = false;
    2051         if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
    2052                 $ref = $_REQUEST['_wp_http_referer'];
    2053         else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
    2054                 $ref = $_SERVER['HTTP_REFERER'];
    2055 
    2056         if ( $ref && $ref !== $_SERVER['REQUEST_URI'] )
    2057                 return $ref;
    2058         return false;
    2059 }
    2060 
    2061 /**
    2062  * Retrieve original referer that was posted, if it exists.
    2063  *
    2064  * @package WordPress
    2065  * @subpackage Security
    2066  * @since 2.0.4
    2067  *
    2068  * @return string|bool False if no original referer or original referer if set.
    2069  */
    2070 function wp_get_original_referer() {
    2071         if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
    2072                 return $_REQUEST['_wp_original_http_referer'];
    2073         return false;
    2074 }
    2075 
    2076 /**
    2077  * Recursive directory creation based on full path.
    2078  *
    2079  * Will attempt to set permissions on folders.
    2080  *
    2081  * @since 2.0.1
    2082  *
    2083  * @param string $target Full path to attempt to create.
    2084  * @return bool Whether the path was created. True if path already exists.
    2085  */
    2086 function wp_mkdir_p( $target ) {
    2087         // from php.net/mkdir user contributed notes
    2088         $target = str_replace( '//', '/', $target );
    2089 
    2090         // safe mode fails with a trailing slash under certain PHP versions.
    2091         $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
    2092         if ( empty($target) )
    2093                 $target = '/';
    2094 
    2095         if ( file_exists( $target ) )
    2096                 return @is_dir( $target );
    2097 
    2098         // Attempting to create the directory may clutter up our display.
    2099         if ( @mkdir( $target ) ) {
    2100                 $stat = @stat( dirname( $target ) );
    2101                 $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
    2102                 @chmod( $target, $dir_perms );
    2103                 return true;
    2104         } elseif ( is_dir( dirname( $target ) ) ) {
    2105                         return false;
    2106         }
    2107 
    2108         // If the above failed, attempt to create the parent node, then try again.
    2109         if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
    2110                 return wp_mkdir_p( $target );
    2111 
    2112         return false;
    2113 }
    2114 
    2115 /**
    2116  * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
    2117  *
    2118  * @since 2.5.0
    2119  *
    2120  * @param string $path File path
    2121  * @return bool True if path is absolute, false is not absolute.
    2122  */
    2123 function path_is_absolute( $path ) {
    2124         // this is definitive if true but fails if $path does not exist or contains a symbolic link
    2125         if ( realpath($path) == $path )
    2126                 return true;
    2127 
    2128         if ( strlen($path) == 0 || $path[0] == '.' )
    2129                 return false;
    2130 
    2131         // windows allows absolute paths like this
    2132         if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
    2133                 return true;
    2134 
    2135         // a path starting with / or \ is absolute; anything else is relative
    2136         return ( $path[0] == '/' || $path[0] == '\\' );
    2137 }
    2138 
    2139 /**
    2140  * Join two filesystem paths together (e.g. 'give me $path relative to $base').
    2141  *
    2142  * If the $path is absolute, then it the full path is returned.
    2143  *
    2144  * @since 2.5.0
    2145  *
    2146  * @param string $base
    2147  * @param string $path
    2148  * @return string The path with the base or absolute path.
    2149  */
    2150 function path_join( $base, $path ) {
    2151         if ( path_is_absolute($path) )
    2152                 return $path;
    2153 
    2154         return rtrim($base, '/') . '/' . ltrim($path, '/');
    2155 }
    2156 
    2157 /**
    2158  * Determines a writable directory for temporary files.
    2159  * Function's preference is to WP_CONTENT_DIR followed by the return value of <code>sys_get_temp_dir()</code>, before finally defaulting to /tmp/
    2160  *
    2161  * In the event that this function does not find a writable location, It may be overridden by the <code>WP_TEMP_DIR</code> constant in your <code>wp-config.php</code> file.
    2162  *
    2163  * @since 2.5.0
    2164  *
    2165  * @return string Writable temporary directory
    2166  */
    2167 function get_temp_dir() {
    2168         static $temp;
    2169         if ( defined('WP_TEMP_DIR') )
    2170                 return trailingslashit(WP_TEMP_DIR);
    2171 
    2172         if ( $temp )
    2173                 return trailingslashit($temp);
    2174 
    2175         $temp = WP_CONTENT_DIR . '/';
    2176         if ( is_dir($temp) && @is_writable($temp) )
    2177                 return $temp;
    2178 
    2179         if  ( function_exists('sys_get_temp_dir') ) {
    2180                 $temp = sys_get_temp_dir();
    2181                 if ( @is_writable($temp) )
    2182                         return trailingslashit($temp);
    2183         }
    2184 
    2185         $temp = ini_get('upload_tmp_dir');
    2186         if ( is_dir($temp) && @is_writable($temp) )
    2187                 return trailingslashit($temp);
    2188 
    2189         $temp = '/tmp/';
    2190         return $temp;
    2191 }
    2192 
    2193 /**
    2194  * Get an array containing the current upload directory's path and url.
    2195  *
    2196  * Checks the 'upload_path' option, which should be from the web root folder,
    2197  * and if it isn't empty it will be used. If it is empty, then the path will be
    2198  * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
    2199  * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
    2200  *
    2201  * The upload URL path is set either by the 'upload_url_path' option or by using
    2202  * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
    2203  *
    2204  * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
    2205  * the administration settings panel), then the time will be used. The format
    2206  * will be year first and then month.
    2207  *
    2208  * If the path couldn't be created, then an error will be returned with the key
    2209  * 'error' containing the error message. The error suggests that the parent
    2210  * directory is not writable by the server.
    2211  *
    2212  * On success, the returned array will have many indices:
    2213  * 'path' - base directory and sub directory or full path to upload directory.
    2214  * 'url' - base url and sub directory or absolute URL to upload directory.
    2215  * 'subdir' - sub directory if uploads use year/month folders option is on.
    2216  * 'basedir' - path without subdir.
    2217  * 'baseurl' - URL path without subdir.
    2218  * 'error' - set to false.
    2219  *
    2220  * @since 2.0.0
    2221  * @uses apply_filters() Calls 'upload_dir' on returned array.
    2222  *
    2223  * @param string $time Optional. Time formatted in 'yyyy/mm'.
    2224  * @return array See above for description.
    2225  */
    2226 function wp_upload_dir( $time = null ) {
    2227         global $switched;
    2228         $siteurl = get_option( 'siteurl' );
    2229         $upload_path = get_option( 'upload_path' );
    2230         $upload_path = trim($upload_path);
    2231         $main_override = is_multisite() && defined( 'MULTISITE' ) && is_main_site();
    2232         if ( empty($upload_path) ) {
    2233                 $dir = WP_CONTENT_DIR . '/uploads';
    2234         } else {
    2235                 $dir = $upload_path;
    2236                 if ( 'wp-content/uploads' == $upload_path ) {
    2237                         $dir = WP_CONTENT_DIR . '/uploads';
    2238                 } elseif ( 0 !== strpos($dir, ABSPATH) ) {
    2239                         // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
    2240                         $dir = path_join( ABSPATH, $dir );
    2241                 }
    2242         }
    2243 
    2244         if ( !$url = get_option( 'upload_url_path' ) ) {
    2245                 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
    2246                         $url = WP_CONTENT_URL . '/uploads';
    2247                 else
    2248                         $url = trailingslashit( $siteurl ) . $upload_path;
    2249         }
    2250 
    2251         if ( defined('UPLOADS') && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
    2252                 $dir = ABSPATH . UPLOADS;
    2253                 $url = trailingslashit( $siteurl ) . UPLOADS;
    2254         }
    2255 
    2256         if ( is_multisite() && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
    2257                 if ( defined( 'BLOGUPLOADDIR' ) )
    2258                         $dir = untrailingslashit(BLOGUPLOADDIR);
    2259                 $url = str_replace( UPLOADS, 'files', $url );
    2260         }
    2261 
    2262         $bdir = $dir;
    2263         $burl = $url;
    2264 
    2265         $subdir = '';
    2266         if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
    2267                 // Generate the yearly and monthly dirs
    2268                 if ( !$time )
    2269                         $time = current_time( 'mysql' );
    2270                 $y = substr( $time, 0, 4 );
    2271                 $m = substr( $time, 5, 2 );
    2272                 $subdir = "/$y/$m";
    2273         }
    2274 
    2275         $dir .= $subdir;
    2276         $url .= $subdir;
    2277 
    2278         $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
    2279 
    2280         // Make sure we have an uploads dir
    2281         if ( ! wp_mkdir_p( $uploads['path'] ) ) {
    2282                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
    2283                 return array( 'error' => $message );
    2284         }
    2285 
    2286         return $uploads;
    2287 }
    2288 
    2289 /**
    2290  * Get a filename that is sanitized and unique for the given directory.
    2291  *
    2292  * If the filename is not unique, then a number will be added to the filename
    2293  * before the extension, and will continue adding numbers until the filename is
    2294  * unique.
    2295  *
    2296  * The callback is passed three parameters, the first one is the directory, the
    2297  * second is the filename, and the third is the extension.
    2298  *
    2299  * @since 2.5.0
    2300  *
    2301  * @param string $dir
    2302  * @param string $filename
    2303  * @param mixed $unique_filename_callback Callback.
    2304  * @return string New filename, if given wasn't unique.
    2305  */
    2306 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
    2307         // sanitize the file name before we begin processing
    2308         $filename = sanitize_file_name($filename);
    2309 
    2310         // separate the filename into a name and extension
    2311         $info = pathinfo($filename);
    2312         $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
    2313         $name = basename($filename, $ext);
    2314 
    2315         // edge case: if file is named '.ext', treat as an empty name
    2316         if ( $name === $ext )
    2317                 $name = '';
    2318 
    2319         // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
    2320         if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
    2321                 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
    2322         } else {
    2323                 $number = '';
    2324 
    2325                 // change '.ext' to lower case
    2326                 if ( $ext && strtolower($ext) != $ext ) {
    2327                         $ext2 = strtolower($ext);
    2328                         $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
    2329 
    2330                         // check for both lower and upper case extension or image sub-sizes may be overwritten
    2331                         while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
    2332                                 $new_number = $number + 1;
    2333                                 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
    2334                                 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
    2335                                 $number = $new_number;
    2336                         }
    2337                         return $filename2;
    2338                 }
    2339 
    2340                 while ( file_exists( $dir . "/$filename" ) ) {
    2341                         if ( '' == "$number$ext" )
    2342                                 $filename = $filename . ++$number . $ext;
    2343                         else
    2344                                 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
    2345                 }
    2346         }
    2347 
    2348         return $filename;
    2349 }
    2350 
    2351 /**
    2352  * Create a file in the upload folder with given content.
    2353  *
    2354  * If there is an error, then the key 'error' will exist with the error message.
    2355  * If success, then the key 'file' will have the unique file path, the 'url' key
    2356  * will have the link to the new file. and the 'error' key will be set to false.
    2357  *
    2358  * This function will not move an uploaded file to the upload folder. It will
    2359  * create a new file with the content in $bits parameter. If you move the upload
    2360  * file, read the content of the uploaded file, and then you can give the
    2361  * filename and content to this function, which will add it to the upload
    2362  * folder.
    2363  *
    2364  * The permissions will be set on the new file automatically by this function.
    2365  *
    2366  * @since 2.0.0
    2367  *
    2368  * @param string $name
    2369  * @param null $deprecated Never used. Set to null.
    2370  * @param mixed $bits File content
    2371  * @param string $time Optional. Time formatted in 'yyyy/mm'.
    2372  * @return array
    2373  */
    2374 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
    2375         if ( !empty( $deprecated ) )
    2376                 _deprecated_argument( __FUNCTION__, '2.0' );
    2377 
    2378         if ( empty( $name ) )
    2379                 return array( 'error' => __( 'Empty filename' ) );
    2380 
    2381         $wp_filetype = wp_check_filetype( $name );
    2382         if ( !$wp_filetype['ext'] )
    2383                 return array( 'error' => __( 'Invalid file type' ) );
    2384 
    2385         $upload = wp_upload_dir( $time );
    2386 
    2387         if ( $upload['error'] !== false )
    2388                 return $upload;
    2389 
    2390         $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
    2391         if ( !is_array( $upload_bits_error ) ) {
    2392                 $upload[ 'error' ] = $upload_bits_error;
    2393                 return $upload;
    2394         }
    2395 
    2396         $filename = wp_unique_filename( $upload['path'], $name );
    2397 
    2398         $new_file = $upload['path'] . "/$filename";
    2399         if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
    2400                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
    2401                 return array( 'error' => $message );
    2402         }
    2403 
    2404         $ifp = @ fopen( $new_file, 'wb' );
    2405         if ( ! $ifp )
    2406                 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
    2407 
    2408         @fwrite( $ifp, $bits );
    2409         fclose( $ifp );
    2410         clearstatcache();
    2411 
    2412         // Set correct file permissions
    2413         $stat = @ stat( dirname( $new_file ) );
    2414         $perms = $stat['mode'] & 0007777;
    2415         $perms = $perms & 0000666;
    2416         @ chmod( $new_file, $perms );
    2417         clearstatcache();
    2418 
    2419         // Compute the URL
    2420         $url = $upload['url'] . "/$filename";
    2421 
    2422         return array( 'file' => $new_file, 'url' => $url, 'error' => false );
    2423 }
    2424 
    2425 /**
    2426  * Retrieve the file type based on the extension name.
    2427  *
    2428  * @package WordPress
    2429  * @since 2.5.0
    2430  * @uses apply_filters() Calls 'ext2type' hook on default supported types.
    2431  *
    2432  * @param string $ext The extension to search.
    2433  * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
    2434  */
    2435 function wp_ext2type( $ext ) {
    2436         $ext2type = apply_filters( 'ext2type', array(
    2437                 'audio'       => array( 'aac', 'ac3',  'aif',  'aiff', 'm3a',  'm4a',   'm4b', 'mka', 'mp1', 'mp2',  'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
    2438                 'video'       => array( 'asf', 'avi',  'divx', 'dv',   'flv',  'm4v',   'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt',  'rm', 'vob', 'wmv' ),
    2439                 'document'    => array( 'doc', 'docx', 'docm', 'dotm', 'odt',  'pages', 'pdf', 'rtf', 'wp',  'wpd' ),
    2440                 'spreadsheet' => array( 'numbers',     'ods',  'xls',  'xlsx', 'xlsb',  'xlsm' ),
    2441                 'interactive' => array( 'key', 'ppt',  'pptx', 'pptm', 'odp',  'swf' ),
    2442                 'text'        => array( 'asc', 'csv',  'tsv',  'txt' ),
    2443                 'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit', 'sqx', 'tar', 'tgz',  'zip', '7z' ),
    2444                 'code'        => array( 'css', 'htm',  'html', 'php',  'js' ),
    2445         ));
    2446         foreach ( $ext2type as $type => $exts )
    2447                 if ( in_array( $ext, $exts ) )
    2448                         return $type;
    2449 }
    2450 
    2451 /**
    2452  * Retrieve the file type from the file name.
    2453  *
    2454  * You can optionally define the mime array, if needed.
    2455  *
    2456  * @since 2.0.4
    2457  *
    2458  * @param string $filename File name or path.
    2459  * @param array $mimes Optional. Key is the file extension with value as the mime type.
    2460  * @return array Values with extension first and mime type.
    2461  */
    2462 function wp_check_filetype( $filename, $mimes = null ) {
    2463         if ( empty($mimes) )
    2464                 $mimes = get_allowed_mime_types();
    2465         $type = false;
    2466         $ext = false;
    2467 
    2468         foreach ( $mimes as $ext_preg => $mime_match ) {
    2469                 $ext_preg = '!\.(' . $ext_preg . ')$!i';
    2470                 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
    2471                         $type = $mime_match;
    2472                         $ext = $ext_matches[1];
    2473                         break;
    2474                 }
    2475         }
    2476 
    2477         return compact( 'ext', 'type' );
    2478 }
    2479 
    2480 /**
    2481  * Attempt to determine the real file type of a file.
    2482  * If unable to, the file name extension will be used to determine type.
    2483  *
    2484  * If it's determined that the extension does not match the file's real type,
    2485  * then the "proper_filename" value will be set with a proper filename and extension.
    2486  *
    2487  * Currently this function only supports validating images known to getimagesize().
    2488  *
    2489  * @since 3.0.0
    2490  *
    2491  * @param string $file Full path to the image.
    2492  * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
    2493  * @param array $mimes Optional. Key is the file extension with value as the mime type.
    2494  * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
    2495  */
    2496 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
    2497 
    2498         $proper_filename = false;
    2499 
    2500         // Do basic extension validation and MIME mapping
    2501         $wp_filetype = wp_check_filetype( $filename, $mimes );
    2502         extract( $wp_filetype );
    2503 
    2504         // We can't do any further validation without a file to work with
    2505         if ( ! file_exists( $file ) )
    2506                 return compact( 'ext', 'type', 'proper_filename' );
    2507 
    2508         // We're able to validate images using GD
    2509         if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
    2510 
    2511                 // Attempt to figure out what type of image it actually is
    2512                 $imgstats = @getimagesize( $file );
    2513 
    2514                 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
    2515                 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
    2516                         // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
    2517                         // You shouldn't need to use this filter, but it's here just in case
    2518                         $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
    2519                                 'image/jpeg' => 'jpg',
    2520                                 'image/png'  => 'png',
    2521                                 'image/gif'  => 'gif',
    2522                                 'image/bmp'  => 'bmp',
    2523                                 'image/tiff' => 'tif',
    2524                         ) );
    2525 
    2526                         // Replace whatever is after the last period in the filename with the correct extension
    2527                         if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
    2528                                 $filename_parts = explode( '.', $filename );
    2529                                 array_pop( $filename_parts );
    2530                                 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
    2531                                 $new_filename = implode( '.', $filename_parts );
    2532 
    2533                                 if ( $new_filename != $filename )
    2534                                         $proper_filename = $new_filename; // Mark that it changed
    2535 
    2536                                 // Redefine the extension / MIME
    2537                                 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
    2538                                 extract( $wp_filetype );
    2539                         }
    2540                 }
    2541         }
    2542 
    2543         // Let plugins try and validate other types of files
    2544         // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
    2545         return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
    2546 }
    2547 
    2548 /**
    2549  * Retrieve list of allowed mime types and file extensions.
    2550  *
    2551  * @since 2.8.6
    2552  *
    2553  * @return array Array of mime types keyed by the file extension regex corresponding to those types.
    2554  */
    2555 function get_allowed_mime_types() {
    2556         static $mimes = false;
    2557 
    2558         if ( !$mimes ) {
    2559                 // Accepted MIME types are set here as PCRE unless provided.
    2560                 $mimes = apply_filters( 'upload_mimes', array(
    2561                 'jpg|jpeg|jpe' => 'image/jpeg',
    2562                 'gif' => 'image/gif',
    2563                 'png' => 'image/png',
    2564                 'bmp' => 'image/bmp',
    2565                 'tif|tiff' => 'image/tiff',
    2566                 'ico' => 'image/x-icon',
    2567                 'asf|asx|wax|wmv|wmx' => 'video/asf',
    2568                 'avi' => 'video/avi',
    2569                 'divx' => 'video/divx',
    2570                 'flv' => 'video/x-flv',
    2571                 'mov|qt' => 'video/quicktime',
    2572                 'mpeg|mpg|mpe' => 'video/mpeg',
    2573                 'txt|asc|c|cc|h' => 'text/plain',
    2574                 'csv' => 'text/csv',
    2575                 'tsv' => 'text/tab-separated-values',
    2576                 'ics' => 'text/calendar',
    2577                 'rtx' => 'text/richtext',
    2578                 'css' => 'text/css',
    2579                 'htm|html' => 'text/html',
    2580                 'mp3|m4a|m4b' => 'audio/mpeg',
    2581                 'mp4|m4v' => 'video/mp4',
    2582                 'ra|ram' => 'audio/x-realaudio',
    2583                 'wav' => 'audio/wav',
    2584                 'ogg|oga' => 'audio/ogg',
    2585                 'ogv' => 'video/ogg',
    2586                 'mid|midi' => 'audio/midi',
    2587                 'wma' => 'audio/wma',
    2588                 'mka' => 'audio/x-matroska',
    2589                 'mkv' => 'video/x-matroska',
    2590                 'rtf' => 'application/rtf',
    2591                 'js' => 'application/javascript',
    2592                 'pdf' => 'application/pdf',
    2593                 'doc|docx' => 'application/msword',
    2594                 'pot|pps|ppt|pptx|ppam|pptm|sldm|ppsm|potm' => 'application/vnd.ms-powerpoint',
    2595                 'wri' => 'application/vnd.ms-write',
    2596                 'xla|xls|xlsx|xlt|xlw|xlam|xlsb|xlsm|xltm' => 'application/vnd.ms-excel',
    2597                 'mdb' => 'application/vnd.ms-access',
    2598                 'mpp' => 'application/vnd.ms-project',
    2599                 'docm|dotm' => 'application/vnd.ms-word',
    2600                 'pptx|sldx|ppsx|potx' => 'application/vnd.openxmlformats-officedocument.presentationml',
    2601                 'xlsx|xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml',
    2602                 'docx|dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml',
    2603                 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
    2604                 'swf' => 'application/x-shockwave-flash',
    2605                 'class' => 'application/java',
    2606                 'tar' => 'application/x-tar',
    2607                 'zip' => 'application/zip',
    2608                 'gz|gzip' => 'application/x-gzip',
    2609                 'rar' => 'application/rar',
    2610                 '7z' => 'application/x-7z-compressed',
    2611                 'exe' => 'application/x-msdownload',
    2612                 // openoffice formats
    2613                 'odt' => 'application/vnd.oasis.opendocument.text',
    2614                 'odp' => 'application/vnd.oasis.opendocument.presentation',
    2615                 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
    2616                 'odg' => 'application/vnd.oasis.opendocument.graphics',
    2617                 'odc' => 'application/vnd.oasis.opendocument.chart',
    2618                 'odb' => 'application/vnd.oasis.opendocument.database',
    2619                 'odf' => 'application/vnd.oasis.opendocument.formula',
    2620                 // wordperfect formats
    2621                 'wp|wpd' => 'application/wordperfect',
    2622                 ) );
    2623         }
    2624 
    2625         return $mimes;
    2626 }
    2627 
    2628 /**
    2629  * Retrieve nonce action "Are you sure" message.
    2630  *
    2631  * The action is split by verb and noun. The action format is as follows:
    2632  * verb-action_extra. The verb is before the first dash and has the format of
    2633  * letters and no spaces and numbers. The noun is after the dash and before the
    2634  * underscore, if an underscore exists. The noun is also only letters.
    2635  *
    2636  * The filter will be called for any action, which is not defined by WordPress.
    2637  * You may use the filter for your plugin to explain nonce actions to the user,
    2638  * when they get the "Are you sure?" message. The filter is in the format of
    2639  * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
    2640  * $noun replaced by the found noun. The two parameters that are given to the
    2641  * hook are the localized "Are you sure you want to do this?" message with the
    2642  * extra text (the text after the underscore).
    2643  *
    2644  * @package WordPress
    2645  * @subpackage Security
    2646  * @since 2.0.4
    2647  *
    2648  * @param string $action Nonce action.
    2649  * @return string Are you sure message.
    2650  */
    2651 function wp_explain_nonce( $action ) {
    2652         if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
    2653                 $verb = $matches[1];
    2654                 $noun = $matches[2];
    2655 
    2656                 $trans = array();
    2657                 $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
    2658 
    2659                 $trans['add']['category']      = array( __( 'Your attempt to add this category has failed.' ), false );
    2660                 $trans['delete']['category']   = array( __( 'Your attempt to delete this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
    2661                 $trans['update']['category']   = array( __( 'Your attempt to edit this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
    2662 
    2663                 $trans['delete']['comment']    = array( __( 'Your attempt to delete this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2664                 $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2665                 $trans['approve']['comment']   = array( __( 'Your attempt to approve this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2666                 $trans['update']['comment']    = array( __( 'Your attempt to edit this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2667                 $trans['bulk']['comments']     = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
    2668                 $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
    2669 
    2670                 $trans['add']['bookmark']      = array( __( 'Your attempt to add this link has failed.' ), false );
    2671                 $trans['delete']['bookmark']   = array( __( 'Your attempt to delete this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2672                 $trans['update']['bookmark']   = array( __( 'Your attempt to edit this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2673                 $trans['bulk']['bookmarks']    = array( __( 'Your attempt to bulk modify links has failed.' ), false );
    2674 
    2675                 $trans['add']['page']          = array( __( 'Your attempt to add this page has failed.' ), false );
    2676                 $trans['delete']['page']       = array( __( 'Your attempt to delete this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
    2677                 $trans['update']['page']       = array( __( 'Your attempt to edit this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
    2678 
    2679                 $trans['edit']['plugin']       = array( __( 'Your attempt to edit this plugin file: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2680                 $trans['activate']['plugin']   = array( __( 'Your attempt to activate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2681                 $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2682                 $trans['upgrade']['plugin']    = array( __( 'Your attempt to update this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2683 
    2684                 $trans['add']['post']          = array( __( 'Your attempt to add this post has failed.' ), false );
    2685                 $trans['delete']['post']       = array( __( 'Your attempt to delete this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
    2686                 $trans['update']['post']       = array( __( 'Your attempt to edit this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
    2687 
    2688                 $trans['add']['user']          = array( __( 'Your attempt to add this user has failed.' ), false );
    2689                 $trans['delete']['users']      = array( __( 'Your attempt to delete users has failed.' ), false );
    2690                 $trans['bulk']['users']        = array( __( 'Your attempt to bulk modify users has failed.' ), false );
    2691                 $trans['update']['user']       = array( __( 'Your attempt to edit this user: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
    2692                 $trans['update']['profile']    = array( __( 'Your attempt to modify the profile for: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
    2693 
    2694                 $trans['update']['options']    = array( __( 'Your attempt to edit your settings has failed.' ), false );
    2695                 $trans['update']['permalink']  = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
    2696                 $trans['edit']['file']         = array( __( 'Your attempt to edit this file: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2697                 $trans['edit']['theme']        = array( __( 'Your attempt to edit this theme file: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2698                 $trans['switch']['theme']      = array( __( 'Your attempt to switch to this theme: &#8220;%s&#8221; has failed.' ), 'use_id' );
    2699 
    2700                 $trans['log']['out']           = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
    2701 
    2702                 if ( isset( $trans[$verb][$noun] ) ) {
    2703                         if ( !empty( $trans[$verb][$noun][1] ) ) {
    2704                                 $lookup = $trans[$verb][$noun][1];
    2705                                 if ( isset($trans[$verb][$noun][2]) )
    2706                                         $lookup_value = $trans[$verb][$noun][2];
    2707                                 $object = $matches[4];
    2708                                 if ( 'use_id' != $lookup ) {
    2709                                         if ( isset( $lookup_value ) )
    2710                                                 $object = call_user_func( $lookup, $lookup_value, $object );
    2711                                         else
    2712                                                 $object = call_user_func( $lookup, $object );
    2713                                 }
    2714                                 return sprintf( $trans[$verb][$noun][0], esc_html($object) );
    2715                         } else {
    2716                                 return $trans[$verb][$noun][0];
    2717                         }
    2718                 }
    2719 
    2720                 return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), isset($matches[4]) ? $matches[4] : '' );
    2721         } else {
    2722                 return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
    2723         }
    2724 }
    2725 
    2726 /**
    2727  * Display "Are You Sure" message to confirm the action being taken.
    2728  *
    2729  * If the action has the nonce explain message, then it will be displayed along
    2730  * with the "Are you sure?" message.
    2731  *
    2732  * @package WordPress
    2733  * @subpackage Security
    2734  * @since 2.0.4
    2735  *
    2736  * @param string $action The nonce action.
    2737  */
    2738 function wp_nonce_ays( $action ) {
    2739         $title = __( 'WordPress Failure Notice' );
    2740         $html = esc_html( wp_explain_nonce( $action ) );
    2741         if ( 'log-out' == $action )
    2742                 $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
    2743         elseif ( wp_get_referer() )
    2744                 $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
    2745 
    2746         wp_die( $html, $title, array('response' => 403) );
    2747 }
    2748 
    2749 
    2750 /**
    2751  * Kill WordPress execution and display HTML message with error message.
    2752  *
    2753  * This function complements the die() PHP function. The difference is that
    2754  * HTML will be displayed to the user. It is recommended to use this function
    2755  * only, when the execution should not continue any further. It is not
    2756  * recommended to call this function very often and try to handle as many errors
    2757  * as possible silently.
    2758  *
    2759  * @since 2.0.4
    2760  *
    2761  * @param string $message Error message.
    2762  * @param string $title Error title.
    2763  * @param string|array $args Optional arguments to control behavior.
    2764  */
    2765 function wp_die( $message, $title = '', $args = array() ) {
    2766         if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
    2767                 die('-1');
    2768 
    2769         if ( function_exists( 'apply_filters' ) ) {
    2770                 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
    2771         } else {
    2772                 $function = '_default_wp_die_handler';
    2773         }
    2774 
    2775         call_user_func( $function, $message, $title, $args );
    2776 }
    2777 
    2778 /**
    2779  * Kill WordPress execution and display HTML message with error message.
    2780  *
    2781  * This is the default handler for wp_die if you want a custom one for your
    2782  * site then you can overload using the wp_die_handler filter in wp_die
    2783  *
    2784  * @since 3.0.0
    2785  * @access private
    2786  *
    2787  * @param string $message Error message.
    2788  * @param string $title Error title.
    2789  * @param string|array $args Optional arguments to control behavior.
    2790  */
    2791 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
    2792         $defaults = array( 'response' => 500 );
    2793         $r = wp_parse_args($args, $defaults);
    2794 
    2795         $have_gettext = function_exists('__');
    2796 
    2797         if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
    2798                 if ( empty( $title ) ) {
    2799                         $error_data = $message->get_error_data();
    2800                         if ( is_array( $error_data ) && isset( $error_data['title'] ) )
    2801                                 $title = $error_data['title'];
    2802                 }
    2803                 $errors = $message->get_error_messages();
    2804                 switch ( count( $errors ) ) :
    2805                 case 0 :
    2806                         $message = '';
    2807                         break;
    2808                 case 1 :
    2809                         $message = "<p>{$errors[0]}</p>";
    2810                         break;
    2811                 default :
    2812                         $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
    2813                         break;
    2814                 endswitch;
    2815         } elseif ( is_string( $message ) ) {
    2816                 $message = "<p>$message</p>";
    2817         }
    2818 
    2819         if ( isset( $r['back_link'] ) && $r['back_link'] ) {
    2820                 $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
    2821                 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
    2822         }
    2823 
    2824         if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
    2825                 if ( !headers_sent() ) {
    2826                         status_header( $r['response'] );
    2827                         nocache_headers();
    2828                         header( 'Content-Type: text/html; charset=utf-8' );
    2829                 }
    2830 
    2831                 if ( empty($title) )
    2832                         $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
    2833 
    2834                 $text_direction = 'ltr';
    2835                 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
    2836                         $text_direction = 'rtl';
    2837                 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
    2838                         $text_direction = 'rtl';
    2839 ?>
    2840 <!DOCTYPE html>
    2841 <!-- 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
    2842 -->
    2843 <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'"; ?>>
    2844 <head>
    2845         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    2846         <title><?php echo $title ?></title>
    2847         <style type="text/css">
    2848                 html {
    2849                         background: #f9f9f9;
    2850                 }
    2851                 body {
    2852                         background: #fff;
    2853                         color: #333;
    2854                         font-family: sans-serif;
    2855                         margin: 2em auto;
    2856                         padding: 1em 2em;
    2857                         -webkit-border-radius: 3px;
    2858                         border-radius: 3px;
    2859                         border: 1px solid #dfdfdf;
    2860                         max-width: 700px;
    2861                 }
    2862                 #error-page {
    2863                         margin-top: 50px;
    2864                 }
    2865                 #error-page p {
    2866                         font-size: 14px;
    2867                         line-height: 1.5;
    2868                         margin: 25px 0 20px;
    2869                 }
    2870                 #error-page code {
    2871                         font-family: Consolas, Monaco, monospace;
    2872                 }
    2873                 ul li {
    2874                         margin-bottom: 10px;
    2875                         font-size: 14px ;
    2876                 }
    2877                 a {
    2878                         color: #21759B;
    2879                         text-decoration: none;
    2880                 }
    2881                 a:hover {
    2882                         color: #D54E21;
    2883                 }
    2884 
    2885                 .button {
    2886                         font-family: sans-serif;
    2887                         text-decoration: none;
    2888                         font-size: 14px !important;
    2889                         line-height: 16px;
    2890                         padding: 6px 12px;
    2891                         cursor: pointer;
    2892                         border: 1px solid #bbb;
    2893                         color: #464646;
    2894                         -webkit-border-radius: 15px;
    2895                         border-radius: 15px;
    2896                         -moz-box-sizing: content-box;
    2897                         -webkit-box-sizing: content-box;
    2898                         box-sizing: content-box;
    2899                 }
    2900 
    2901                 .button:hover {
    2902                         color: #000;
    2903                         border-color: #666;
    2904                 }
    2905 
    2906                 .button {
    2907                         background: #f2f2f2 url(<?php echo wp_guess_url(); ?>/wp-admin/images/white-grad.png) repeat-x scroll left top;
    2908                 }
    2909 
    2910                 .button:active {
    2911                         background: #eee url(<?php echo wp_guess_url(); ?>/wp-admin/images/white-grad-active.png) repeat-x scroll left top;
    2912                 }
    2913                 <?php if ( 'rtl' == $text_direction ) : ?>
    2914                 body { font-family: Tahoma, Arial; }
    2915                 <?php endif; ?>
    2916         </style>
    2917 </head>
    2918 <body id="error-page">
    2919 <?php endif; // !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ?>
    2920         <?php echo $message; ?>
    2921 </body>
    2922 </html>
    2923 <?php
    2924         die();
    2925 }
    2926 
    2927 /**
    2928  * Kill WordPress execution and display XML message with error message.
    2929  *
    2930  * This is the handler for wp_die when processing XMLRPC requests.
    2931  *
    2932  * @since 3.2.0
    2933  * @access private
    2934  *
    2935  * @param string $message Error message.
    2936  * @param string $title Error title.
    2937  * @param string|array $args Optional arguments to control behavior.
    2938  */
    2939 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
    2940         global $wp_xmlrpc_server;
    2941         $defaults = array( 'response' => 500 );
    2942 
    2943         $r = wp_parse_args($args, $defaults);
    2944 
    2945         if ( $wp_xmlrpc_server ) {
    2946                 $error = new IXR_Error( $r['response'] , $message);
    2947                 $wp_xmlrpc_server->output( $error->getXml() );
    2948         }
    2949         die();
    2950 }
    2951 
    2952 /**
    2953  * Filter to enable special wp_die handler for xmlrpc requests.
    2954  *
    2955  * @since 3.2.0
    2956  * @access private
    2957  */
    2958 function _xmlrpc_wp_die_filter() {
    2959         return '_xmlrpc_wp_die_handler';
    2960 }
    2961 
    2962 
    2963 /**
    2964  * Retrieve the WordPress home page URL.
    2965  *
    2966  * If the constant named 'WP_HOME' exists, then it will be used and returned by
    2967  * the function. This can be used to counter the redirection on your local
    2968  * development environment.
    2969  *
    2970  * @access private
    2971  * @package WordPress
    2972  * @since 2.2.0
    2973  *
    2974  * @param string $url URL for the home location
    2975  * @return string Homepage location.
    2976  */
    2977 function _config_wp_home( $url = '' ) {
    2978         if ( defined( 'WP_HOME' ) )
    2979                 return untrailingslashit( WP_HOME );
    2980         return $url;
    2981 }
    2982 
    2983 /**
    2984  * Retrieve the WordPress site URL.
    2985  *
    2986  * If the constant named 'WP_SITEURL' is defined, then the value in that
    2987  * constant will always be returned. This can be used for debugging a site on
    2988  * your localhost while not having to change the database to your URL.
    2989  *
    2990  * @access private
    2991  * @package WordPress
    2992  * @since 2.2.0
    2993  *
    2994  * @param string $url URL to set the WordPress site location.
    2995  * @return string The WordPress Site URL
    2996  */
    2997 function _config_wp_siteurl( $url = '' ) {
    2998         if ( defined( 'WP_SITEURL' ) )
    2999                 return untrailingslashit( WP_SITEURL );
    3000         return $url;
    3001 }
    3002 
    3003 /**
    3004  * Set the localized direction for MCE plugin.
    3005  *
    3006  * Will only set the direction to 'rtl', if the WordPress locale has the text
    3007  * direction set to 'rtl'.
    3008  *
    3009  * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
    3010  * keys. These keys are then returned in the $input array.
    3011  *
    3012  * @access private
    3013  * @package WordPress
    3014  * @subpackage MCE
    3015  * @since 2.1.0
    3016  *
    3017  * @param array $input MCE plugin array.
    3018  * @return array Direction set for 'rtl', if needed by locale.
    3019  */
    3020 function _mce_set_direction( $input ) {
    3021         if ( is_rtl() ) {
    3022                 $input['directionality'] = 'rtl';
    3023                 $input['plugins'] .= ',directionality';
    3024                 $input['theme_advanced_buttons1'] .= ',ltr';
    3025         }
    3026 
    3027         return $input;
    3028 }
    3029 
    3030 
    3031 /**
    3032  * Convert smiley code to the icon graphic file equivalent.
    3033  *
    3034  * You can turn off smilies, by going to the write setting screen and unchecking
    3035  * the box, or by setting 'use_smilies' option to false or removing the option.
    3036  *
    3037  * Plugins may override the default smiley list by setting the $wpsmiliestrans
    3038  * to an array, with the key the code the blogger types in and the value the
    3039  * image file.
    3040  *
    3041  * The $wp_smiliessearch global is for the regular expression and is set each
    3042  * time the function is called.
    3043  *
    3044  * The full list of smilies can be found in the function and won't be listed in
    3045  * the description. Probably should create a Codex page for it, so that it is
    3046  * available.
    3047  *
    3048  * @global array $wpsmiliestrans
    3049  * @global array $wp_smiliessearch
    3050  * @since 2.2.0
    3051  */
    3052 function smilies_init() {
    3053         global $wpsmiliestrans, $wp_smiliessearch;
    3054 
    3055         // don't bother setting up smilies if they are disabled
    3056         if ( !get_option( 'use_smilies' ) )
    3057                 return;
    3058 
    3059         if ( !isset( $wpsmiliestrans ) ) {
    3060                 $wpsmiliestrans = array(
    3061                 ':mrgreen:' => 'icon_mrgreen.gif',
    3062                 ':neutral:' => 'icon_neutral.gif',
    3063                 ':twisted:' => 'icon_twisted.gif',
    3064                   ':arrow:' => 'icon_arrow.gif',
    3065                   ':shock:' => 'icon_eek.gif',
    3066                   ':smile:' => 'icon_smile.gif',
    3067                     ':???:' => 'icon_confused.gif',
    3068                    ':cool:' => 'icon_cool.gif',
    3069                    ':evil:' => 'icon_evil.gif',
    3070                    ':grin:' => 'icon_biggrin.gif',
    3071                    ':idea:' => 'icon_idea.gif',
    3072                    ':oops:' => 'icon_redface.gif',
    3073                    ':razz:' => 'icon_razz.gif',
    3074                    ':roll:' => 'icon_rolleyes.gif',
    3075                    ':wink:' => 'icon_wink.gif',
    3076                     ':cry:' => 'icon_cry.gif',
    3077                     ':eek:' => 'icon_surprised.gif',
    3078                     ':lol:' => 'icon_lol.gif',
    3079                     ':mad:' => 'icon_mad.gif',
    3080                     ':sad:' => 'icon_sad.gif',
    3081                       '8-)' => 'icon_cool.gif',
    3082                       '8-O' => 'icon_eek.gif',
    3083                       ':-(' => 'icon_sad.gif',
    3084                       ':-)' => 'icon_smile.gif',
    3085                       ':-?' => 'icon_confused.gif',
    3086                       ':-D' => 'icon_biggrin.gif',
    3087                       ':-P' => 'icon_razz.gif',
    3088                       ':-o' => 'icon_surprised.gif',
    3089                       ':-x' => 'icon_mad.gif',
    3090                       ':-|' => 'icon_neutral.gif',
    3091                       ';-)' => 'icon_wink.gif',
    3092                        '8)' => 'icon_cool.gif',
    3093                        '8O' => 'icon_eek.gif',
    3094                        ':(' => 'icon_sad.gif',
    3095                        ':)' => 'icon_smile.gif',
    3096                        ':?' => 'icon_confused.gif',
    3097                        ':D' => 'icon_biggrin.gif',
    3098                        ':P' => 'icon_razz.gif',
    3099                        ':o' => 'icon_surprised.gif',
    3100                        ':x' => 'icon_mad.gif',
    3101                        ':|' => 'icon_neutral.gif',
    3102                        ';)' => 'icon_wink.gif',
    3103                       ':!:' => 'icon_exclaim.gif',
    3104                       ':?:' => 'icon_question.gif',
    3105                 );
    3106         }
    3107 
    3108         if (count($wpsmiliestrans) == 0) {
    3109                 return;
    3110         }
    3111 
    3112         /*
    3113          * NOTE: we sort the smilies in reverse key order. This is to make sure
    3114          * we match the longest possible smilie (:???: vs :?) as the regular
    3115          * expression used below is first-match
    3116          */
    3117         krsort($wpsmiliestrans);
    3118 
    3119         $wp_smiliessearch = '/(?:\s|^)';
    3120 
    3121         $subchar = '';
    3122         foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
    3123                 $firstchar = substr($smiley, 0, 1);
    3124                 $rest = substr($smiley, 1);
    3125 
    3126                 // new subpattern?
    3127                 if ($firstchar != $subchar) {
    3128                         if ($subchar != '') {
    3129                                 $wp_smiliessearch .= ')|(?:\s|^)';
    3130                         }
    3131                         $subchar = $firstchar;
    3132                         $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
    3133                 } else {
    3134                         $wp_smiliessearch .= '|';
    3135                 }
    3136                 $wp_smiliessearch .= preg_quote($rest, '/');
    3137         }
    3138 
    3139         $wp_smiliessearch .= ')(?:\s|$)/m';
    3140 }
    3141 
    3142 /**
    3143  * Merge user defined arguments into defaults array.
    3144  *
    3145  * This function is used throughout WordPress to allow for both string or array
    3146  * to be merged into another array.
    3147  *
    3148  * @since 2.2.0
    3149  *
    3150  * @param string|array $args Value to merge with $defaults
    3151  * @param array $defaults Array that serves as the defaults.
    3152  * @return array Merged user defined values with defaults.
    3153  */
    3154 function wp_parse_args( $args, $defaults = '' ) {
    3155         if ( is_object( $args ) )
    3156                 $r = get_object_vars( $args );
    3157         elseif ( is_array( $args ) )
    3158                 $r =& $args;
    3159         else
    3160                 wp_parse_str( $args, $r );
    3161 
    3162         if ( is_array( $defaults ) )
    3163                 return array_merge( $defaults, $r );
    3164         return $r;
    3165 }
    3166 
    3167 /**
    3168  * Clean up an array, comma- or space-separated list of IDs.
    3169  *
    3170  * @since 3.0.0
    3171  *
    3172  * @param array|string $list
    3173  * @return array Sanitized array of IDs
    3174  */
    3175 function wp_parse_id_list( $list ) {
    3176         if ( !is_array($list) )
    3177                 $list = preg_split('/[\s,]+/', $list);
    3178 
    3179         return array_unique(array_map('absint', $list));
    3180 }
    3181 
    3182 /**
    3183  * Extract a slice of an array, given a list of keys.
    3184  *
    3185  * @since 3.1.0
    3186  *
    3187  * @param array $array The original array
    3188  * @param array $keys The list of keys
    3189  * @return array The array slice
    3190  */
    3191 function wp_array_slice_assoc( $array, $keys ) {
    3192         $slice = array();
    3193         foreach ( $keys as $key )
    3194                 if ( isset( $array[ $key ] ) )
    3195                         $slice[ $key ] = $array[ $key ];
    3196 
    3197         return $slice;
    3198 }
    3199 
    3200 /**
    3201  * Filters a list of objects, based on a set of key => value arguments.
    3202  *
    3203  * @since 3.0.0
    3204  *
    3205  * @param array $list An array of objects to filter
    3206  * @param array $args An array of key => value arguments to match against each object
    3207  * @param string $operator The logical operation to perform. 'or' means only one element
    3208  *      from the array needs to match; 'and' means all elements must match. The default is 'and'.
    3209  * @param bool|string $field A field from the object to place instead of the entire object
    3210  * @return array A list of objects or object fields
    3211  */
    3212 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
    3213         if ( ! is_array( $list ) )
    3214                 return array();
    3215 
    3216         $list = wp_list_filter( $list, $args, $operator );
    3217 
    3218         if ( $field )
    3219                 $list = wp_list_pluck( $list, $field );
    3220 
    3221         return $list;
    3222 }
    3223 
    3224 /**
    3225  * Filters a list of objects, based on a set of key => value arguments.
    3226  *
    3227  * @since 3.1.0
    3228  *
    3229  * @param array $list An array of objects to filter
    3230  * @param array $args An array of key => value arguments to match against each object
    3231  * @param string $operator The logical operation to perform:
    3232  *    'AND' means all elements from the array must match;
    3233  *    'OR' means only one element needs to match;
    3234  *    'NOT' means no elements may match.
    3235  *   The default is 'AND'.
    3236  * @return array
    3237  */
    3238 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
    3239         if ( ! is_array( $list ) )
    3240                 return array();
    3241 
    3242         if ( empty( $args ) )
    3243                 return $list;
    3244 
    3245         $operator = strtoupper( $operator );
    3246         $count = count( $args );
    3247         $filtered = array();
    3248 
    3249         foreach ( $list as $key => $obj ) {
    3250                 $to_match = (array) $obj;
    3251 
    3252                 $matched = 0;
    3253                 foreach ( $args as $m_key => $m_value ) {
    3254                         if ( $m_value == $to_match[ $m_key ] )
    3255                                 $matched++;
    3256                 }
    3257 
    3258                 if ( ( 'AND' == $operator && $matched == $count )
    3259                   || ( 'OR' == $operator && $matched > 0 )
    3260                   || ( 'NOT' == $operator && 0 == $matched ) ) {
    3261                         $filtered[$key] = $obj;
    3262                 }
    3263         }
    3264 
    3265         return $filtered;
    3266 }
    3267 
    3268 /**
    3269  * Pluck a certain field out of each object in a list.
    3270  *
    3271  * @since 3.1.0
    3272  *
    3273  * @param array $list A list of objects or arrays
    3274  * @param int|string $field A field from the object to place instead of the entire object
    3275  * @return array
    3276  */
    3277 function wp_list_pluck( $list, $field ) {
    3278         foreach ( $list as $key => $value ) {
    3279                 if ( is_object( $value ) )
    3280                         $list[ $key ] = $value->$field;
    3281                 else
    3282                         $list[ $key ] = $value[ $field ];
    3283         }
    3284 
    3285         return $list;
    3286 }
    3287 
    3288 /**
    3289  * Determines if Widgets library should be loaded.
    3290  *
    3291  * Checks to make sure that the widgets library hasn't already been loaded. If
    3292  * it hasn't, then it will load the widgets library and run an action hook.
    3293  *
    3294  * @since 2.2.0
    3295  * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
    3296  */
    3297 function wp_maybe_load_widgets() {
    3298         if ( ! apply_filters('load_default_widgets', true) )
    3299                 return;
    3300         require_once( ABSPATH . WPINC . '/default-widgets.php' );
    3301         add_action( '_admin_menu', 'wp_widgets_add_menu' );
    3302 }
    3303 
    3304 /**
    3305  * Append the Widgets menu to the themes main menu.
    3306  *
    3307  * @since 2.2.0
    3308  * @uses $submenu The administration submenu list.
    3309  */
    3310 function wp_widgets_add_menu() {
    3311         global $submenu;
    3312         $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
    3313         ksort( $submenu['themes.php'], SORT_NUMERIC );
    3314 }
    3315 
    3316 /**
    3317  * Flush all output buffers for PHP 5.2.
    3318  *
    3319  * Make sure all output buffers are flushed before our singletons our destroyed.
    3320  *
    3321  * @since 2.2.0
    3322  */
    3323 function wp_ob_end_flush_all() {
    3324         $levels = ob_get_level();
    3325         for ($i=0; $i<$levels; $i++)
    3326                 ob_end_flush();
    3327 }
    3328 
    3329 /**
    3330  * Load custom DB error or display WordPress DB error.
    3331  *
    3332  * If a file exists in the wp-content directory named db-error.php, then it will
    3333  * be loaded instead of displaying the WordPress DB error. If it is not found,
    3334  * then the WordPress DB error will be displayed instead.
    3335  *
    3336  * The WordPress DB error sets the HTTP status header to 500 to try to prevent
    3337  * search engines from caching the message. Custom DB messages should do the
    3338  * same.
    3339  *
    3340  * This function was backported to the the WordPress 2.3.2, but originally was
    3341  * added in WordPress 2.5.0.
    3342  *
    3343  * @since 2.3.2
    3344  * @uses $wpdb
    3345  */
    3346 function dead_db() {
    3347         global $wpdb;
    3348 
    3349         // Load custom DB error template, if present.
    3350         if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
    3351                 require_once( WP_CONTENT_DIR . '/db-error.php' );
    3352                 die();
    3353         }
    3354 
    3355         // If installing or in the admin, provide the verbose message.
    3356         if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
    3357                 wp_die($wpdb->error);
    3358 
    3359         // Otherwise, be terse.
    3360         status_header( 500 );
    3361         nocache_headers();
    3362         header( 'Content-Type: text/html; charset=utf-8' );
    3363 ?>
    3364 <!DOCTYPE html>
    3365 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
    3366 <head>
    3367 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    3368         <title><?php echo /*WP_I18N_DB_ERROR*/'Database Error'/*/WP_I18N_DB_ERROR*/; ?></title>
    3369 
    3370 </head>
    3371 <body>
    3372         <h1><?php echo /*WP_I18N_DB_CONNECTION_ERROR*/'Error establishing a database connection'/*/WP_I18N_DB_CONNECTION_ERROR*/; ?></h1>
    3373 </body>
    3374 </html>
    3375 <?php
    3376         die();
    3377 }
    3378 
    3379 /**
    3380  * Converts value to nonnegative integer.
    3381  *
    3382  * @since 2.5.0
    3383  *
    3384  * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
    3385  * @return int An nonnegative integer
    3386  */
    3387 function absint( $maybeint ) {
    3388         return abs( intval( $maybeint ) );
    3389 }
    3390 
    3391 /**
    3392  * Determines if the blog can be accessed over SSL.
    3393  *
    3394  * Determines if blog can be accessed over SSL by using cURL to access the site
    3395  * using the https in the siteurl. Requires cURL extension to work correctly.
    3396  *
    3397  * @since 2.5.0
    3398  *
    3399  * @param string $url
    3400  * @return bool Whether SSL access is available
    3401  */
    3402 function url_is_accessable_via_ssl($url)
    3403 {
    3404         if (in_array('curl', get_loaded_extensions())) {
    3405                 $ssl = preg_replace( '/^http:\/\//', 'https://',  $url );
    3406 
    3407                 $ch = curl_init();
    3408                 curl_setopt($ch, CURLOPT_URL, $ssl);
    3409                 curl_setopt($ch, CURLOPT_FAILONERROR, true);
    3410                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    3411                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    3412                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    3413 
    3414                 curl_exec($ch);
    3415 
    3416                 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    3417                 curl_close ($ch);
    3418 
    3419                 if ($status == 200 || $status == 401) {
    3420                         return true;
    3421                 }
    3422         }
    3423         return false;
    3424 }
    3425 
    3426 /**
    3427  * Marks a function as deprecated and informs when it has been used.
    3428  *
    3429  * There is a hook deprecated_function_run that will be called that can be used
    3430  * to get the backtrace up to what file and function called the deprecated
    3431  * function.
    3432  *
    3433  * The current behavior is to trigger a user error if WP_DEBUG is true.
    3434  *
    3435  * This function is to be used in every function that is deprecated.
    3436  *
    3437  * @package WordPress
    3438  * @subpackage Debug
    3439  * @since 2.5.0
    3440  * @access private
    3441  *
    3442  * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
    3443  *   and the version the function was deprecated in.
    3444  * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
    3445  *   trigger or false to not trigger error.
    3446  *
    3447  * @param string $function The function that was called
    3448  * @param string $version The version of WordPress that deprecated the function
    3449  * @param string $replacement Optional. The function that should have been called
    3450  */
    3451 function _deprecated_function( $function, $version, $replacement = null ) {
    3452 
    3453         do_action( 'deprecated_function_run', $function, $replacement, $version );
    3454 
    3455         // Allow plugin to filter the output error trigger
    3456         if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
    3457                 if ( ! is_null($replacement) )
    3458                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
    3459                 else
    3460                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
    3461         }
    3462 }
    3463 
    3464 /**
    3465  * Marks a file as deprecated and informs when it has been used.
    3466  *
    3467  * There is a hook deprecated_file_included that will be called that can be used
    3468  * to get the backtrace up to what file and function included the deprecated
    3469  * file.
    3470  *
    3471  * The current behavior is to trigger a user error if WP_DEBUG is true.
    3472  *
    3473  * This function is to be used in every file that is deprecated.
    3474  *
    3475  * @package WordPress
    3476  * @subpackage Debug
    3477  * @since 2.5.0
    3478  * @access private
    3479  *
    3480  * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
    3481  *   the version in which the file was deprecated, and any message regarding the change.
    3482  * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
    3483  *   trigger or false to not trigger error.
    3484  *
    3485  * @param string $file The file that was included
    3486  * @param string $version The version of WordPress that deprecated the file
    3487  * @param string $replacement Optional. The file that should have been included based on ABSPATH
    3488  * @param string $message Optional. A message regarding the change
    3489  */
    3490 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
    3491 
    3492         do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
    3493 
    3494         // Allow plugin to filter the output error trigger
    3495         if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
    3496                 $message = empty( $message ) ? '' : ' ' . $message;
    3497                 if ( ! is_null( $replacement ) )
    3498                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
    3499                 else
    3500                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
    3501         }
    3502 }
    3503 /**
    3504  * Marks a function argument as deprecated and informs when it has been used.
    3505  *
    3506  * This function is to be used whenever a deprecated function argument is used.
    3507  * Before this function is called, the argument must be checked for whether it was
    3508  * used by comparing it to its default value or evaluating whether it is empty.
    3509  * For example:
    3510  * <code>
    3511  * if ( !empty($deprecated) )
    3512  *      _deprecated_argument( __FUNCTION__, '3.0' );
    3513  * </code>
    3514  *
    3515  * There is a hook deprecated_argument_run that will be called that can be used
    3516  * to get the backtrace up to what file and function used the deprecated
    3517  * argument.
    3518  *
    3519  * The current behavior is to trigger a user error if WP_DEBUG is true.
    3520  *
    3521  * @package WordPress
    3522  * @subpackage Debug
    3523  * @since 3.0.0
    3524  * @access private
    3525  *
    3526  * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
    3527  *   and the version in which the argument was deprecated.
    3528  * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
    3529  *   trigger or false to not trigger error.
    3530  *
    3531  * @param string $function The function that was called
    3532  * @param string $version The version of WordPress that deprecated the argument used
    3533  * @param string $message Optional. A message regarding the change.
    3534  */
    3535 function _deprecated_argument( $function, $version, $message = null ) {
    3536 
    3537         do_action( 'deprecated_argument_run', $function, $message, $version );
    3538 
    3539         // Allow plugin to filter the output error trigger
    3540         if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
    3541                 if ( ! is_null( $message ) )
    3542                         trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
    3543                 else
    3544                         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 ) );
    3545         }
    3546 }
    3547 
    3548 /**
    3549  * Marks something as being incorrectly called.
    3550  *
    3551  * There is a hook doing_it_wrong_run that will be called that can be used
    3552  * to get the backtrace up to what file and function called the deprecated
    3553  * function.
    3554  *
    3555  * The current behavior is to trigger a user error if WP_DEBUG is true.
    3556  *
    3557  * @package WordPress
    3558  * @subpackage Debug
    3559  * @since 3.1.0
    3560  * @access private
    3561  *
    3562  * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
    3563  * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
    3564  *   trigger or false to not trigger error.
    3565  *
    3566  * @param string $function The function that was called.
    3567  * @param string $message A message explaining what has been done incorrectly.
    3568  * @param string $version The version of WordPress where the message was added.
    3569  */
    3570 function _doing_it_wrong( $function, $message, $version ) {
    3571 
    3572         do_action( 'doing_it_wrong_run', $function, $message, $version );
    3573 
    3574         // Allow plugin to filter the output error trigger
    3575         if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
    3576                 $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
    3577                 $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
    3578                 trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
    3579         }
    3580 }
    3581 
    3582 /**
    3583  * Is the server running earlier than 1.5.0 version of lighttpd?
    3584  *
    3585  * @since 2.5.0
    3586  *
    3587  * @return bool Whether the server is running lighttpd < 1.5.0
    3588  */
    3589 function is_lighttpd_before_150() {
    3590         $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
    3591         $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
    3592         return  'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
    3593 }
    3594 
    3595 /**
    3596  * Does the specified module exist in the Apache config?
    3597  *
    3598  * @since 2.5.0
    3599  *
    3600  * @param string $mod e.g. mod_rewrite
    3601  * @param bool $default The default return value if the module is not found
    3602  * @return bool
    3603  */
    3604 function apache_mod_loaded($mod, $default = false) {
    3605         global $is_apache;
    3606 
    3607         if ( !$is_apache )
    3608                 return false;
    3609 
    3610         if ( function_exists('apache_get_modules') ) {
    3611                 $mods = apache_get_modules();
    3612                 if ( in_array($mod, $mods) )
    3613                         return true;
    3614         } elseif ( function_exists('phpinfo') ) {
    3615                         ob_start();
    3616                         phpinfo(8);
    3617                         $phpinfo = ob_get_clean();
    3618                         if ( false !== strpos($phpinfo, $mod) )
    3619                                 return true;
    3620         }
    3621         return $default;
    3622 }
    3623 
    3624 /**
    3625  * Check if IIS 7 supports pretty permalinks.
    3626  *
    3627  * @since 2.8.0
    3628  *
    3629  * @return bool
    3630  */
    3631 function iis7_supports_permalinks() {
    3632         global $is_iis7;
    3633 
    3634         $supports_permalinks = false;
    3635         if ( $is_iis7 ) {
    3636                 /* First we check if the DOMDocument class exists. If it does not exist,
    3637                  * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
    3638                  * hence we just bail out and tell user that pretty permalinks cannot be used.
    3639                  * This is not a big issue because PHP 4.X is going to be deprecated and for IIS it
    3640                  * is recommended to use PHP 5.X NTS.
    3641                  * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
    3642                  * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
    3643                  * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
    3644                  * via ISAPI then pretty permalinks will not work.
    3645                  */
    3646                 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
    3647         }
    3648 
    3649         return apply_filters('iis7_supports_permalinks', $supports_permalinks);
    3650 }
    3651 
    3652 /**
    3653  * File validates against allowed set of defined rules.
    3654  *
    3655  * A return value of '1' means that the $file contains either '..' or './'. A
    3656  * return value of '2' means that the $file contains ':' after the first
    3657  * character. A return value of '3' means that the file is not in the allowed
    3658  * files list.
    3659  *
    3660  * @since 1.2.0
    3661  *
    3662  * @param string $file File path.
    3663  * @param array $allowed_files List of allowed files.
    3664  * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
    3665  */
    3666 function validate_file( $file, $allowed_files = '' ) {
    3667         if ( false !== strpos( $file, '..' ) )
    3668                 return 1;
    3669 
    3670         if ( false !== strpos( $file, './' ) )
    3671                 return 1;
    3672 
    3673         if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
    3674                 return 3;
    3675 
    3676         if (':' == substr( $file, 1, 1 ) )
    3677                 return 2;
    3678 
    3679         return 0;
    3680 }
    3681 
    3682 /**
    3683  * Determine if SSL is used.
    3684  *
    3685  * @since 2.6.0
    3686  *
    3687  * @return bool True if SSL, false if not used.
    3688  */
    3689 function is_ssl() {
    3690         if ( isset($_SERVER['HTTPS']) ) {
    3691                 if ( 'on' == strtolower($_SERVER['HTTPS']) )
    3692                         return true;
    3693                 if ( '1' == $_SERVER['HTTPS'] )
    3694                         return true;
    3695         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
    3696                 return true;
    3697         }
    3698         return false;
    3699 }
    3700 
    3701 /**
    3702  * Whether SSL login should be forced.
    3703  *
    3704  * @since 2.6.0
    3705  *
    3706  * @param string|bool $force Optional.
    3707  * @return bool True if forced, false if not forced.
    3708  */
    3709 function force_ssl_login( $force = null ) {
    3710         static $forced = false;
    3711 
    3712         if ( !is_null( $force ) ) {
    3713                 $old_forced = $forced;
    3714                 $forced = $force;
    3715                 return $old_forced;
    3716         }
    3717 
    3718         return $forced;
    3719 }
    3720 
    3721 /**
    3722  * Whether to force SSL used for the Administration Screens.
    3723  *
    3724  * @since 2.6.0
    3725  *
    3726  * @param string|bool $force
    3727  * @return bool True if forced, false if not forced.
    3728  */
    3729 function force_ssl_admin( $force = null ) {
    3730         static $forced = false;
    3731 
    3732         if ( !is_null( $force ) ) {
    3733                 $old_forced = $forced;
    3734                 $forced = $force;
    3735                 return $old_forced;
    3736         }
    3737 
    3738         return $forced;
    3739 }
    3740 
    3741 /**
    3742  * Guess the URL for the site.
    3743  *
    3744  * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
    3745  * directory.
    3746  *
    3747  * @since 2.6.0
    3748  *
    3749  * @return string
    3750  */
    3751 function wp_guess_url() {
    3752         if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
    3753                 $url = WP_SITEURL;
    3754         } else {
    3755                 $schema = is_ssl() ? 'https://' : 'http://';
    3756                 $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    3757         }
    3758         return rtrim($url, '/');
    3759 }
    3760 
    3761 /**
    3762  * Temporarily suspend cache additions.
    3763  *
    3764  * Stops more data being added to the cache, but still allows cache retrieval.
    3765  * This is useful for actions, such as imports, when a lot of data would otherwise
    3766  * be almost uselessly added to the cache.
    3767  *
    3768  * Suspension lasts for a single page load at most. Remember to call this
    3769  * function again if you wish to re-enable cache adds earlier.
    3770  *
    3771  * @since 3.3.0
    3772  *
    3773  * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
    3774  * @return bool The current suspend setting
    3775  */
    3776 function wp_suspend_cache_addition( $suspend = null ) {
    3777         static $_suspend = false;
    3778 
    3779         if ( is_bool( $suspend ) )
    3780                 $_suspend = $suspend;
    3781 
    3782         return $_suspend;
    3783 }
    3784 
    3785 /**
    3786  * Suspend cache invalidation.
    3787  *
    3788  * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
    3789  * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
    3790  * cache when invalidation is suspended.
    3791  *
    3792  * @since 2.7.0
    3793  *
    3794  * @param bool $suspend Whether to suspend or enable cache invalidation
    3795  * @return bool The current suspend setting
    3796  */
    3797 function wp_suspend_cache_invalidation($suspend = true) {
    3798         global $_wp_suspend_cache_invalidation;
    3799 
    3800         $current_suspend = $_wp_suspend_cache_invalidation;
    3801         $_wp_suspend_cache_invalidation = $suspend;
    3802         return $current_suspend;
    3803 }
    3804 
    3805 /**
    3806731 * Retrieve site option value based on name of option.
    3807732 *
    3808733 * @see get_option()
     
    41181043        }
    41191044        return $result;
    41201045}
    4121 
    4122 /**
    4123  * Is main site?
    4124  *
    4125  *
    4126  * @since 3.0.0
    4127  * @package WordPress
    4128  *
    4129  * @param int $blog_id optional blog id to test (default current blog)
    4130  * @return bool True if not multisite or $blog_id is main site
    4131  */
    4132 function is_main_site( $blog_id = '' ) {
    4133         global $current_site, $current_blog;
    4134 
    4135         if ( !is_multisite() )
    4136                 return true;
    4137 
    4138         if ( !$blog_id )
    4139                 $blog_id = $current_blog->blog_id;
    4140 
    4141         return $blog_id == $current_site->blog_id;
    4142 }
    4143 
    4144 /**
    4145  * Whether global terms are enabled.
    4146  *
    4147  *
    4148  * @since 3.0.0
    4149  * @package WordPress
    4150  *
    4151  * @return bool True if multisite and global terms enabled
    4152  */
    4153 function global_terms_enabled() {
    4154         if ( ! is_multisite() )
    4155                 return false;
    4156 
    4157         static $global_terms = null;
    4158         if ( is_null( $global_terms ) ) {
    4159                 $filter = apply_filters( 'global_terms_enabled', null );
    4160                 if ( ! is_null( $filter ) )
    4161                         $global_terms = (bool) $filter;
    4162                 else
    4163                         $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
    4164         }
    4165         return $global_terms;
    4166 }
    4167 
    4168 /**
    4169  * gmt_offset modification for smart timezone handling.
    4170  *
    4171  * Overrides the gmt_offset option if we have a timezone_string available.
    4172  *
    4173  * @since 2.8.0
    4174  *
    4175  * @return float|bool
    4176  */
    4177 function wp_timezone_override_offset() {
    4178         if ( !$timezone_string = get_option( 'timezone_string' ) ) {
    4179                 return false;
    4180         }
    4181 
    4182         $timezone_object = timezone_open( $timezone_string );
    4183         $datetime_object = date_create();
    4184         if ( false === $timezone_object || false === $datetime_object ) {
    4185                 return false;
    4186         }
    4187         return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
    4188 }
    4189 
    4190 /**
    4191  * {@internal Missing Short Description}}
    4192  *
    4193  * @since 2.9.0
    4194  *
    4195  * @param unknown_type $a
    4196  * @param unknown_type $b
    4197  * @return int
    4198  */
    4199 function _wp_timezone_choice_usort_callback( $a, $b ) {
    4200         // Don't use translated versions of Etc
    4201         if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
    4202                 // Make the order of these more like the old dropdown
    4203                 if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
    4204                         return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
    4205                 }
    4206                 if ( 'UTC' === $a['city'] ) {
    4207                         if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
    4208                                 return 1;
    4209                         }
    4210                         return -1;
    4211                 }
    4212                 if ( 'UTC' === $b['city'] ) {
    4213                         if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
    4214                                 return -1;
    4215                         }
    4216                         return 1;
    4217                 }
    4218                 return strnatcasecmp( $a['city'], $b['city'] );
    4219         }
    4220         if ( $a['t_continent'] == $b['t_continent'] ) {
    4221                 if ( $a['t_city'] == $b['t_city'] ) {
    4222                         return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
    4223                 }
    4224                 return strnatcasecmp( $a['t_city'], $b['t_city'] );
    4225         } else {
    4226                 // Force Etc to the bottom of the list
    4227                 if ( 'Etc' === $a['continent'] ) {
    4228                         return 1;
    4229                 }
    4230                 if ( 'Etc' === $b['continent'] ) {
    4231                         return -1;
    4232                 }
    4233                 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
    4234         }
    4235 }
    4236 
    4237 /**
    4238  * Gives a nicely formatted list of timezone strings. // temporary! Not in final
    4239  *
    4240  * @since 2.9.0
    4241  *
    4242  * @param string $selected_zone Selected Zone
    4243  * @return string
    4244  */
    4245 function wp_timezone_choice( $selected_zone ) {
    4246         static $mo_loaded = false;
    4247 
    4248         $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
    4249 
    4250         // Load translations for continents and cities
    4251         if ( !$mo_loaded ) {
    4252                 $locale = get_locale();
    4253                 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
    4254                 load_textdomain( 'continents-cities', $mofile );
    4255                 $mo_loaded = true;
    4256         }
    4257 
    4258         $zonen = array();
    4259         foreach ( timezone_identifiers_list() as $zone ) {
    4260                 $zone = explode( '/', $zone );
    4261                 if ( !in_array( $zone[0], $continents ) ) {
    4262                         continue;
    4263                 }
    4264 
    4265                 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
    4266                 $exists = array(
    4267                         0 => ( isset( $zone[0] ) && $zone[0] ),
    4268                         1 => ( isset( $zone[1] ) && $zone[1] ),
    4269                         2 => ( isset( $zone[2] ) && $zone[2] ),
    4270                 );
    4271                 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
    4272                 $exists[4] = ( $exists[1] && $exists[3] );
    4273                 $exists[5] = ( $exists[2] && $exists[3] );
    4274 
    4275                 $zonen[] = array(
    4276                         'continent'   => ( $exists[0] ? $zone[0] : '' ),
    4277                         'city'        => ( $exists[1] ? $zone[1] : '' ),
    4278                         'subcity'     => ( $exists[2] ? $zone[2] : '' ),
    4279                         't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
    4280                         't_city'      => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
    4281                         't_subcity'   => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
    4282                 );
    4283         }
    4284         usort( $zonen, '_wp_timezone_choice_usort_callback' );
    4285 
    4286         $structure = array();
    4287 
    4288         if ( empty( $selected_zone ) ) {
    4289                 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
    4290         }
    4291 
    4292         foreach ( $zonen as $key => $zone ) {
    4293                 // Build value in an array to join later
    4294                 $value = array( $zone['continent'] );
    4295 
    4296                 if ( empty( $zone['city'] ) ) {
    4297                         // It's at the continent level (generally won't happen)
    4298                         $display = $zone['t_continent'];
    4299                 } else {
    4300                         // It's inside a continent group
    4301 
    4302                         // Continent optgroup
    4303                         if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
    4304                                 $label = $zone['t_continent'];
    4305                                 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
    4306                         }
    4307 
    4308                         // Add the city to the value
    4309                         $value[] = $zone['city'];
    4310 
    4311                         $display = $zone['t_city'];
    4312                         if ( !empty( $zone['subcity'] ) ) {
    4313                                 // Add the subcity to the value
    4314                                 $value[] = $zone['subcity'];
    4315                                 $display .= ' - ' . $zone['t_subcity'];
    4316                         }
    4317                 }
    4318 
    4319                 // Build the value
    4320                 $value = join( '/', $value );
    4321                 $selected = '';
    4322                 if ( $value === $selected_zone ) {
    4323                         $selected = 'selected="selected" ';
    4324                 }
    4325                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
    4326 
    4327                 // Close continent optgroup
    4328                 if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
    4329                         $structure[] = '</optgroup>';
    4330                 }
    4331         }
    4332 
    4333         // Do UTC
    4334         $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
    4335         $selected = '';
    4336         if ( 'UTC' === $selected_zone )
    4337                 $selected = 'selected="selected" ';
    4338         $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
    4339         $structure[] = '</optgroup>';
    4340 
    4341         // Do manual UTC offsets
    4342         $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
    4343         $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,
    4344                 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);
    4345         foreach ( $offset_range as $offset ) {
    4346                 if ( 0 <= $offset )
    4347                         $offset_name = '+' . $offset;
    4348                 else
    4349                         $offset_name = (string) $offset;
    4350 
    4351                 $offset_value = $offset_name;
    4352                 $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
    4353                 $offset_name = 'UTC' . $offset_name;
    4354                 $offset_value = 'UTC' . $offset_value;
    4355                 $selected = '';
    4356                 if ( $offset_value === $selected_zone )
    4357                         $selected = 'selected="selected" ';
    4358                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
    4359 
    4360         }
    4361         $structure[] = '</optgroup>';
    4362 
    4363         return join( "\n", $structure );
    4364 }
    4365 
    4366 /**
    4367  * Strip close comment and close php tags from file headers used by WP.
    4368  * See http://core.trac.wordpress.org/ticket/8497
    4369  *
    4370  * @since 2.8.0
    4371  *
    4372  * @param string $str
    4373  * @return string
    4374  */
    4375 function _cleanup_header_comment($str) {
    4376         return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
    4377 }
    4378 
    4379 /**
    4380  * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
    4381  *
    4382  * @since 2.9.0
    4383  */
    4384 function wp_scheduled_delete() {
    4385         global $wpdb;
    4386 
    4387         $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
    4388 
    4389         $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);
    4390 
    4391         foreach ( (array) $posts_to_delete as $post ) {
    4392                 $post_id = (int) $post['post_id'];
    4393                 if ( !$post_id )
    4394                         continue;
    4395 
    4396                 $del_post = get_post($post_id);
    4397 
    4398                 if ( !$del_post || 'trash' != $del_post->post_status ) {
    4399                         delete_post_meta($post_id, '_wp_trash_meta_status');
    4400                         delete_post_meta($post_id, '_wp_trash_meta_time');
    4401                 } else {
    4402                         wp_delete_post($post_id);
    4403                 }
    4404         }
    4405 
    4406         $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);
    4407 
    4408         foreach ( (array) $comments_to_delete as $comment ) {
    4409                 $comment_id = (int) $comment['comment_id'];
    4410                 if ( !$comment_id )
    4411                         continue;
    4412 
    4413                 $del_comment = get_comment($comment_id);
    4414 
    4415                 if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
    4416                         delete_comment_meta($comment_id, '_wp_trash_meta_time');
    4417                         delete_comment_meta($comment_id, '_wp_trash_meta_status');
    4418                 } else {
    4419                         wp_delete_comment($comment_id);
    4420                 }
    4421         }
    4422 }
    4423 
    4424 /**
    4425  * Retrieve metadata from a file.
    4426  *
    4427  * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
    4428  * Each piece of metadata must be on its own line. Fields can not span multiple
    4429  * lines, the value will get cut at the end of the first line.
    4430  *
    4431  * If the file data is not within that first 8kiB, then the author should correct
    4432  * their plugin file and move the data headers to the top.
    4433  *
    4434  * @see http://codex.wordpress.org/File_Header
    4435  *
    4436  * @since 2.9.0
    4437  * @param string $file Path to the file
    4438  * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
    4439  * @param string $context If specified adds filter hook "extra_{$context}_headers"
    4440  */
    4441 function get_file_data( $file, $default_headers, $context = '' ) {
    4442         // We don't need to write to the file, so just open for reading.
    4443         $fp = fopen( $file, 'r' );
    4444 
    4445         // Pull only the first 8kiB of the file in.
    4446         $file_data = fread( $fp, 8192 );
    4447 
    4448         // PHP will close file handle, but we are good citizens.
    4449         fclose( $fp );
    4450 
    4451         if ( $context != '' ) {
    4452                 $extra_headers = apply_filters( "extra_{$context}_headers", array() );
    4453 
    4454                 $extra_headers = array_flip( $extra_headers );
    4455                 foreach( $extra_headers as $key=>$value ) {
    4456                         $extra_headers[$key] = $key;
    4457                 }
    4458                 $all_headers = array_merge( $extra_headers, (array) $default_headers );
    4459         } else {
    4460                 $all_headers = $default_headers;
    4461         }
    4462 
    4463         foreach ( $all_headers as $field => $regex ) {
    4464                 preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
    4465                 if ( !empty( ${$field} ) )
    4466                         ${$field} = _cleanup_header_comment( ${$field}[1] );
    4467                 else
    4468                         ${$field} = '';
    4469         }
    4470 
    4471         $file_data = compact( array_keys( $all_headers ) );
    4472 
    4473         return $file_data;
    4474 }
    4475 
    4476 /**
    4477  * Used internally to tidy up the search terms.
    4478  *
    4479  * @access private
    4480  * @since 2.9.0
    4481  *
    4482  * @param string $t
    4483  * @return string
    4484  */
    4485 function _search_terms_tidy($t) {
    4486         return trim($t, "\"'\n\r ");
    4487 }
    4488 
    4489 /**
    4490  * Returns true.
    4491  *
    4492  * Useful for returning true to filters easily.
    4493  *
    4494  * @since 3.0.0
    4495  * @see __return_false()
    4496  * @return bool true
    4497  */
    4498 function __return_true() {
    4499         return true;
    4500 }
    4501 
    4502 /**
    4503  * Returns false.
    4504  *
    4505  * Useful for returning false to filters easily.
    4506  *
    4507  * @since 3.0.0
    4508  * @see __return_true()
    4509  * @return bool false
    4510  */
    4511 function __return_false() {
    4512         return false;
    4513 }
    4514 
    4515 /**
    4516  * Returns 0.
    4517  *
    4518  * Useful for returning 0 to filters easily.
    4519  *
    4520  * @since 3.0.0
    4521  * @see __return_zero()
    4522  * @return int 0
    4523  */
    4524 function __return_zero() {
    4525         return 0;
    4526 }
    4527 
    4528 /**
    4529  * Returns an empty array.
    4530  *
    4531  * Useful for returning an empty array to filters easily.
    4532  *
    4533  * @since 3.0.0
    4534  * @see __return_zero()
    4535  * @return array Empty array
    4536  */
    4537 function __return_empty_array() {
    4538         return array();
    4539 }
    4540 
    4541 /**
    4542  * Send a HTTP header to disable content type sniffing in browsers which support it.
    4543  *
    4544  * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
    4545  * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
    4546  *
    4547  * @since 3.0.0
    4548  * @return none
    4549  */
    4550 function send_nosniff_header() {
    4551         @header( 'X-Content-Type-Options: nosniff' );
    4552 }
    4553 
    4554 /**
    4555  * Returns a MySQL expression for selecting the week number based on the start_of_week option.
    4556  *
    4557  * @internal
    4558  * @since 3.0.0
    4559  * @param string $column
    4560  * @return string
    4561  */
    4562 function _wp_mysql_week( $column ) {
    4563         switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
    4564         default :
    4565         case 0 :
    4566                 return "WEEK( $column, 0 )";
    4567         case 1 :
    4568                 return "WEEK( $column, 1 )";
    4569         case 2 :
    4570         case 3 :
    4571         case 4 :
    4572         case 5 :
    4573         case 6 :
    4574                 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
    4575         }
    4576 }
    4577 
    4578 /**
    4579  * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
    4580  *
    4581  * @since 3.1.0
    4582  * @access private
    4583  *
    4584  * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
    4585  * @param int $start The ID to start the loop check at
    4586  * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
    4587  * @param array $callback_args optional additional arguments to send to $callback
    4588  * @return array IDs of all members of loop
    4589  */
    4590 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
    4591         $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
    4592 
    4593         if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
    4594                 return array();
    4595 
    4596         return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
    4597 }
    4598 
    4599 /**
    4600  * Uses the "The Tortoise and the Hare" algorithm to detect loops.
    4601  *
    4602  * For every step of the algorithm, the hare takes two steps and the tortoise one.
    4603  * If the hare ever laps the tortoise, there must be a loop.
    4604  *
    4605  * @since 3.1.0
    4606  * @access private
    4607  *
    4608  * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
    4609  * @param int $start The ID to start the loop check at
    4610  * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
    4611  * @param array $callback_args optional additional arguments to send to $callback
    4612  * @param bool $_return_loop Return loop members or just detect presence of loop?
    4613  *             Only set to true if you already know the given $start is part of a loop
    4614  *             (otherwise the returned array might include branches)
    4615  * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
    4616  */
    4617 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
    4618         $tortoise = $hare = $evanescent_hare = $start;
    4619         $return = array();
    4620 
    4621         // Set evanescent_hare to one past hare
    4622         // Increment hare two steps
    4623         while (
    4624                 $tortoise
    4625         &&
    4626                 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
    4627         &&
    4628                 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
    4629         ) {
    4630                 if ( $_return_loop )
    4631                         $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
    4632 
    4633                 // tortoise got lapped - must be a loop
    4634                 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
    4635                         return $_return_loop ? $return : $tortoise;
    4636 
    4637                 // Increment tortoise by one step
    4638                 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
    4639         }
    4640 
    4641         return false;
    4642 }
    4643 
    4644 /**
    4645  * Send a HTTP header to limit rendering of pages to same origin iframes.
    4646  *
    4647  * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
    4648  *
    4649  * @since 3.1.3
    4650  * @return none
    4651  */
    4652 function send_frame_options_header() {
    4653         @header( 'X-Frame-Options: SAMEORIGIN' );
    4654 }
    4655 
    4656 /**
    4657  * Retrieve a list of protocols to allow in HTML attributes.
    4658  *
    4659  * @since 3.3.0
    4660  * @see wp_kses()
    4661  * @see esc_url()
    4662  *
    4663  * @return array Array of allowed protocols
    4664  */
    4665 function wp_allowed_protocols() {
    4666         static $protocols;
    4667 
    4668         if ( empty( $protocols ) ) {
    4669                 $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' );
    4670                 $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
    4671         }
    4672 
    4673         return $protocols;
    4674 }
    4675 
    4676 ?>