X-Git-Url: https://scripts.mit.edu/gitweb/autoinstalls/wordpress.git/blobdiff_plain/98a4d31e52bd56c908617df281730bd4ba58d110..e0bf0ae6a149125bedfeaf344114a97d5864e74d:/wp-includes/functions.php?ds=sidebyside diff --git a/wp-includes/functions.php b/wp-includes/functions.php index 3984a316..ea774868 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,54 @@ 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; + } 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,1729 +307,1221 @@ 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 - * - * @param string $option Option name. - */ -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 ) ) ); -} - -/** - * Print option value after sanitizing for forms. + * @subpackage XMLRPC + * @since 0.71 * - * @uses attr Sanitizes value. - * @since 1.5.0 - * @package WordPress - * @subpackage Option + * @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 form_option( $option ) { - echo esc_attr(get_option( $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/
*
- * If the feed action does not have a hook, then the function will die with a
- * message telling the visitor that the feed is not valid.
+ * 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.
*
- * It is better to only have one hook for each feed.
+ * @since 2.5.0
*
- * @since 2.1.0
- * @uses $wp_query Used to tell if the use a comment feed.
- * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
+ * @return string Writable temporary directory
*/
-function do_feed() {
- global $wp_query;
+function get_temp_dir() {
+ static $temp;
+ if ( defined('WP_TEMP_DIR') )
+ return trailingslashit(WP_TEMP_DIR);
- $feed = get_query_var( 'feed' );
+ if ( $temp )
+ return trailingslashit( rtrim( $temp, '\\' ) );
- // Remove the pad, if present.
- $feed = preg_replace( '/^_+/', '', $feed );
+ if ( function_exists('sys_get_temp_dir') ) {
+ $temp = sys_get_temp_dir();
+ if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
+ return trailingslashit( rtrim( $temp, '\\' ) );
+ }
- if ( $feed == '' || $feed == 'feed' )
- $feed = get_default_feed();
+ $temp = ini_get('upload_tmp_dir');
+ if ( is_dir( $temp ) && wp_is_writable( $temp ) )
+ return trailingslashit( rtrim( $temp, '\\' ) );
- $hook = 'do_feed_' . $feed;
- if ( !has_action($hook) ) {
- $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), esc_html($feed));
- wp_die($message);
- }
+ $temp = WP_CONTENT_DIR . '/';
+ if ( is_dir( $temp ) && wp_is_writable( $temp ) )
+ return $temp;
- do_action( $hook, $wp_query->is_comment_feed );
+ $temp = '/tmp/';
+ return $temp;
}
/**
- * Load the RDF RSS 0.91 Feed template.
+ * Determine if a directory is writable.
*
- * @since 2.1.0
- */
-function do_feed_rdf() {
- load_template( ABSPATH . WPINC . '/feed-rdf.php' );
-}
-
-/**
- * Load the RSS 1.0 Feed Template
+ * This function is used to work around certain ACL issues
+ * in PHP primarily affecting Windows Servers.
*
- * @since 2.1.0
- */
-function do_feed_rss() {
- load_template( ABSPATH . WPINC . '/feed-rss.php' );
-}
-
-/**
- * Load either the RSS2 comment feed or the RSS2 posts feed.
+ * @see win_is_writable()
*
- * @since 2.1.0
+ * @since 3.6.0
*
- * @param bool $for_comments True for the comment feed, false for normal feed.
+ * @param string $path
+ * @return bool
*/
-function do_feed_rss2( $for_comments ) {
- if ( $for_comments )
- load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
+function wp_is_writable( $path ) {
+ if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
+ return win_is_writable( $path );
else
- load_template( ABSPATH . WPINC . '/feed-rss2.php' );
+ return @is_writable( $path );
}
/**
- * Load either Atom comment feed or Atom posts feed.
+ * Workaround for Windows bug in is_writable() function
*
- * @since 2.1.0
+ * 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.
*
- * @param bool $for_comments True for the comment feed, false for normal feed.
- */
-function do_feed_atom( $for_comments ) {
- if ($for_comments)
- load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
- else
- load_template( ABSPATH . WPINC . '/feed-atom.php' );
-}
-
-/**
- * Display the robot.txt file content.
+ * @link http://bugs.php.net/bug.php?id=27609
+ * @link http://bugs.php.net/bug.php?id=30931
*
- * The echo content should be with usage of the permalinks or for creating the
- * robot.txt file.
+ * @since 2.8.0
*
- * @since 2.1.0
- * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
+ * @param string $path
+ * @return bool
*/
-function do_robots() {
- header( 'Content-Type: text/plain; charset=utf-8' );
+function win_is_writable( $path ) {
- do_action( 'do_robotstxt' );
+ 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' );
- if ( '0' == get_option( 'blog_public' ) ) {
- echo "User-agent: *\n";
- echo "Disallow: /\n";
- } else {
- echo "User-agent: *\n";
- echo "Disallow:\n";
- }
+ // 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;
}
/**
- * Test whether blog is already installed.
+ * Get an array containing the current upload directory's path and url.
*
- * The cache will be checked first. If you have a cache plugin, which saves the
- * cache values, then this will work. If you use the default WordPress cache,
- * and the database goes away, then you might have problems.
+ * Checks the 'upload_path' option, which should be from the web root folder,
+ * and if it isn't empty it will be used. If it is empty, then the path will be
+ * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
+ * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
*
- * Checks for the option siteurl for whether WordPress is installed.
+ * The upload URL path is set either by the 'upload_url_path' option or by using
+ * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
*
- * @since 2.1.0
- * @uses $wpdb
- *
- * @return bool Whether blog is already installed.
- */
-function is_blog_installed() {
- global $wpdb;
-
- // Check cache first. If options table goes away and we have true cached, oh well.
- if ( wp_cache_get( 'is_blog_installed' ) )
- return true;
-
- $suppress = $wpdb->suppress_errors();
- $alloptions = wp_load_alloptions();
- // If siteurl is not set to autoload, check it specifically
- if ( !isset( $alloptions['siteurl'] ) )
- $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
- else
- $installed = $alloptions['siteurl'];
- $wpdb->suppress_errors( $suppress );
-
- $installed = !empty( $installed );
- wp_cache_set( 'is_blog_installed', $installed );
-
- return $installed;
-}
-
-/**
- * Retrieve URL with nonce added to URL query.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @param string $actionurl URL to add nonce action
- * @param string $action Optional. Nonce action name
- * @return string URL with nonce action added.
- */
-function wp_nonce_url( $actionurl, $action = -1 ) {
- $actionurl = str_replace( '&', '&', $actionurl );
- return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
-}
-
-/**
- * Retrieve or display nonce hidden field for forms.
- *
- * The nonce field is used to validate that the contents of the form came from
- * the location on the current site and not somewhere else. The nonce does not
- * offer absolute protection, but should protect against most cases. It is very
- * important to use nonce field in forms.
- *
- * If you set $echo to true and set $referer to true, then you will need to
- * retrieve the {@link wp_referer_field() wp referer field}. If you have the
- * $referer set to true and are echoing the nonce field, it will also echo the
- * referer field.
- *
- * The $action and $name are optional, but if you want to have better security,
- * it is strongly suggested to set those two parameters. It is easier to just
- * call the function without any parameters, because validation of the nonce
- * doesn't require any parameters, but since crackers know what the default is
- * it won't be difficult for them to find a way around your nonce and cause
- * damage.
- *
- * The input name will be whatever $name value you gave. The input value will be
- * the nonce creation value.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @param string $action Optional. Action name.
- * @param string $name Optional. Nonce name.
- * @param bool $referer Optional, default true. Whether to set the referer field for validation.
- * @param bool $echo Optional, default true. Whether to display or return hidden form field.
- * @return string Nonce field.
- */
-function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
- $name = esc_attr( $name );
- $nonce_field = '';
- if ( $echo )
- echo $nonce_field;
-
- if ( $referer )
- wp_referer_field( $echo, 'previous' );
-
- return $nonce_field;
-}
-
-/**
- * Retrieve or display referer hidden field for forms.
- *
- * The referer link is the current Request URI from the server super global. The
- * input name is '_wp_http_referer', in case you wanted to check manually.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @param bool $echo Whether to echo or return the referer field.
- * @return string Referer field.
- */
-function wp_referer_field( $echo = true) {
- $ref = esc_attr( $_SERVER['REQUEST_URI'] );
- $referer_field = '';
-
- if ( $echo )
- echo $referer_field;
- return $referer_field;
-}
-
-/**
- * Retrieve or display original referer hidden field for forms.
- *
- * The input name is '_wp_original_http_referer' and will be either the same
- * value of {@link wp_referer_field()}, if that was posted already or it will
- * be the current page, if it doesn't exist.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @param bool $echo Whether to echo the original http referer
- * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
- * @return string Original referer field.
- */
-function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
- $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
- $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
- $orig_referer_field = '';
- if ( $echo )
- echo $orig_referer_field;
- return $orig_referer_field;
-}
-
-/**
- * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @return string|bool False on failure. Referer URL on success.
- */
-function wp_get_referer() {
- $ref = '';
- if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
- $ref = $_REQUEST['_wp_http_referer'];
- else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
- $ref = $_SERVER['HTTP_REFERER'];
-
- if ( $ref !== $_SERVER['REQUEST_URI'] )
- return $ref;
- return false;
-}
-
-/**
- * Retrieve original referer that was posted, if it exists.
- *
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
- *
- * @return string|bool False if no original referer or original referer if set.
- */
-function wp_get_original_referer() {
- if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
- return $_REQUEST['_wp_original_http_referer'];
- return false;
-}
-
-/**
- * Recursive directory creation based on full path.
- *
- * Will attempt to set permissions on folders.
- *
- * @since 2.0.1
- *
- * @param string $target Full path to attempt to create.
- * @return bool Whether the path was created or not. True if path already exists.
- */
-function wp_mkdir_p( $target ) {
- // from php.net/mkdir user contributed notes
- $target = str_replace( '//', '/', $target );
- if ( file_exists( $target ) )
- return @is_dir( $target );
-
- // Attempting to create the directory may clutter up our display.
- if ( @mkdir( $target ) ) {
- $stat = @stat( dirname( $target ) );
- $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
- @chmod( $target, $dir_perms );
- return true;
- } elseif ( is_dir( dirname( $target ) ) ) {
- return false;
- }
-
- // If the above failed, attempt to create the parent node, then try again.
- if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
- return wp_mkdir_p( $target );
-
- return false;
-}
-
-/**
- * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
- *
- * @since 2.5.0
- *
- * @param string $path File path
- * @return bool True if path is absolute, false is not absolute.
- */
-function path_is_absolute( $path ) {
- // this is definitive if true but fails if $path does not exist or contains a symbolic link
- if ( realpath($path) == $path )
- return true;
-
- if ( strlen($path) == 0 || $path{0} == '.' )
- return false;
-
- // windows allows absolute paths like this
- if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
- return true;
-
- // a path starting with / or \ is absolute; anything else is relative
- return (bool) preg_match('#^[/\\\\]#', $path);
-}
-
-/**
- * Join two filesystem paths together (e.g. 'give me $path relative to $base').
- *
- * If the $path is absolute, then it the full path is returned.
- *
- * @since 2.5.0
- *
- * @param string $base
- * @param string $path
- * @return string The path with the base or absolute path.
- */
-function path_join( $base, $path ) {
- if ( path_is_absolute($path) )
- return $path;
-
- return rtrim($base, '/') . '/' . ltrim($path, '/');
-}
-
-/**
- * Get an array containing the current upload directory's path and url.
- *
- * Checks the 'upload_path' option, which should be from the web root folder,
- * and if it isn't empty it will be used. If it is empty, then the path will be
- * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
- * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
- *
- * The upload URL path is set either by the 'upload_url_path' option or by using
- * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
- *
- * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
- * the administration settings panel), then the time will be used. The format
- * will be year first and then month.
+ * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
+ * the administration settings panel), then the time will be used. The format
+ * will be year first and then month.
*
* If the path couldn't be created, then an error will be returned with the key
* 'error' containing the error message. The error suggests that the parent
@@ -2027,30 +1543,72 @@ 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';
- else
+ } 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;
-
- // $dir is absolute, $path is (maybe) relative to ABSPATH
- $dir = path_join( ABSPATH, $dir );
+ }
if ( !$url = get_option( 'upload_url_path' ) ) {
- if ( empty($upload_path) or ( $upload_path == $dir ) )
+ if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
$url = WP_CONTENT_URL . '/uploads';
else
$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_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' ) ) {
@@ -2065,12 +1623,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;
@@ -2083,14 +1654,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 ) {
@@ -2099,21 +1670,33 @@ function wp_unique_filename( $dir, $filename, $unique_filename_callback = null )
// separate the filename into a name and extension
$info = pathinfo($filename);
- $ext = !empty($info['extension']) ? $info['extension'] : '';
- $name = basename($filename, ".{$ext}");
+ $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
+ $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 = '';
- if ( !empty( $ext ) )
- $ext = ".$ext";
+ // change '.ext' to lower case
+ if ( $ext && strtolower($ext) != $ext ) {
+ $ext2 = strtolower($ext);
+ $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
+
+ // check for both lower and upper case extension or image sub-sizes may be overwritten
+ while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
+ $new_number = $number + 1;
+ $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
+ $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
+ $number = $new_number;
+ }
+ return $filename2;
+ }
while ( file_exists( $dir . "/$filename" ) ) {
if ( '' == "$number$ext" )
@@ -2144,17 +1727,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 );
@@ -2162,11 +1748,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 );
}
@@ -2176,11 +1773,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";
@@ -2199,18 +1799,18 @@ 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'),
+ $ext2type = apply_filters( 'ext2type', array(
+ '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;
}
@@ -2226,56 +1826,8 @@ function wp_ext2type( $ext ) {
* @return array Values with extension first and mime type.
*/
function wp_check_filetype( $filename, $mimes = null ) {
- // Accepted MIME types are set here as PCRE unless provided.
- $mimes = ( is_array( $mimes ) ) ? $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',
- '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',
- )
- );
-
+ if ( empty($mimes) )
+ $mimes = get_allowed_mime_types();
$type = false;
$ext = false;
@@ -2292,101 +1844,201 @@ function wp_check_filetype( $filename, $mimes = null ) {
}
/**
- * Retrieve nonce action "Are you sure" message.
+ * Attempt to determine the real file type of a file.
+ * If unable to, the file name extension will be used to determine type.
*
- * 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.
+ * 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.
*
- * 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).
+ * Currently this function only supports validating images known to getimagesize().
*
- * @package WordPress
- * @subpackage Security
- * @since 2.0.4
+ * @since 3.0.0
*
- * @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];
+ * @param string $file Full path to the image.
+ * @param string $filename The filename of the image (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 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 apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), $matches[4] );
- } else {
- return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
}
+
+ // 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 list of mime types and file extensions.
+ *
+ * @since 3.5.0
+ *
+ * @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.
+ *
+ * @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.
+ *
+ * @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();
+
+ 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 );
}
/**
@@ -2403,33 +2055,58 @@ function wp_explain_nonce( $action ) {
*/
function wp_nonce_ays( $action ) {
$title = __( 'WordPress Failure Notice' );
- $html = esc_html( wp_explain_nonce( $action ) );
- if ( wp_get_referer() )
- $html .= "" . __( 'Please try again.' ) . ""; - elseif ( 'log-out' == $action ) - $html .= "
" . sprintf( __( "Do you really want to log out?"), wp_logout_url() ); + 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); + wp_die( $html, $title, array('response' => 403) ); } /** * 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 arguements to control behaviour. + * @param string|array $args Optional arguments to control behavior. */ -function wp_die( $message, $title = '', $args = array() ) { - global $wp_locale; +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. + * + * 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 arguments to control behavior. + */ +function _default_wp_die_handler( $message, $title = '', $args = array() ) { $defaults = array( 'response' => 500 ); $r = wp_parse_args($args, $defaults); @@ -2459,58 +2136,269 @@ 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?
+ *
+ * @since 2.5.0
+ *
+ * @return bool Whether the server is running lighttpd < 1.5.0
+ */
+function is_lighttpd_before_150() {
+ $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
+ $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
+ return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
+}
+
+/**
+ * Does the specified module exist in the Apache config?
+ *
+ * @since 2.5.0
+ *
+ * @param string $mod e.g. mod_rewrite
+ * @param bool $default The default return value if the module is not found
+ * @return bool
+ */
+function apache_mod_loaded($mod, $default = false) {
+ global $is_apache;
+
+ if ( !$is_apache )
+ return false;
+
+ if ( function_exists('apache_get_modules') ) {
+ $mods = apache_get_modules();
+ if ( in_array($mod, $mods) )
+ return true;
+ } elseif ( function_exists('phpinfo') ) {
+ ob_start();
+ phpinfo(8);
+ $phpinfo = ob_get_clean();
+ if ( false !== strpos($phpinfo, $mod) )
+ return true;
+ }
+ 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.
+ *
+ * A return value of '1' means that the $file contains either '..' or './'. A
+ * return value of '2' means that the $file contains ':' after the first
+ * character. A return value of '3' means that the file is not in the allowed
+ * files list.
+ *
+ * @since 1.2.0
+ *
+ * @param string $file File path.
+ * @param array $allowed_files List of allowed files.
+ * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
+ */
+function validate_file( $file, $allowed_files = '' ) {
+ if ( false !== strpos( $file, '..' ) )
+ return 1;
+
+ if ( false !== strpos( $file, './' ) )
+ return 1;
+
+ if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
+ return 3;
+
+ if (':' == substr( $file, 1, 1 ) )
+ return 2;
+
+ return 0;
+}
+
+/**
+ * Determine if SSL is used.
+ *
+ * @since 2.6.0
+ *
+ * @return bool True if SSL, false if not used.
+ */
+function is_ssl() {
+ if ( isset($_SERVER['HTTPS']) ) {
+ if ( 'on' == strtolower($_SERVER['HTTPS']) )
+ return true;
+ if ( '1' == $_SERVER['HTTPS'] )
+ return true;
+ } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Whether SSL login should be forced.
+ *
+ * @since 2.6.0
+ *
+ * @param string|bool $force Optional.
+ * @return bool True if forced, false if not forced.
+ */
+function force_ssl_login( $force = null ) {
+ static $forced = false;
+
+ if ( !is_null( $force ) ) {
+ $old_forced = $forced;
+ $forced = $force;
+ return $old_forced;
+ }
+
+ return $forced;
+}
+
+/**
+ * Whether to force SSL used for the Administration Screens.
+ *
+ * @since 2.6.0
+ *
+ * @param string|bool $force
+ * @return bool True if forced, false if not forced.
+ */
+function force_ssl_admin( $force = null ) {
+ static $forced = false;
+
+ if ( !is_null( $force ) ) {
+ $old_forced = $forced;
+ $forced = $force;
+ return $old_forced;
+ }
+
+ return $forced;
+}
+
+/**
+ * Guess the URL for the site.
+ *
+ * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
+ * directory.
+ *
+ * @since 2.6.0
+ *
+ * @return string
+ */
+function wp_guess_url() {
+ if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
+ $url = WP_SITEURL;
+ } else {
+ $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
+ $url = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
+ }
+
+ 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
+ * cache when invalidation is suspended.
+ *
+ * @since 2.7.0
+ *
+ * @param bool $suspend Whether to suspend or enable cache invalidation
+ * @return bool The current suspend setting
+ */
+function wp_suspend_cache_invalidation($suspend = true) {
+ global $_wp_suspend_cache_invalidation;
+
+ $current_suspend = $_wp_suspend_cache_invalidation;
+ $_wp_suspend_cache_invalidation = $suspend;
+ return $current_suspend;
+}
+
+/**
+ * Is main site?
+ *
+ *
+ * @since 3.0.0
+ * @package WordPress
+ *
+ * @param int $blog_id optional blog id to test (default current blog)
+ * @return bool True if not multisite or $blog_id is main site
+ */
+function is_main_site( $blog_id = '' ) {
+ global $current_site;
+
+ if ( ! is_multisite() )
+ return true;
+
+ if ( ! $blog_id )
+ $blog_id = get_current_blog_id();
+
+ return $blog_id == $current_site->blog_id;
+}
+
+/**
+ * Whether global terms are enabled.
+ *
+ *
+ * @since 3.0.0
+ * @package WordPress
+ *
+ * @return bool True if multisite and global terms enabled
+ */
+function global_terms_enabled() {
+ if ( ! is_multisite() )
+ return false;
+
+ 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.
+ *
+ * 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 ( !$timezone_string = get_option( 'timezone_string' ) ) {
+ return false;
+ }
+
+ $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 ) / HOUR_IN_SECONDS, 2 );
+}
+
+/**
+ * {@internal Missing Short Description}}
+ *
+ * @since 2.9.0
+ *
+ * @param unknown_type $a
+ * @param unknown_type $b
+ * @return int
+ */
+function _wp_timezone_choice_usort_callback( $a, $b ) {
+ // Don't use translated versions of Etc
+ if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
+ // Make the order of these more like the old dropdown
+ if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
+ return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
+ }
+ if ( 'UTC' === $a['city'] ) {
+ if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
+ return 1;
+ }
+ return -1;
+ }
+ if ( 'UTC' === $b['city'] ) {
+ if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
+ return -1;
+ }
+ return 1;
+ }
+ return strnatcasecmp( $a['city'], $b['city'] );
+ }
+ if ( $a['t_continent'] == $b['t_continent'] ) {
+ if ( $a['t_city'] == $b['t_city'] ) {
+ return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
+ }
+ return strnatcasecmp( $a['t_city'], $b['t_city'] );
+ } else {
+ // Force Etc to the bottom of the list
+ if ( 'Etc' === $a['continent'] ) {
+ return 1;
+ }
+ if ( 'Etc' === $b['continent'] ) {
+ return -1;
+ }
+ return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
+ }
+}
+
+/**
+ * Gives a nicely formatted list of timezone strings.
+ *
+ * @since 2.9.0
+ *
+ * @param string $selected_zone Selected Zone
+ * @return string
+ */
+function wp_timezone_choice( $selected_zone ) {
+ static $mo_loaded = false;
+
+ $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
+
+ // Load translations for continents and cities
+ if ( !$mo_loaded ) {
+ $locale = get_locale();
+ $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
+ load_textdomain( 'continents-cities', $mofile );
+ $mo_loaded = true;
+ }
+
+ $zonen = array();
+ foreach ( timezone_identifiers_list() as $zone ) {
+ $zone = explode( '/', $zone );
+ if ( !in_array( $zone[0], $continents ) ) {
+ continue;
+ }
+
+ // 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] ),
+ 1 => ( isset( $zone[1] ) && $zone[1] ),
+ 2 => ( isset( $zone[2] ) && $zone[2] ),
+ );
+ $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] : '' ),
+ 'city' => ( $exists[1] ? $zone[1] : '' ),
+ 'subcity' => ( $exists[2] ? $zone[2] : '' ),
+ 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
+ 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
+ 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
+ );
+ }
+ usort( $zonen, '_wp_timezone_choice_usort_callback' );
+
+ $structure = array();
+
+ if ( empty( $selected_zone ) ) {
+ $structure[] = '';
+ }
+
+ foreach ( $zonen as $key => $zone ) {
+ // Build value in an array to join later
+ $value = array( $zone['continent'] );
+
+ if ( empty( $zone['city'] ) ) {
+ // It's at the continent level (generally won't happen)
+ $display = $zone['t_continent'];
+ } else {
+ // It's inside a continent group
- $subchar = '';
- foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
- $firstchar = substr($smiley, 0, 1);
- $rest = substr($smiley, 1);
+ // Continent optgroup
+ if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
+ $label = $zone['t_continent'];
+ $structure[] = '';
+ }
+ }
- if ( is_array( $defaults ) )
- return array_merge( $defaults, $r );
- return $r;
-}
+ // Do UTC
+ $structure[] = '';
+
+ // Do manual UTC offsets
+ $structure[] = '';
+
+ return join( "\n", $structure );
}
/**
- * Flush all output buffers for PHP 5.2.
+ * Strip close comment and close php tags from file headers used by WP.
+ * See http://core.trac.wordpress.org/ticket/8497
*
- * Make sure all output buffers are flushed before our singletons our destroyed.
+ * @since 2.8.0
*
- * @since 2.2.0
+ * @param string $str
+ * @return string
*/
-function wp_ob_end_flush_all() {
- $levels = ob_get_level();
- for ($i=0; $i<$levels; $i++)
- ob_end_flush();
+function _cleanup_header_comment($str) {
+ return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
}
/**
- * Load the correct database class file.
- *
- * This function is used to load the database class file either at runtime or by
- * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
- * defined globally by the inline code in wp-db.php.
+ * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
*
- * @since 2.5.0
- * @global $wpdb WordPress Database Object
+ * @since 2.9.0
*/
-function require_wp_db() {
+function wp_scheduled_delete() {
global $wpdb;
- if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
- require_once( WP_CONTENT_DIR . '/db.php' );
- else
- require_once( ABSPATH . WPINC . '/wp-db.php' );
+
+ $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);
+
+ foreach ( (array) $posts_to_delete as $post ) {
+ $post_id = (int) $post['post_id'];
+ if ( !$post_id )
+ continue;
+
+ $del_post = get_post($post_id);
+
+ if ( !$del_post || 'trash' != $del_post->post_status ) {
+ delete_post_meta($post_id, '_wp_trash_meta_status');
+ delete_post_meta($post_id, '_wp_trash_meta_time');
+ } else {
+ wp_delete_post($post_id);
+ }
+ }
+
+ $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);
+
+ foreach ( (array) $comments_to_delete as $comment ) {
+ $comment_id = (int) $comment['comment_id'];
+ if ( !$comment_id )
+ continue;
+
+ $del_comment = get_comment($comment_id);
+
+ if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
+ delete_comment_meta($comment_id, '_wp_trash_meta_time');
+ delete_comment_meta($comment_id, '_wp_trash_meta_status');
+ } else {
+ wp_delete_comment($comment_id);
+ }
+ }
}
/**
- * Load custom DB error or display WordPress DB error.
+ * Retrieve metadata from a file.
*
- * If a file exists in the wp-content directory named db-error.php, then it will
- * be loaded instead of displaying the WordPress DB error. If it is not found,
- * then the WordPress DB error will be displayed instead.
+ * 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 WordPress DB error sets the HTTP status header to 500 to try to prevent
- * search engines from caching the message. Custom DB messages should do the
- * same.
+ * 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.
*
- * This function was backported to the the WordPress 2.3.2, but originally was
- * added in WordPress 2.5.0.
+ * @see http://codex.wordpress.org/File_Header
*
- * @since 2.3.2
- * @uses $wpdb
+ * @since 2.9.0
+ * @param string $file Path to the file
+ * @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 dead_db() {
- global $wpdb;
+function get_file_data( $file, $default_headers, $context = '' ) {
+ // We don't need to write to the file, so just open for reading.
+ $fp = fopen( $file, 'r' );
- // Load custom DB error template, if present.
- if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
- require_once( WP_CONTENT_DIR . '/db-error.php' );
- die();
- }
+ // Pull only the first 8kiB of the file in.
+ $file_data = fread( $fp, 8192 );
- // If installing or in the admin, provide the verbose message.
- if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
- wp_die($wpdb->error);
+ // PHP will close file handle, but we are good citizens.
+ fclose( $fp );
- // Otherwise, be terse.
- status_header( 500 );
- nocache_headers();
- header( 'Content-Type: text/html; charset=utf-8' );
-?>
-
->
-
-
-