X-Git-Url: https://scripts.mit.edu/gitweb/autoinstallsdev/wordpress.git/blobdiff_plain/7c1a4aea7aeb083c7424823d11f24401edcba439..e08b42e8ad054ec67522d7ac1aaae5dc68cb3d01:/wp-includes/functions.php diff --git a/wp-includes/functions.php b/wp-includes/functions.php index 1df479e6..05acf4e1 100644 --- a/wp-includes/functions.php +++ b/wp-includes/functions.php @@ -5,42 +5,40 @@ * @package WordPress */ +require( ABSPATH . WPINC . '/option.php' ); + /** - * Converts MySQL DATETIME field to user specified date format. + * Converts given date string into a different format. * - * If $dateformatstring has 'G' value, then gmmktime() function will be used to - * make the time. If $dateformatstring is set to 'U', then mktime() function - * will be used to make the time. + * $format should be either a PHP date format string, e.g. 'U' for a Unix + * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT. * - * The $translate will only be used, if it is set to true and it is by default - * and if the $wp_locale object has the month and weekday set. + * If $translate is true then the given date and format string will + * be passed to date_i18n() for translation. * * @since 0.71 * - * @param string $dateformatstring Either 'G', 'U', or php date format. - * @param string $mysqlstring Time from mysql DATETIME field. - * @param bool $translate Optional. Default is true. Will switch format to locale. - * @return string Date formated by $dateformatstring or locale (if available). + * @param string $format Format of the date to return. + * @param string $date Date string to convert. + * @param bool $translate Whether the return date should be translated. Default is true. + * @return string|int Formatted date string, or Unix timestamp. */ -function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) { - global $wp_locale; - $m = $mysqlstring; - if ( empty( $m ) ) +function mysql2date( $format, $date, $translate = true ) { + if ( empty( $date ) ) return false; - if( 'G' == $dateformatstring ) { - return strtotime( $m . ' +0000' ); - } + if ( 'G' == $format ) + return strtotime( $date . ' +0000' ); - $i = strtotime( $m ); + $i = strtotime( $date ); - if( 'U' == $dateformatstring ) + if ( 'U' == $format ) return $i; - if ( $translate) - return date_i18n( $dateformatstring, $i ); + if ( $translate ) + return date_i18n( $format, $i ); else - return date( $dateformatstring, $i ); + return date( $format, $i ); } /** @@ -61,10 +59,10 @@ function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) { function current_time( $type, $gmt = 0 ) { switch ( $type ) { case 'mysql': - return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) ); + return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) ); break; case 'timestamp': - return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 ); + return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ); break; } } @@ -86,8 +84,8 @@ function current_time( $type, $gmt = 0 ) { function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) { global $wp_locale; $i = $unixtimestamp; - // Sanity check for PHP 5.1.0- - if ( false === $i || intval($i) < 0 ) { + + if ( false === $i ) { if ( ! $gmt ) $i = current_time( 'timestamp' ); else @@ -120,6 +118,23 @@ function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) { $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 ); } + $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' ); + $timezone_formats_re = implode( '|', $timezone_formats ); + if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) { + $timezone_string = get_option( 'timezone_string' ); + if ( $timezone_string ) { + $timezone_object = timezone_open( $timezone_string ); + $date_object = date_create( null, $timezone_object ); + foreach( $timezone_formats as $timezone_format ) { + if ( false !== strpos( $dateformatstring, $timezone_format ) ) { + $formatted = date_format( $date_object, $timezone_format ); + $dateformatstring = ' '.$dateformatstring; + $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring ); + $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 ); + } + } + } + } $j = @$datefunc( $dateformatstring, $i ); // allow plugins to redo this entirely for languages with untypical grammars $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt); @@ -127,23 +142,18 @@ function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) { } /** - * Convert number to format based on the locale. + * Convert integer number to format based on the locale. * * @since 2.3.0 * - * @param mixed $number The number to convert based on locale. + * @param int $number The number to convert based on locale. * @param int $decimals Precision of the number of decimal places. * @return string Converted number in string format. */ -function number_format_i18n( $number, $decimals = null ) { +function number_format_i18n( $number, $decimals = 0 ) { global $wp_locale; - // let the user override the precision only - $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals ); - - $num = number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] ); - - // let the user translate digits from latin to localized language - return apply_filters( 'number_format_i18n', $num ); + $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] ); + return apply_filters( 'number_format_i18n', $formatted ); } /** @@ -164,10 +174,10 @@ function number_format_i18n( $number, $decimals = null ) { * @since 2.3.0 * * @param int|string $bytes Number of bytes. Note max integer size for integers. - * @param int $decimals Precision of number of decimal places. + * @param int $decimals Precision of number of decimal places. Deprecated. * @return bool|string False on failure. Number string on success. */ -function size_format( $bytes, $decimals = null ) { +function size_format( $bytes, $decimals = 0 ) { $quant = array( // ========================= Origin ==== 'TB' => 1099511627776, // pow( 1024, 4) @@ -176,7 +186,6 @@ function size_format( $bytes, $decimals = null ) { 'kB' => 1024, // pow( 1024, 1) 'B ' => 1, // pow( 1024, 0) ); - foreach ( $quant as $unit => $mag ) if ( doubleval($bytes) >= $mag ) return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit; @@ -199,24 +208,15 @@ function get_weekstartend( $mysqlstring, $start_of_week = '' ) { $md = substr( $mysqlstring, 5, 2 ); // Mysql string day $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day. $weekday = date( 'w', $day ); // The day of the week from the timestamp - $i = 86400; // One day - if( !is_numeric($start_of_week) ) + if ( !is_numeric($start_of_week) ) $start_of_week = get_option( 'start_of_week' ); if ( $weekday < $start_of_week ) - $weekday = 7 - $start_of_week - $weekday; - - while ( $weekday > $start_of_week ) { - $weekday = date( 'w', $day ); - if ( $weekday < $start_of_week ) - $weekday = 7 - $start_of_week - $weekday; + $weekday += 7; - $day -= 86400; - $i = 0; - } - $week['start'] = $day + 86400 - $i; - $week['end'] = $week['start'] + 604799; - return $week; + $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day + $end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second + return compact( 'start', 'end' ); } /** @@ -242,30 +242,55 @@ function maybe_unserialize( $original ) { * @since 2.0.5 * * @param mixed $data Value to check to see if was serialized. + * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true. * @return bool False if not serialized and true if it was. */ -function is_serialized( $data ) { +function is_serialized( $data, $strict = true ) { // if it isn't a string, it isn't serialized - if ( !is_string( $data ) ) + if ( ! is_string( $data ) ) return false; $data = trim( $data ); - if ( 'N;' == $data ) + if ( 'N;' == $data ) return true; - if ( !preg_match( '/^([adObis]):/', $data, $badions ) ) + $length = strlen( $data ); + if ( $length < 4 ) return false; - switch ( $badions[1] ) { + if ( ':' !== $data[1] ) + return false; + if ( $strict ) { + $lastc = $data[ $length - 1 ]; + if ( ';' !== $lastc && '}' !== $lastc ) + return false; + } else { + $semicolon = strpos( $data, ';' ); + $brace = strpos( $data, '}' ); + // Either ; or } must exist. + if ( false === $semicolon && false === $brace ) + return false; + // But neither must be in the first X characters. + if ( false !== $semicolon && $semicolon < 3 ) + return false; + if ( false !== $brace && $brace < 4 ) + return false; + } + $token = $data[0]; + switch ( $token ) { + case 's' : + if ( $strict ) { + if ( '"' !== $data[ $length - 2 ] ) + return false; + } elseif ( false === strpos( $data, '"' ) ) { + return false; + } + // or else fall through case 'a' : case 'O' : - case 's' : - if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) ) - return true; - break; + return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data ); case 'b' : case 'i' : case 'd' : - if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) ) - return true; - break; + $end = $strict ? '$' : ''; + return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data ); } return false; } @@ -283,1006 +308,360 @@ function is_serialized_string( $data ) { if ( !is_string( $data ) ) return false; $data = trim( $data ); - if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings + $length = strlen( $data ); + if ( $length < 4 ) + return false; + elseif ( ':' !== $data[1] ) + return false; + elseif ( ';' !== $data[$length-1] ) + return false; + elseif ( $data[0] !== 's' ) + return false; + elseif ( '"' !== $data[$length-2] ) + return false; + else return true; - return false; } /** - * Retrieve option value based on setting name. - * - * If the option does not exist or does not have a value, then the return value - * will be false. This is useful to check whether you need to install an option - * and is commonly used during installation of plugin options and to test - * whether upgrading is required. - * - * You can "short-circuit" the retrieval of the option from the database for - * your plugin or core options that aren't protected. You can do so by hooking - * into the 'pre_option_$option' with the $option being replaced by the option - * name. You should not try to override special options, but you will not be - * prevented from doing so. - * - * There is a second filter called 'option_$option' with the $option being - * replaced with the option name. This gives the value as the only parameter. - * - * If the option was serialized, when the option was added and, or updated, then - * it will be unserialized, when it is returned. + * Serialize data, if needed. * - * @since 1.5.0 - * @package WordPress - * @subpackage Option - * @uses apply_filters() Calls 'pre_option_$optionname' false to allow - * overwriting the option value in a plugin. - * @uses apply_filters() Calls 'option_$optionname' with the option name value. + * @since 2.0.5 * - * @param string $setting Name of option to retrieve. Should already be SQL-escaped - * @return mixed Value set for the option. + * @param mixed $data Data that might be serialized. + * @return mixed A scalar data */ -function get_option( $setting, $default = false ) { - global $wpdb; - - // Allow plugins to short-circuit options. - $pre = apply_filters( 'pre_option_' . $setting, false ); - if ( false !== $pre ) - return $pre; - - // prevent non-existent options from triggering multiple queries - $notoptions = wp_cache_get( 'notoptions', 'options' ); - if ( isset( $notoptions[$setting] ) ) - return $default; - - $alloptions = wp_load_alloptions(); - - if ( isset( $alloptions[$setting] ) ) { - $value = $alloptions[$setting]; - } else { - $value = wp_cache_get( $setting, 'options' ); - - if ( false === $value ) { - if ( defined( 'WP_INSTALLING' ) ) - $suppress = $wpdb->suppress_errors(); - // expected_slashed ($setting) - $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" ); - if ( defined( 'WP_INSTALLING' ) ) - $wpdb->suppress_errors($suppress); - - if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values - $value = $row->option_value; - wp_cache_add( $setting, $value, 'options' ); - } else { // option does not exist, so we must cache its non-existence - $notoptions[$setting] = true; - wp_cache_set( 'notoptions', $notoptions, 'options' ); - return $default; - } - } - } - - // If home is not set use siteurl. - if ( 'home' == $setting && '' == $value ) - return get_option( 'siteurl' ); +function maybe_serialize( $data ) { + if ( is_array( $data ) || is_object( $data ) ) + return serialize( $data ); - if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) ) - $value = untrailingslashit( $value ); + // Double serialization is required for backward compatibility. + // See http://core.trac.wordpress.org/ticket/12930 + if ( is_serialized( $data, false ) ) + return serialize( $data ); - return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) ); + return $data; } /** - * Protect WordPress special option from being modified. + * Retrieve post title from XMLRPC XML. * - * Will die if $option is in protected list. Protected options are 'alloptions' - * and 'notoptions' options. + * If the title element is not part of the XML, then the default post title from + * the $post_default_title will be used instead. * - * @since 2.2.0 * @package WordPress - * @subpackage Option + * @subpackage XMLRPC + * @since 0.71 + * + * @global string $post_default_title Default XMLRPC post title. * - * @param string $option Option name. + * @param string $content XMLRPC XML Request content + * @return string Post title */ -function wp_protect_special_option( $option ) { - $protected = array( 'alloptions', 'notoptions' ); - if ( in_array( $option, $protected ) ) - die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) ); +function xmlrpc_getposttitle( $content ) { + global $post_default_title; + if ( preg_match( '/
sys_get_temp_dir()
,
+ * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
+ * before finally defaulting to /tmp/
+ *
+ * In the event that this function does not find a writable location,
+ * It may be overridden by the WP_TEMP_DIR
constant in
+ * your wp-config.php
file.
+ *
+ * @since 2.5.0
+ *
+ * @return string Writable temporary directory
+ */
+function get_temp_dir() {
+ static $temp;
+ if ( defined('WP_TEMP_DIR') )
+ return trailingslashit(WP_TEMP_DIR);
+
+ if ( $temp )
+ return trailingslashit( rtrim( $temp, '\\' ) );
+
+ if ( function_exists('sys_get_temp_dir') ) {
+ $temp = sys_get_temp_dir();
+ if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
+ return trailingslashit( rtrim( $temp, '\\' ) );
+ }
+
+ $temp = ini_get('upload_tmp_dir');
+ if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
+ return trailingslashit( rtrim( $temp, '\\' ) );
+
+ $temp = WP_CONTENT_DIR . '/';
+ if ( is_dir( $temp ) && wp_is_writable( $temp ) )
+ return $temp;
+
+ $temp = '/tmp/';
+ return $temp;
+}
+
+/**
+ * Determine if a directory is writable.
+ *
+ * This function is used to work around certain ACL issues
+ * in PHP primarily affecting Windows Servers.
+ *
+ * @see win_is_writable()
+ *
+ * @since 3.6.0
+ *
+ * @param string $path
+ * @return bool
+ */
+function wp_is_writable( $path ) {
+ if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
+ return win_is_writable( $path );
+ else
+ return @is_writable( $path );
+}
+
+/**
+ * Workaround for Windows bug in is_writable() function
+ *
+ * PHP has issues with Windows ACL's for determine if a
+ * directory is writable or not, this works around them by
+ * checking the ability to open files rather than relying
+ * upon PHP to interprate the OS ACL.
+ *
+ * @link http://bugs.php.net/bug.php?id=27609
+ * @link http://bugs.php.net/bug.php?id=30931
+ *
+ * @since 2.8.0
+ *
+ * @param string $path
+ * @return bool
+ */
+function win_is_writable( $path ) {
+
+ if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
+ return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
+ else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
+ return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
+
+ // check tmp file for read/write capabilities
+ $should_delete_tmp_file = !file_exists( $path );
+ $f = @fopen( $path, 'a' );
+ if ( $f === false )
+ return false;
+ fclose( $f );
+ if ( $should_delete_tmp_file )
+ unlink( $path );
+ return true;
+}
+
/**
* Get an array containing the current upload directory's path and url.
*
@@ -2033,18 +1562,15 @@ function path_join( $base, $path ) {
*/
function wp_upload_dir( $time = null ) {
$siteurl = get_option( 'siteurl' );
- $upload_path = get_option( 'upload_path' );
- $upload_path = trim($upload_path);
- if ( empty($upload_path) ) {
+ $upload_path = trim( get_option( 'upload_path' ) );
+
+ if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
$dir = WP_CONTENT_DIR . '/uploads';
+ } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
+ // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
+ $dir = path_join( ABSPATH, $upload_path );
} else {
$dir = $upload_path;
- if ( 'wp-content/uploads' == $upload_path ) {
- $dir = WP_CONTENT_DIR . '/uploads';
- } elseif ( 0 !== strpos($dir, ABSPATH) ) {
- // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
- $dir = path_join( ABSPATH, $dir );
- }
}
if ( !$url = get_option( 'upload_url_path' ) ) {
@@ -2054,13 +1580,54 @@ function wp_upload_dir( $time = null ) {
$url = trailingslashit( $siteurl ) . $upload_path;
}
- if ( defined('UPLOADS') ) {
+ // Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
+ // We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
+ if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
$dir = ABSPATH . UPLOADS;
$url = trailingslashit( $siteurl ) . UPLOADS;
}
- $bdir = $dir;
- $burl = $url;
+ // If multisite (and if not the main site in a post-MU network)
+ if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
+
+ if ( ! get_site_option( 'ms_files_rewriting' ) ) {
+ // If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
+ // Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
+ // prevents a four-digit ID from conflicting with a year-based directory for the main site.
+ // But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
+ // directory, as they never had wp-content/uploads for the main site.)
+
+ if ( defined( 'MULTISITE' ) )
+ $ms_dir = '/sites/' . get_current_blog_id();
+ else
+ $ms_dir = '/' . get_current_blog_id();
+
+ $dir .= $ms_dir;
+ $url .= $ms_dir;
+
+ } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
+ // Handle the old-form ms-files.php rewriting if the network still has that enabled.
+ // When ms-files rewriting is enabled, then we only listen to UPLOADS when:
+ // 1) we are not on the main site in a post-MU network,
+ // as wp-content/uploads is used there, and
+ // 2) we are not switched, as ms_upload_constants() hardcodes
+ // these constants to reflect the original blog ID.
+ //
+ // Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
+ // (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
+ // as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
+ // rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
+
+ if ( defined( 'BLOGUPLOADDIR' ) )
+ $dir = untrailingslashit( BLOGUPLOADDIR );
+ else
+ $dir = ABSPATH . UPLOADS;
+ $url = trailingslashit( $siteurl ) . 'files';
+ }
+ }
+
+ $basedir = $dir;
+ $baseurl = $url;
$subdir = '';
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
@@ -2075,12 +1642,25 @@ function wp_upload_dir( $time = null ) {
$dir .= $subdir;
$url .= $subdir;
- $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
+ $uploads = apply_filters( 'upload_dir',
+ array(
+ 'path' => $dir,
+ 'url' => $url,
+ 'subdir' => $subdir,
+ 'basedir' => $basedir,
+ 'baseurl' => $baseurl,
+ 'error' => false,
+ ) );
// Make sure we have an uploads dir
if ( ! wp_mkdir_p( $uploads['path'] ) ) {
- $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
- return array( 'error' => $message );
+ if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
+ $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
+ else
+ $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
+
+ $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
+ $uploads['error'] = $message;
}
return $uploads;
@@ -2093,14 +1673,14 @@ function wp_upload_dir( $time = null ) {
* before the extension, and will continue adding numbers until the filename is
* unique.
*
- * The callback must accept two parameters, the first one is the directory and
- * the second is the filename. The callback must be a function.
+ * The callback is passed three parameters, the first one is the directory, the
+ * second is the filename, and the third is the extension.
*
- * @since 2.5
+ * @since 2.5.0
*
* @param string $dir
* @param string $filename
- * @param string $unique_filename_callback Function name, must be a function.
+ * @param mixed $unique_filename_callback Callback.
* @return string New filename, if given wasn't unique.
*/
function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
@@ -2113,12 +1693,12 @@ function wp_unique_filename( $dir, $filename, $unique_filename_callback = null )
$name = basename($filename, $ext);
// edge case: if file is named '.ext', treat as an empty name
- if( $name === $ext )
+ if ( $name === $ext )
$name = '';
- // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
- if ( $unique_filename_callback && function_exists( $unique_filename_callback ) ) {
- $filename = $unique_filename_callback( $dir, $name );
+ // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
+ if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
+ $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
} else {
$number = '';
@@ -2166,17 +1746,20 @@ function wp_unique_filename( $dir, $filename, $unique_filename_callback = null )
* @since 2.0.0
*
* @param string $name
- * @param null $deprecated Not used. Set to null.
+ * @param null $deprecated Never used. Set to null.
* @param mixed $bits File content
* @param string $time Optional. Time formatted in 'yyyy/mm'.
* @return array
*/
function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
+ if ( !empty( $deprecated ) )
+ _deprecated_argument( __FUNCTION__, '2.0' );
+
if ( empty( $name ) )
return array( 'error' => __( 'Empty filename' ) );
$wp_filetype = wp_check_filetype( $name );
- if ( !$wp_filetype['ext'] )
+ if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
return array( 'error' => __( 'Invalid file type' ) );
$upload = wp_upload_dir( $time );
@@ -2184,11 +1767,22 @@ function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
if ( $upload['error'] !== false )
return $upload;
+ $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
+ if ( !is_array( $upload_bits_error ) ) {
+ $upload[ 'error' ] = $upload_bits_error;
+ return $upload;
+ }
+
$filename = wp_unique_filename( $upload['path'], $name );
$new_file = $upload['path'] . "/$filename";
if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
- $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
+ if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
+ $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
+ else
+ $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
+
+ $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
return array( 'error' => $message );
}
@@ -2198,11 +1792,14 @@ function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
@fwrite( $ifp, $bits );
fclose( $ifp );
+ clearstatcache();
+
// Set correct file permissions
$stat = @ stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0007777;
$perms = $perms & 0000666;
@ chmod( $new_file, $perms );
+ clearstatcache();
// Compute the URL
$url = $upload['url'] . "/$filename";
@@ -2221,19 +1818,24 @@ function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
* @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
*/
function wp_ext2type( $ext ) {
- $ext2type = apply_filters('ext2type', array(
- 'audio' => array('aac','ac3','aif','aiff','mp1','mp2','mp3','m3a','m4a','m4b','ogg','ram','wav','wma'),
- 'video' => array('asf','avi','divx','dv','mov','mpg','mpeg','mp4','mpv','ogm','qt','rm','vob','wmv', 'm4v'),
- 'document' => array('doc','docx','pages','odt','rtf','pdf'),
- 'spreadsheet' => array('xls','xlsx','numbers','ods'),
- 'interactive' => array('ppt','pptx','key','odp','swf'),
- 'text' => array('txt'),
- 'archive' => array('tar','bz2','gz','cab','dmg','rar','sea','sit','sqx','zip'),
- 'code' => array('css','html','php','js'),
- ));
+ $ext = strtolower( $ext );
+ $ext2type = apply_filters( 'ext2type', array(
+ 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
+ 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
+ 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
+ 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
+ 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
+ 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
+ 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
+ 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
+ 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
+ ) );
+
foreach ( $ext2type as $type => $exts )
- if ( in_array($ext, $exts) )
+ if ( in_array( $ext, $exts ) )
return $type;
+
+ return null;
}
/**
@@ -2266,166 +1868,201 @@ function wp_check_filetype( $filename, $mimes = null ) {
}
/**
- * Retrieve list of allowed mime types and file extensions.
+ * Attempt to determine the real file type of a file.
+ * If unable to, the file name extension will be used to determine type.
*
- * @since 2.8.6
+ * If it's determined that the extension does not match the file's real type,
+ * then the "proper_filename" value will be set with a proper filename and extension.
*
- * @return array Array of mime types keyed by the file extension regex corresponding to those types.
+ * Currently this function only supports validating images known to getimagesize().
+ *
+ * @since 3.0.0
+ *
+ * @param string $file Full path to the file.
+ * @param string $filename The name of the file (may differ from $file due to $file being in a tmp directory)
+ * @param array $mimes Optional. Key is the file extension with value as the mime type.
+ * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
*/
-function get_allowed_mime_types() {
- static $mimes = false;
-
- if ( !$mimes ) {
- // Accepted MIME types are set here as PCRE unless provided.
- $mimes = apply_filters( 'upload_mimes', array(
- 'jpg|jpeg|jpe' => 'image/jpeg',
- 'gif' => 'image/gif',
- 'png' => 'image/png',
- 'bmp' => 'image/bmp',
- 'tif|tiff' => 'image/tiff',
- 'ico' => 'image/x-icon',
- 'asf|asx|wax|wmv|wmx' => 'video/asf',
- 'avi' => 'video/avi',
- 'divx' => 'video/divx',
- 'flv' => 'video/x-flv',
- 'mov|qt' => 'video/quicktime',
- 'mpeg|mpg|mpe' => 'video/mpeg',
- 'txt|c|cc|h' => 'text/plain',
- 'rtx' => 'text/richtext',
- 'css' => 'text/css',
- 'htm|html' => 'text/html',
- 'mp3|m4a' => 'audio/mpeg',
- 'mp4|m4v' => 'video/mp4',
- 'ra|ram' => 'audio/x-realaudio',
- 'wav' => 'audio/wav',
- 'ogg' => 'audio/ogg',
- 'mid|midi' => 'audio/midi',
- 'wma' => 'audio/wma',
- 'rtf' => 'application/rtf',
- 'js' => 'application/javascript',
- 'pdf' => 'application/pdf',
- 'doc|docx' => 'application/msword',
- 'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint',
- 'wri' => 'application/vnd.ms-write',
- 'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel',
- 'mdb' => 'application/vnd.ms-access',
- 'mpp' => 'application/vnd.ms-project',
- 'swf' => 'application/x-shockwave-flash',
- 'class' => 'application/java',
- 'tar' => 'application/x-tar',
- 'zip' => 'application/zip',
- 'gz|gzip' => 'application/x-gzip',
- 'exe' => 'application/x-msdownload',
- // openoffice formats
- 'odt' => 'application/vnd.oasis.opendocument.text',
- 'odp' => 'application/vnd.oasis.opendocument.presentation',
- 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
- 'odg' => 'application/vnd.oasis.opendocument.graphics',
- 'odc' => 'application/vnd.oasis.opendocument.chart',
- 'odb' => 'application/vnd.oasis.opendocument.database',
- 'odf' => 'application/vnd.oasis.opendocument.formula',
- ) );
+function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
+
+ $proper_filename = false;
+
+ // Do basic extension validation and MIME mapping
+ $wp_filetype = wp_check_filetype( $filename, $mimes );
+ extract( $wp_filetype );
+
+ // We can't do any further validation without a file to work with
+ if ( ! file_exists( $file ) )
+ return compact( 'ext', 'type', 'proper_filename' );
+
+ // We're able to validate images using GD
+ if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
+
+ // Attempt to figure out what type of image it actually is
+ $imgstats = @getimagesize( $file );
+
+ // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
+ if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
+ // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
+ // You shouldn't need to use this filter, but it's here just in case
+ $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
+ 'image/jpeg' => 'jpg',
+ 'image/png' => 'png',
+ 'image/gif' => 'gif',
+ 'image/bmp' => 'bmp',
+ 'image/tiff' => 'tif',
+ ) );
+
+ // Replace whatever is after the last period in the filename with the correct extension
+ if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
+ $filename_parts = explode( '.', $filename );
+ array_pop( $filename_parts );
+ $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
+ $new_filename = implode( '.', $filename_parts );
+
+ if ( $new_filename != $filename )
+ $proper_filename = $new_filename; // Mark that it changed
+
+ // Redefine the extension / MIME
+ $wp_filetype = wp_check_filetype( $new_filename, $mimes );
+ extract( $wp_filetype );
+ }
+ }
}
- return $mimes;
+ // Let plugins try and validate other types of files
+ // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
+ return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
}
/**
- * Retrieve nonce action "Are you sure" message.
+ * Retrieve list of mime types and file extensions.
*
- * The action is split by verb and noun. The action format is as follows:
- * verb-action_extra. The verb is before the first dash and has the format of
- * letters and no spaces and numbers. The noun is after the dash and before the
- * underscore, if an underscore exists. The noun is also only letters.
+ * @since 3.5.0
*
- * The filter will be called for any action, which is not defined by WordPress.
- * You may use the filter for your plugin to explain nonce actions to the user,
- * when they get the "Are you sure?" message. The filter is in the format of
- * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
- * $noun replaced by the found noun. The two parameters that are given to the
- * hook are the localized "Are you sure you want to do this?" message with the
- * extra text (the text after the underscore).
+ * @uses apply_filters() Calls 'mime_types' on returned array. This filter should
+ * be used to add types, not remove them. To remove types use the upload_mimes filter.
*
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
+ * @return array Array of mime types keyed by the file extension regex corresponding to those types.
+ */
+function wp_get_mime_types() {
+ // Accepted MIME types are set here as PCRE unless provided.
+ return apply_filters( 'mime_types', array(
+ // Image formats
+ 'jpg|jpeg|jpe' => 'image/jpeg',
+ 'gif' => 'image/gif',
+ 'png' => 'image/png',
+ 'bmp' => 'image/bmp',
+ 'tif|tiff' => 'image/tiff',
+ 'ico' => 'image/x-icon',
+ // Video formats
+ 'asf|asx' => 'video/x-ms-asf',
+ 'wmv' => 'video/x-ms-wmv',
+ 'wmx' => 'video/x-ms-wmx',
+ 'wm' => 'video/x-ms-wm',
+ 'avi' => 'video/avi',
+ 'divx' => 'video/divx',
+ 'flv' => 'video/x-flv',
+ 'mov|qt' => 'video/quicktime',
+ 'mpeg|mpg|mpe' => 'video/mpeg',
+ 'mp4|m4v' => 'video/mp4',
+ 'ogv' => 'video/ogg',
+ 'webm' => 'video/webm',
+ 'mkv' => 'video/x-matroska',
+ // Text formats
+ 'txt|asc|c|cc|h' => 'text/plain',
+ 'csv' => 'text/csv',
+ 'tsv' => 'text/tab-separated-values',
+ 'ics' => 'text/calendar',
+ 'rtx' => 'text/richtext',
+ 'css' => 'text/css',
+ 'htm|html' => 'text/html',
+ // Audio formats
+ 'mp3|m4a|m4b' => 'audio/mpeg',
+ 'ra|ram' => 'audio/x-realaudio',
+ 'wav' => 'audio/wav',
+ 'ogg|oga' => 'audio/ogg',
+ 'mid|midi' => 'audio/midi',
+ 'wma' => 'audio/x-ms-wma',
+ 'wax' => 'audio/x-ms-wax',
+ 'mka' => 'audio/x-matroska',
+ // Misc application formats
+ 'rtf' => 'application/rtf',
+ 'js' => 'application/javascript',
+ 'pdf' => 'application/pdf',
+ 'swf' => 'application/x-shockwave-flash',
+ 'class' => 'application/java',
+ 'tar' => 'application/x-tar',
+ 'zip' => 'application/zip',
+ 'gz|gzip' => 'application/x-gzip',
+ 'rar' => 'application/rar',
+ '7z' => 'application/x-7z-compressed',
+ 'exe' => 'application/x-msdownload',
+ // MS Office formats
+ 'doc' => 'application/msword',
+ 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
+ 'wri' => 'application/vnd.ms-write',
+ 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
+ 'mdb' => 'application/vnd.ms-access',
+ 'mpp' => 'application/vnd.ms-project',
+ 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
+ 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
+ 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
+ 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
+ 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
+ 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
+ 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
+ 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
+ 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
+ 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
+ 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
+ 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
+ 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
+ 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
+ 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
+ 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
+ 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
+ // OpenOffice formats
+ 'odt' => 'application/vnd.oasis.opendocument.text',
+ 'odp' => 'application/vnd.oasis.opendocument.presentation',
+ 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
+ 'odg' => 'application/vnd.oasis.opendocument.graphics',
+ 'odc' => 'application/vnd.oasis.opendocument.chart',
+ 'odb' => 'application/vnd.oasis.opendocument.database',
+ 'odf' => 'application/vnd.oasis.opendocument.formula',
+ // WordPerfect formats
+ 'wp|wpd' => 'application/wordperfect',
+ // iWork formats
+ 'key' => 'application/vnd.apple.keynote',
+ 'numbers' => 'application/vnd.apple.numbers',
+ 'pages' => 'application/vnd.apple.pages',
+ ) );
+}
+/**
+ * Retrieve list of allowed mime types and file extensions.
*
- * @param string $action Nonce action.
- * @return string Are you sure message.
- */
-function wp_explain_nonce( $action ) {
- if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
- $verb = $matches[1];
- $noun = $matches[2];
-
- $trans = array();
- $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: “%s” has failed.' ), 'get_the_title' );
-
- $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false );
- $trans['delete']['category'] = array( __( 'Your attempt to delete this category: “%s” has failed.' ), 'get_cat_name' );
- $trans['update']['category'] = array( __( 'Your attempt to edit this category: “%s” has failed.' ), 'get_cat_name' );
-
- $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: “%s” has failed.' ), 'use_id' );
- $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: “%s” has failed.' ), 'use_id' );
- $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: “%s” has failed.' ), 'use_id' );
- $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: “%s” has failed.' ), 'use_id' );
- $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
- $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
-
- $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false );
- $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: “%s” has failed.' ), 'use_id' );
- $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: “%s” has failed.' ), 'use_id' );
- $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false );
-
- $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false );
- $trans['delete']['page'] = array( __( 'Your attempt to delete this page: “%s” has failed.' ), 'get_the_title' );
- $trans['update']['page'] = array( __( 'Your attempt to edit this page: “%s” has failed.' ), 'get_the_title' );
-
- $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: “%s” has failed.' ), 'use_id' );
- $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: “%s” has failed.' ), 'use_id' );
- $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: “%s” has failed.' ), 'use_id' );
- $trans['upgrade']['plugin'] = array( __( 'Your attempt to upgrade this plugin: “%s” has failed.' ), 'use_id' );
-
- $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false );
- $trans['delete']['post'] = array( __( 'Your attempt to delete this post: “%s” has failed.' ), 'get_the_title' );
- $trans['update']['post'] = array( __( 'Your attempt to edit this post: “%s” has failed.' ), 'get_the_title' );
-
- $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false );
- $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false );
- $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false );
- $trans['update']['user'] = array( __( 'Your attempt to edit this user: “%s” has failed.' ), 'get_the_author_meta', 'display_name' );
- $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: “%s” has failed.' ), 'get_the_author_meta', 'display_name' );
-
- $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false );
- $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
- $trans['edit']['file'] = array( __( 'Your attempt to edit this file: “%s” has failed.' ), 'use_id' );
- $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: “%s” has failed.' ), 'use_id' );
- $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: “%s” has failed.' ), 'use_id' );
-
- $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
-
- if ( isset( $trans[$verb][$noun] ) ) {
- if ( !empty( $trans[$verb][$noun][1] ) ) {
- $lookup = $trans[$verb][$noun][1];
- if ( isset($trans[$verb][$noun][2]) )
- $lookup_value = $trans[$verb][$noun][2];
- $object = $matches[4];
- if ( 'use_id' != $lookup ) {
- if ( isset( $lookup_value ) )
- $object = call_user_func( $lookup, $lookup_value, $object );
- else
- $object = call_user_func( $lookup, $object );
- }
- return sprintf( $trans[$verb][$noun][0], esc_html($object) );
- } else {
- return $trans[$verb][$noun][0];
- }
- }
+ * @since 2.8.6
+ *
+ * @uses apply_filters() Calls 'upload_mimes' on returned array
+ * @uses wp_get_upload_mime_types() to fetch the list of mime types
+ *
+ * @param int|WP_User $user Optional. User to check. Defaults to current user.
+ * @return array Array of mime types keyed by the file extension regex corresponding to those types.
+ */
+function get_allowed_mime_types( $user = null ) {
+ $t = wp_get_mime_types();
- return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), isset($matches[4]) ? $matches[4] : '' );
- } else {
- return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
- }
+ unset( $t['swf'], $t['exe'] );
+ if ( function_exists( 'current_user_can' ) )
+ $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
+
+ if ( empty( $unfiltered ) )
+ unset( $t['htm|html'] );
+
+ return apply_filters( 'upload_mimes', $t, $user );
}
/**
@@ -2442,11 +2079,14 @@ function wp_explain_nonce( $action ) {
*/
function wp_nonce_ays( $action ) {
$title = __( 'WordPress Failure Notice' );
- $html = esc_html( wp_explain_nonce( $action ) );
- if ( 'log-out' == $action )
- $html .= "" . sprintf( __( "Do you really want to log out?"), wp_logout_url() ); - elseif ( wp_get_referer() ) - $html .= "
" . __( 'Please try again.' ) . ""; + if ( 'log-out' == $action ) { + $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '
'; + $html .= sprintf( __( "Do you really want to log out?"), wp_logout_url() ); + } else { + $html = __( 'Are you sure you want to do this?' ); + if ( wp_get_referer() ) + $html .= "
" . __( 'Please try again.' ) . ""; + } wp_die( $html, $title, array('response' => 403) ); } @@ -2454,21 +2094,43 @@ function wp_nonce_ays( $action ) { /** * Kill WordPress execution and display HTML message with error message. * - * Call this function complements the die() PHP function. The difference is that + * This function complements the die() PHP function. The difference is that * HTML will be displayed to the user. It is recommended to use this function * only, when the execution should not continue any further. It is not * recommended to call this function very often and try to handle as many errors - * as possible siliently. + * as possible silently. + * + * @since 2.0.4 + * + * @param string $message Error message. + * @param string $title Error title. + * @param string|array $args Optional arguments to control behavior. + */ +function wp_die( $message = '', $title = '', $args = array() ) { + if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) + $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' ); + elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) + $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' ); + else + $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' ); + + call_user_func( $function, $message, $title, $args ); +} + +/** + * Kill WordPress execution and display HTML message with error message. * - * @since 2.0.4 + * This is the default handler for wp_die if you want a custom one for your + * site then you can overload using the wp_die_handler filter in wp_die + * + * @since 3.0.0 + * @access private * * @param string $message Error message. * @param string $title Error title. - * @param string|array $args Optional arguements to control behaviour. + * @param string|array $args Optional arguments to control behavior. */ -function wp_die( $message, $title = '', $args = array() ) { - global $wp_locale; - +function _default_wp_die_handler( $message, $title = '', $args = array() ) { $defaults = array( 'response' => 500 ); $r = wp_parse_args($args, $defaults); @@ -2498,47 +2160,135 @@ function wp_die( $message, $title = '', $args = array() ) { if ( isset( $r['back_link'] ) && $r['back_link'] ) { $back_text = $have_gettext? __('« Back') : '« Back'; - $message .= "\n
"; + $message .= "\n"; } - if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL ) - $admin_dir = WP_SITEURL . '/wp-admin/'; - elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) ) - $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/'; - elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false ) - $admin_dir = ''; - else - $admin_dir = 'wp-admin/'; - - if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) : - if( !headers_sent() ){ - status_header( $r['response'] ); - nocache_headers(); - header( 'Content-Type: text/html; charset=utf-8' ); - } + if ( ! did_action( 'admin_head' ) ) : + if ( !headers_sent() ) { + status_header( $r['response'] ); + nocache_headers(); + header( 'Content-Type: text/html; charset=utf-8' ); + } - if ( empty($title) ) { - $title = $have_gettext? __('WordPress › Error') : 'WordPress › Error'; - } + if ( empty($title) ) + $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error'; - $text_direction = 'ltr'; - if ( isset($r['text_direction']) && $r['text_direction'] == 'rtl' ) $text_direction = 'rtl'; - if ( ( $wp_locale ) && ( 'rtl' == $wp_locale->text_direction ) ) $text_direction = 'rtl'; + $text_direction = 'ltr'; + if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] ) + $text_direction = 'rtl'; + elseif ( function_exists( 'is_rtl' ) && is_rtl() ) + $text_direction = 'rtl'; ?> - - -> + + +>
+ * if ( !empty($deprecated) )
+ * _deprecated_argument( __FUNCTION__, '3.0' );
+ *
+ *
+ * There is a hook deprecated_argument_run that will be called that can be used
+ * to get the backtrace up to what file and function used the deprecated
+ * argument.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * @package WordPress
+ * @subpackage Debug
+ * @since 3.0.0
+ * @access private
+ *
+ * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
+ * and the version in which the argument was deprecated.
+ * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
+ * trigger or false to not trigger error.
+ *
+ * @param string $function The function that was called
+ * @param string $version The version of WordPress that deprecated the argument used
+ * @param string $message Optional. A message regarding the change.
+ */
+function _deprecated_argument( $function, $version, $message = null ) {
+
+ do_action( 'deprecated_argument_run', $function, $message, $version );
+
+ // Allow plugin to filter the output error trigger
+ if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
+ if ( function_exists( '__' ) ) {
+ if ( ! is_null( $message ) )
+ trigger_error( sprintf( __('%1$s was called with an argument that is deprecated since version %2$s! %3$s'), $function, $version, $message ) );
+ else
+ trigger_error( sprintf( __('%1$s was called with an argument that is deprecated since version %2$s with no alternative available.'), $function, $version ) );
+ } else {
+ if ( ! is_null( $message ) )
+ trigger_error( sprintf( '%1$s was called with an argument that is deprecated since version %2$s! %3$s', $function, $version, $message ) );
+ else
+ trigger_error( sprintf( '%1$s was called with an argument that is deprecated since version %2$s with no alternative available.', $function, $version ) );
+ }
+ }
+}
+
+/**
+ * Marks something as being incorrectly called.
+ *
+ * There is a hook doing_it_wrong_run that will be called that can be used
+ * to get the backtrace up to what file and function called the deprecated
+ * function.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * @package WordPress
+ * @subpackage Debug
+ * @since 3.1.0
+ * @access private
+ *
+ * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
+ * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
+ * trigger or false to not trigger error.
+ *
+ * @param string $function The function that was called.
+ * @param string $message A message explaining what has been done incorrectly.
+ * @param string $version The version of WordPress where the message was added.
+ */
+function _doing_it_wrong( $function, $message, $version ) {
+
+ do_action( 'doing_it_wrong_run', $function, $message, $version );
+
+ // Allow plugin to filter the output error trigger
+ if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
+ if ( function_exists( '__' ) ) {
+ $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
+ $message .= ' ' . __( 'Please see Debugging in WordPress for more information.' );
+ trigger_error( sprintf( __( '%1$s was called incorrectly. %2$s %3$s' ), $function, $message, $version ) );
+ } else {
+ $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
+ $message .= ' Please see Debugging in WordPress for more information.';
+ trigger_error( sprintf( '%1$s was called incorrectly. %2$s %3$s', $function, $message, $version ) );
+ }
}
}
/**
- * Is the server running earlier than 1.5.0 version of lighttpd
+ * Is the server running earlier than 1.5.0 version of lighttpd?
*
* @since 2.5.0
*
@@ -3023,7 +3069,7 @@ function is_lighttpd_before_150() {
}
/**
- * Does the specified module exist in the apache config?
+ * Does the specified module exist in the Apache config?
*
* @since 2.5.0
*
@@ -3051,6 +3097,33 @@ function apache_mod_loaded($mod, $default = false) {
return $default;
}
+/**
+ * Check if IIS 7+ supports pretty permalinks.
+ *
+ * @since 2.8.0
+ *
+ * @return bool
+ */
+function iis7_supports_permalinks() {
+ global $is_iis7;
+
+ $supports_permalinks = false;
+ if ( $is_iis7 ) {
+ /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
+ * easily update the xml configuration file, hence we just bail out and tell user that
+ * pretty permalinks cannot be used.
+ *
+ * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
+ * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
+ * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
+ * via ISAPI then pretty permalinks will not work.
+ */
+ $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
+ }
+
+ return apply_filters('iis7_supports_permalinks', $supports_permalinks);
+}
+
/**
* File validates against allowed set of defined rules.
*
@@ -3066,16 +3139,16 @@ function apache_mod_loaded($mod, $default = false) {
* @return int 0 means nothing is wrong, greater than 0 means something was wrong.
*/
function validate_file( $file, $allowed_files = '' ) {
- if ( false !== strpos( $file, '..' ))
+ if ( false !== strpos( $file, '..' ) )
return 1;
- if ( false !== strpos( $file, './' ))
+ if ( false !== strpos( $file, './' ) )
return 1;
- if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
+ if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
return 3;
- if (':' == substr( $file, 1, 1 ))
+ if (':' == substr( $file, 1, 1 ) )
return 2;
return 0;
@@ -3121,7 +3194,7 @@ function force_ssl_login( $force = null ) {
}
/**
- * Whether to force SSL used for the Administration Panels.
+ * Whether to force SSL used for the Administration Screens.
*
* @since 2.6.0
*
@@ -3154,17 +3227,70 @@ function wp_guess_url() {
if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
$url = WP_SITEURL;
} else {
- $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
- $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
+ $abspath_fix = str_replace( '\\', '/', ABSPATH );
+ $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
+
+ // The request is for the admin
+ if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
+ $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
+
+ // The request is for a file in ABSPATH
+ } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
+ // Strip off any file/query params in the path
+ $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
+
+ } else {
+ if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
+ // Request is hitting a file inside ABSPATH
+ $directory = str_replace( ABSPATH, '', $script_filename_dir );
+ // Strip off the sub directory, and any file/query paramss
+ $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
+ } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
+ // Request is hitting a file above ABSPATH
+ $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
+ // Strip off any file/query params from the path, appending the sub directory to the install
+ $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
+ } else {
+ $path = $_SERVER['REQUEST_URI'];
+ }
+ }
+
+ $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
+ $url = $schema . $_SERVER['HTTP_HOST'] . $path;
}
- return $url;
+
+ return rtrim($url, '/');
+}
+
+/**
+ * Temporarily suspend cache additions.
+ *
+ * Stops more data being added to the cache, but still allows cache retrieval.
+ * This is useful for actions, such as imports, when a lot of data would otherwise
+ * be almost uselessly added to the cache.
+ *
+ * Suspension lasts for a single page load at most. Remember to call this
+ * function again if you wish to re-enable cache adds earlier.
+ *
+ * @since 3.3.0
+ *
+ * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
+ * @return bool The current suspend setting
+ */
+function wp_suspend_cache_addition( $suspend = null ) {
+ static $_suspend = false;
+
+ if ( is_bool( $suspend ) )
+ $_suspend = $suspend;
+
+ return $_suspend;
}
/**
* Suspend cache invalidation.
*
- * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
- * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
+ * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
+ * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
* cache when invalidation is suspended.
*
* @since 2.7.0
@@ -3180,172 +3306,119 @@ function wp_suspend_cache_invalidation($suspend = true) {
return $current_suspend;
}
-function get_site_option( $key, $default = false, $use_cache = true ) {
- // Allow plugins to short-circuit site options.
- $pre = apply_filters( 'pre_site_option_' . $key, false );
- if ( false !== $pre )
- return $pre;
-
- $value = get_option($key, $default);
-
- return apply_filters( 'site_option_' . $key, $value );
-}
-
-// expects $key, $value not to be SQL escaped
-function add_site_option( $key, $value ) {
- $value = apply_filters( 'pre_add_site_option_' . $key, $value );
- $result = add_option($key, $value);
- do_action( "add_site_option_{$key}", $key, $value );
- return $result;
-}
-
-function delete_site_option( $key ) {
- $result = delete_option($key);
- do_action( "delete_site_option_{$key}", $key );
- return $result;
-}
-
-// expects $key, $value not to be SQL escaped
-function update_site_option( $key, $value ) {
- $oldvalue = get_site_option( $key );
- $value = apply_filters( 'pre_update_site_option_' . $key, $value, $oldvalue );
- $result = update_option($key, $value);
- do_action( "update_site_option_{$key}", $key, $value );
- return $result;
-}
-
/**
- * Delete a site transient
+ * Whether a site is the main site of the current network.
*
- * @since 2.890
- * @package WordPress
- * @subpackage Transient
+ * @since 3.0.0
*
- * @param string $transient Transient name. Expected to not be SQL-escaped
- * @return bool true if successful, false otherwise
+ * @param int $site_id Optional. Site ID to test. Defaults to current site.
+ * @return bool True if $site_id is the main site of the network, or if not running multisite.
*/
-function delete_site_transient($transient) {
- global $_wp_using_ext_object_cache, $wpdb;
+function is_main_site( $site_id = null ) {
+ // This is the current network's information; 'site' is old terminology.
+ global $current_site;
+
+ if ( ! is_multisite() )
+ return true;
- if ( $_wp_using_ext_object_cache ) {
- return wp_cache_delete($transient, 'site-transient');
- } else {
- $transient = '_site_transient_' . esc_sql($transient);
- return delete_site_option($transient);
- }
+ if ( ! $site_id )
+ $site_id = get_current_blog_id();
+
+ return (int) $site_id === (int) $current_site->blog_id;
}
/**
- * Get the value of a site transient
+ * Whether a network is the main network of the multisite install.
*
- * If the transient does not exist or does not have a value, then the return value
- * will be false.
- *
- * @since 2.9.0
- * @package WordPress
- * @subpackage Transient
+ * @since 3.7.0
*
- * @param string $transient Transient name. Expected to not be SQL-escaped
- * @return mixed Value of transient
+ * @param int $network_id Optional. Network ID to test. Defaults to current network.
+ * @return bool True if $network_id is the main network, or if not running multisite.
*/
-function get_site_transient($transient) {
- global $_wp_using_ext_object_cache, $wpdb;
+function is_main_network( $network_id = null ) {
+ global $wpdb;
+
+ if ( ! is_multisite() )
+ return true;
- $pre = apply_filters( 'pre_site_transient_' . $transient, false );
- if ( false !== $pre )
- return $pre;
+ $current_network_id = (int) get_current_site()->id;
- if ( $_wp_using_ext_object_cache ) {
- $value = wp_cache_get($transient, 'site-transient');
- } else {
- $transient_option = '_site_transient_' . esc_sql($transient);
- $transient_timeout = '_site_transient_timeout_' . esc_sql($transient);
- if ( get_site_option($transient_timeout) < time() ) {
- delete_site_option($transient_option);
- delete_site_option($transient_timeout);
- return false;
- }
+ if ( ! $network_id )
+ $network_id = $current_network_id;
+ $network_id = (int) $network_id;
- $value = get_site_option($transient_option);
- }
+ if ( defined( 'PRIMARY_NETWORK_ID' ) )
+ return $network_id === (int) PRIMARY_NETWORK_ID;
+
+ if ( 1 === $current_network_id )
+ return $network_id === $current_network_id;
+
+ $primary_network_id = (int) wp_cache_get( 'primary_network_id', 'site-options' );
+
+ if ( $primary_network_id )
+ return $network_id === $primary_network_id;
- return apply_filters('site_transient_' . $transient, $value);
+ $primary_network_id = (int) $wpdb->get_var( "SELECT id FROM $wpdb->site ORDER BY id LIMIT 1" );
+ wp_cache_add( 'primary_network_id', $primary_network_id, 'site-options' );
+
+ return $network_id === $primary_network_id;
}
/**
- * Set/update the value of a site transient
+ * Whether global terms are enabled.
*
- * You do not need to serialize values, if the value needs to be serialize, then
- * it will be serialized before it is set.
*
- * @since 2.9.0
+ * @since 3.0.0
* @package WordPress
- * @subpackage Transient
*
- * @param string $transient Transient name. Expected to not be SQL-escaped
- * @param mixed $value Transient value.
- * @param int $expiration Time until expiration in seconds, default 0
- * @return bool False if value was not set and true if value was set.
+ * @return bool True if multisite and global terms enabled
*/
-function set_site_transient($transient, $value, $expiration = 0) {
- global $_wp_using_ext_object_cache, $wpdb;
+function global_terms_enabled() {
+ if ( ! is_multisite() )
+ return false;
- if ( $_wp_using_ext_object_cache ) {
- return wp_cache_set($transient, $value, 'site-transient', $expiration);
- } else {
- $transient_timeout = '_site_transient_timeout_' . $transient;
- $transient = '_site_transient_' . $transient;
- $safe_transient = esc_sql($transient);
- if ( false === get_site_option( $safe_transient ) ) {
- if ( 0 != $expiration )
- add_site_option($transient_timeout, time() + $expiration);
- return add_site_option($transient, $value);
- } else {
- if ( 0 != $expiration )
- update_site_option($transient_timeout, time() + $expiration);
- return update_site_option($transient, $value);
- }
+ static $global_terms = null;
+ if ( is_null( $global_terms ) ) {
+ $filter = apply_filters( 'global_terms_enabled', null );
+ if ( ! is_null( $filter ) )
+ $global_terms = (bool) $filter;
+ else
+ $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
}
+ return $global_terms;
}
/**
- * gmt_offset modification for smart timezone handling
+ * gmt_offset modification for smart timezone handling.
+ *
+ * Overrides the gmt_offset option if we have a timezone_string available.
*
- * Overrides the gmt_offset option if we have a timezone_string available
+ * @since 2.8.0
+ *
+ * @return float|bool
*/
function wp_timezone_override_offset() {
- if ( !wp_timezone_supported() ) {
- return false;
- }
if ( !$timezone_string = get_option( 'timezone_string' ) ) {
return false;
}
- @date_default_timezone_set( $timezone_string );
$timezone_object = timezone_open( $timezone_string );
$datetime_object = date_create();
if ( false === $timezone_object || false === $datetime_object ) {
return false;
}
- return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
+ return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
}
/**
- * Check for PHP timezone support
+ * Sort-helper for timezones.
+ *
+ * @since 2.9.0
+ *
+ * @param array $a
+ * @param array $b
+ * @return int
*/
-function wp_timezone_supported() {
- $support = false;
- if (
- function_exists( 'date_default_timezone_set' ) &&
- function_exists( 'timezone_identifiers_list' ) &&
- function_exists( 'timezone_open' ) &&
- function_exists( 'timezone_offset_get' )
- ) {
- $support = true;
- }
- return apply_filters( 'timezone_support', $support );
-}
-
function _wp_timezone_choice_usort_callback( $a, $b ) {
// Don't use translated versions of Etc
if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
@@ -3385,10 +3458,12 @@ function _wp_timezone_choice_usort_callback( $a, $b ) {
}
/**
- * Gives a nicely formatted list of timezone strings // temporary! Not in final
+ * Gives a nicely formatted list of timezone strings.
*
- * @param $selected_zone string Selected Zone
+ * @since 2.9.0
*
+ * @param string $selected_zone Selected Zone
+ * @return string
*/
function wp_timezone_choice( $selected_zone ) {
static $mo_loaded = false;
@@ -3412,13 +3487,13 @@ function wp_timezone_choice( $selected_zone ) {
// This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
$exists = array(
- 0 => ( isset( $zone[0] ) && $zone[0] ) ? true : false,
- 1 => ( isset( $zone[1] ) && $zone[1] ) ? true : false,
- 2 => ( isset( $zone[2] ) && $zone[2] ) ? true : false
+ 0 => ( isset( $zone[0] ) && $zone[0] ),
+ 1 => ( isset( $zone[1] ) && $zone[1] ),
+ 2 => ( isset( $zone[2] ) && $zone[2] ),
);
- $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] ) ? true : false;
- $exists[4] = ( $exists[1] && $exists[3] ) ? true : false;
- $exists[5] = ( $exists[2] && $exists[3] ) ? true : false;
+ $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
+ $exists[4] = ( $exists[1] && $exists[3] );
+ $exists[5] = ( $exists[2] && $exists[3] );
$zonen[] = array(
'continent' => ( $exists[0] ? $zone[0] : '' ),
@@ -3504,7 +3579,7 @@ function wp_timezone_choice( $selected_zone ) {
if ( $offset_value === $selected_zone )
$selected = 'selected="selected" ';
$structure[] = '";
-
+
}
$structure[] = '';
@@ -3512,11 +3587,14 @@ function wp_timezone_choice( $selected_zone ) {
}
/**
- * Strip close comment and close php tags from file headers used by WP
+ * Strip close comment and close php tags from file headers used by WP.
* See http://core.trac.wordpress.org/ticket/8497
*
- * @since 2.8
-**/
+ * @since 2.8.0
+ *
+ * @param string $str
+ * @return string
+ */
function _cleanup_header_comment($str) {
return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
}
@@ -3525,13 +3603,11 @@ function _cleanup_header_comment($str) {
* Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
*
* @since 2.9.0
- *
- * @return void
*/
function wp_scheduled_delete() {
global $wpdb;
- $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
+ $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
$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);
@@ -3569,29 +3645,21 @@ function wp_scheduled_delete() {
}
/**
- * Parse the file contents to retrieve its metadata.
- *
- * Searches for metadata for a file, such as a plugin or theme. Each piece of
- * metadata must be on its own line. For a field spanning multple lines, it
- * must not have any newlines or only parts of it will be displayed.
+ * Retrieve metadata from a file.
*
- * Some users have issues with opening large files and manipulating the contents
- * for want is usually the first 1kiB or 2kiB. This function stops pulling in
- * the file contents when it has all of the required data.
+ * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
+ * Each piece of metadata must be on its own line. Fields can not span multiple
+ * lines, the value will get cut at the end of the first line.
*
- * The first 8kiB of the file will be pulled in and if the file data is not
- * within that first 8kiB, then the author should correct their plugin file
- * and move the data headers to the top.
+ * If the file data is not within that first 8kiB, then the author should correct
+ * their plugin file and move the data headers to the top.
*
- * The file is assumed to have permissions to allow for scripts to read
- * the file. This is not checked however and the file is only opened for
- * reading.
+ * @see http://codex.wordpress.org/File_Header
*
* @since 2.9.0
- *
* @param string $file Path to the file
- * @param bool $markup If the returned data should have HTML markup applied
- * @param string $context If specified adds filter hook "extra_<$context>_headers"
+ * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
+ * @param string $context If specified adds filter hook "extra_{$context}_headers"
*/
function get_file_data( $file, $default_headers, $context = '' ) {
// We don't need to write to the file, so just open for reading.
@@ -3603,38 +3671,523 @@ function get_file_data( $file, $default_headers, $context = '' ) {
// PHP will close file handle, but we are good citizens.
fclose( $fp );
- if( $context != '' ) {
- $extra_headers = apply_filters( "extra_$context".'_headers', array() );
+ // Make sure we catch CR-only line endings.
+ $file_data = str_replace( "\r", "\n", $file_data );
- $extra_headers = array_flip( $extra_headers );
- foreach( $extra_headers as $key=>$value ) {
- $extra_headers[$key] = $key;
- }
- $all_headers = array_merge($extra_headers, $default_headers);
+ if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
+ $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
+ $all_headers = array_merge( $extra_headers, (array) $default_headers );
} else {
$all_headers = $default_headers;
}
-
foreach ( $all_headers as $field => $regex ) {
- preg_match( '/' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
- if ( !empty( ${$field} ) )
- ${$field} = _cleanup_header_comment( ${$field}[1] );
+ if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
+ $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
else
- ${$field} = '';
+ $all_headers[ $field ] = '';
}
- $file_data = compact( array_keys( $all_headers ) );
-
- return $file_data;
+ return $all_headers;
}
-/*
- * Used internally to tidy up the search terms
- *
- * @private
- * @since 2.9.0
+
+/**
+ * Returns true.
+ *
+ * Useful for returning true to filters easily.
+ *
+ * @since 3.0.0
+ * @see __return_false()
+ * @return bool true
*/
-function _search_terms_tidy($t) {
- return trim($t, "\"'\n\r ");
+function __return_true() {
+ return true;
+}
+
+/**
+ * Returns false.
+ *
+ * Useful for returning false to filters easily.
+ *
+ * @since 3.0.0
+ * @see __return_true()
+ * @return bool false
+ */
+function __return_false() {
+ return false;
+}
+
+/**
+ * Returns 0.
+ *
+ * Useful for returning 0 to filters easily.
+ *
+ * @since 3.0.0
+ * @return int 0
+ */
+function __return_zero() {
+ return 0;
+}
+
+/**
+ * Returns an empty array.
+ *
+ * Useful for returning an empty array to filters easily.
+ *
+ * @since 3.0.0
+ * @return array Empty array
+ */
+function __return_empty_array() {
+ return array();
+}
+
+/**
+ * Returns null.
+ *
+ * Useful for returning null to filters easily.
+ *
+ * @since 3.4.0
+ * @return null
+ */
+function __return_null() {
+ return null;
+}
+
+/**
+ * Returns an empty string.
+ *
+ * Useful for returning an empty string to filters easily.
+ *
+ * @since 3.7.0
+ * @see __return_null()
+ * @return string Empty string
+ */
+function __return_empty_string() {
+ return '';
+}
+
+/**
+ * Send a HTTP header to disable content type sniffing in browsers which support it.
+ *
+ * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
+ * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
+ *
+ * @since 3.0.0
+ * @return none
+ */
+function send_nosniff_header() {
+ @header( 'X-Content-Type-Options: nosniff' );
+}
+
+/**
+ * Returns a MySQL expression for selecting the week number based on the start_of_week option.
+ *
+ * @internal
+ * @since 3.0.0
+ * @param string $column
+ * @return string
+ */
+function _wp_mysql_week( $column ) {
+ switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
+ default :
+ case 0 :
+ return "WEEK( $column, 0 )";
+ case 1 :
+ return "WEEK( $column, 1 )";
+ case 2 :
+ case 3 :
+ case 4 :
+ case 5 :
+ case 6 :
+ return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
+ }
+}
+
+/**
+ * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
+ * @param int $start The ID to start the loop check at
+ * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
+ * @param array $callback_args optional additional arguments to send to $callback
+ * @return array IDs of all members of loop
+ */
+function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
+ $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
+
+ if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
+ return array();
+
+ return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
+}
+
+/**
+ * Uses the "The Tortoise and the Hare" algorithm to detect loops.
+ *
+ * For every step of the algorithm, the hare takes two steps and the tortoise one.
+ * If the hare ever laps the tortoise, there must be a loop.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
+ * @param int $start The ID to start the loop check at
+ * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
+ * @param array $callback_args optional additional arguments to send to $callback
+ * @param bool $_return_loop Return loop members or just detect presence of loop?
+ * Only set to true if you already know the given $start is part of a loop
+ * (otherwise the returned array might include branches)
+ * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
+ */
+function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
+ $tortoise = $hare = $evanescent_hare = $start;
+ $return = array();
+
+ // Set evanescent_hare to one past hare
+ // Increment hare two steps
+ while (
+ $tortoise
+ &&
+ ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
+ &&
+ ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
+ ) {
+ if ( $_return_loop )
+ $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
+
+ // tortoise got lapped - must be a loop
+ if ( $tortoise == $evanescent_hare || $tortoise == $hare )
+ return $_return_loop ? $return : $tortoise;
+
+ // Increment tortoise by one step
+ $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
+ }
+
+ return false;
+}
+
+/**
+ * Send a HTTP header to limit rendering of pages to same origin iframes.
+ *
+ * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
+ *
+ * @since 3.1.3
+ * @return none
+ */
+function send_frame_options_header() {
+ @header( 'X-Frame-Options: SAMEORIGIN' );
+}
+
+/**
+ * Retrieve a list of protocols to allow in HTML attributes.
+ *
+ * @since 3.3.0
+ * @see wp_kses()
+ * @see esc_url()
+ *
+ * @return array Array of allowed protocols
+ */
+function wp_allowed_protocols() {
+ static $protocols;
+
+ if ( empty( $protocols ) ) {
+ $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
+ $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
+ }
+
+ return $protocols;
+}
+
+/**
+ * Return a comma separated string of functions that have been called to get to the current point in code.
+ *
+ * @link http://core.trac.wordpress.org/ticket/19589
+ * @since 3.4.0
+ *
+ * @param string $ignore_class A class to ignore all function calls within - useful when you want to just give info about the callee
+ * @param int $skip_frames A number of stack frames to skip - useful for unwinding back to the source of the issue
+ * @param bool $pretty Whether or not you want a comma separated string or raw array returned
+ * @return string|array Either a string containing a reversed comma separated trace or an array of individual calls.
+ */
+function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
+ if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
+ $trace = debug_backtrace( false );
+ else
+ $trace = debug_backtrace();
+
+ $caller = array();
+ $check_class = ! is_null( $ignore_class );
+ $skip_frames++; // skip this function
+
+ foreach ( $trace as $call ) {
+ if ( $skip_frames > 0 ) {
+ $skip_frames--;
+ } elseif ( isset( $call['class'] ) ) {
+ if ( $check_class && $ignore_class == $call['class'] )
+ continue; // Filter out calls
+
+ $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
+ } else {
+ if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
+ $caller[] = "{$call['function']}('{$call['args'][0]}')";
+ } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
+ $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
+ } else {
+ $caller[] = $call['function'];
+ }
+ }
+ }
+ if ( $pretty )
+ return join( ', ', array_reverse( $caller ) );
+ else
+ return $caller;
+}
+
+/**
+ * Retrieve ids that are not already present in the cache
+ *
+ * @since 3.4.0
+ *
+ * @param array $object_ids ID list
+ * @param string $cache_key The cache bucket to check against
+ *
+ * @return array
+ */
+function _get_non_cached_ids( $object_ids, $cache_key ) {
+ $clean = array();
+ foreach ( $object_ids as $id ) {
+ $id = (int) $id;
+ if ( !wp_cache_get( $id, $cache_key ) ) {
+ $clean[] = $id;
+ }
+ }
+
+ return $clean;
+}
+
+/**
+ * Test if the current device has the capability to upload files.
+ *
+ * @since 3.4.0
+ * @access private
+ *
+ * @return bool true|false
+ */
+function _device_can_upload() {
+ if ( ! wp_is_mobile() )
+ return true;
+
+ $ua = $_SERVER['HTTP_USER_AGENT'];
+
+ if ( strpos($ua, 'iPhone') !== false
+ || strpos($ua, 'iPad') !== false
+ || strpos($ua, 'iPod') !== false ) {
+ return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
+ }
+
+ return true;
+}
+
+/**
+ * Test if a given path is a stream URL
+ *
+ * @param string $path The resource path or URL
+ * @return bool True if the path is a stream URL
+ */
+function wp_is_stream( $path ) {
+ $wrappers = stream_get_wrappers();
+ $wrappers_re = '(' . join('|', $wrappers) . ')';
+
+ return preg_match( "!^$wrappers_re://!", $path ) === 1;
+}
+
+/**
+ * Test if the supplied date is valid for the Gregorian calendar
+ *
+ * @since 3.5.0
+ *
+ * @return bool true|false
+ */
+function wp_checkdate( $month, $day, $year, $source_date ) {
+ return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
+}
+
+/**
+ * Load the auth check for monitoring whether the user is still logged in.
+ *
+ * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
+ *
+ * This is disabled for certain screens where a login screen could cause an
+ * inconvenient interruption. A filter called wp_auth_check_load can be used
+ * for fine-grained control.
+ *
+ * @since 3.6.0
+ */
+function wp_auth_check_load() {
+ if ( ! is_admin() && ! is_user_logged_in() )
+ return;
+
+ if ( defined( 'IFRAME_REQUEST' ) )
+ return;
+
+ $screen = get_current_screen();
+ $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
+ $show = ! in_array( $screen->id, $hidden );
+
+ if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
+ wp_enqueue_style( 'wp-auth-check' );
+ wp_enqueue_script( 'wp-auth-check' );
+
+ add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
+ add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
+ }
+}
+
+/**
+ * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
+ *
+ * @since 3.6.0
+ */
+function wp_auth_check_html() {
+ $login_url = wp_login_url();
+ $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
+ $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
+
+ if ( $same_domain && force_ssl_login() && ! force_ssl_admin() )
+ $same_domain = false;
+
+ // Let plugins change this if they know better.
+ $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
+ $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
+
+ ?>
+
+ [\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
+}
+
+/**
+ * Return a canonical form of the provided charset appropriate for passing to PHP
+ * functions such as htmlspecialchars() and charset html attributes.
+ *
+ * @link http://core.trac.wordpress.org/ticket/23688
+ * @since 3.6.0
+ *
+ * @param string A charset name
+ * @return string The canonical form of the charset
+ */
+function _canonical_charset( $charset ) {
+ if ( 'UTF-8' === $charset || 'utf-8' === $charset || 'utf8' === $charset ||
+ 'UTF8' === $charset )
+ return 'UTF-8';
+
+ if ( 'ISO-8859-1' === $charset || 'iso-8859-1' === $charset ||
+ 'iso8859-1' === $charset || 'ISO8859-1' === $charset )
+ return 'ISO-8859-1';
+
+ return $charset;
+}
+
+/**
+ * Sets the mbstring internal encoding to a binary safe encoding whne func_overload is enabled.
+ *
+ * When mbstring.func_overload is in use for multi-byte encodings, the results from strlen() and
+ * similar functions respect the utf8 characters, causing binary data to return incorrect lengths.
+ *
+ * This function overrides the mbstring encoding to a binary-safe encoding, and resets it to the
+ * users expected encoding afterwards through the `reset_mbstring_encoding` function.
+ *
+ * It is safe to recursively call this function, however each `mbstring_binary_safe_encoding()`
+ * call must be followed up with an equal number of `reset_mbstring_encoding()` calls.
+ *
+ * @see reset_mbstring_encoding()
+ *
+ * @since 3.7.0
+ *
+ * @param bool $reset Whether to reset the encoding back to a previously-set encoding.
+ */
+function mbstring_binary_safe_encoding( $reset = false ) {
+ static $encodings = array();
+ static $overloaded = null;
+
+ if ( is_null( $overloaded ) )
+ $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
+
+ if ( false === $overloaded )
+ return;
+
+ if ( ! $reset ) {
+ $encoding = mb_internal_encoding();
+ array_push( $encodings, $encoding );
+ mb_internal_encoding( 'ISO-8859-1' );
+ }
+
+ if ( $reset && $encodings ) {
+ $encoding = array_pop( $encodings );
+ mb_internal_encoding( $encoding );
+ }
+}
+
+/**
+ * Resets the mbstring internal encoding to a users previously set encoding.
+ *
+ * @see mbstring_binary_safe_encoding()
+ *
+ * @since 3.7.0
+ */
+function reset_mbstring_encoding() {
+ mbstring_binary_safe_encoding( true );
}
-?>