X-Git-Url: https://scripts.mit.edu/gitweb/autoinstalls/wordpress.git/blobdiff_plain/7688c6ba71852cd89123b62b2d57683535e4702a..78ff9d91a14da1f53bd3f1ffcab1264d92359b72:/wp-includes/functions.php
diff --git a/wp-includes/functions.php b/wp-includes/functions.php
index c07069c1..9b0335b6 100644
--- a/wp-includes/functions.php
+++ b/wp-includes/functions.php
@@ -1,634 +1,709 @@
month) && !empty($wp_locale->weekday) && $translate ) {
- $datemonth = $wp_locale->get_month(date('m', $i));
- $datemonth_abbrev = $wp_locale->get_month_abbrev($datemonth);
- $dateweekday = $wp_locale->get_weekday(date('w', $i));
- $dateweekday_abbrev = $wp_locale->get_weekday_abbrev($dateweekday);
- $datemeridiem = $wp_locale->get_meridiem(date('a', $i));
- $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i));
- $dateformatstring = ' '.$dateformatstring;
- $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring);
+ if ( 'U' == $format )
+ return $i;
- $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
- }
- $j = @date($dateformatstring, $i);
- if ( !$j ) {
- // for debug purposes
- // echo $i." ".$mysqlstring;
- }
- return $j;
+ if ( $translate )
+ return date_i18n( $format, $i );
+ else
+ return date( $format, $i );
}
-function current_time($type, $gmt = 0) {
- switch ($type) {
+/**
+ * Retrieve the current time based on specified type.
+ *
+ * The 'mysql' type will return the time in the format for MySQL DATETIME field.
+ * The 'timestamp' type will return the current timestamp.
+ *
+ * If $gmt is set to either '1' or 'true', then both types will use GMT time.
+ * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
+ *
+ * @since 1.0.0
+ *
+ * @param string $type Either 'mysql' or 'timestamp'.
+ * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
+ * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
+ */
+function current_time( $type, $gmt = 0 ) {
+ switch ( $type ) {
case 'mysql':
- if ( $gmt ) $d = gmdate('Y-m-d H:i:s');
- else $d = gmdate('Y-m-d H:i:s', (time() + (get_option('gmt_offset') * 3600)));
- return $d;
+ 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':
- if ( $gmt ) $d = time();
- else $d = time() + (get_option('gmt_offset') * 3600);
- return $d;
+ return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
break;
}
}
-function date_i18n($dateformatstring, $unixtimestamp) {
+/**
+ * Retrieve the date in localized format, based on timestamp.
+ *
+ * If the locale specifies the locale month and weekday, then the locale will
+ * take over the format for the date. If it isn't, then the date format string
+ * will be used instead.
+ *
+ * @since 0.71
+ *
+ * @param string $dateformatstring Format to display the date.
+ * @param int $unixtimestamp Optional. Unix timestamp.
+ * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
+ * @return string The date, translated if locale specifies it.
+ */
+function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
global $wp_locale;
$i = $unixtimestamp;
- if ( (!empty($wp_locale->month)) && (!empty($wp_locale->weekday)) ) {
- $datemonth = $wp_locale->get_month(date('m', $i));
- $datemonth_abbrev = $wp_locale->get_month_abbrev($datemonth);
- $dateweekday = $wp_locale->get_weekday(date('w', $i));
- $dateweekday_abbrev = $wp_locale->get_weekday_abbrev($dateweekday);
- $datemeridiem = $wp_locale->get_meridiem(date('a', $i));
- $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i));
- $dateformatstring = ' '.$dateformatstring;
- $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring);
- $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring);
- $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
+ if ( false === $i ) {
+ if ( ! $gmt )
+ $i = current_time( 'timestamp' );
+ else
+ $i = time();
+ // we should not let date() interfere with our
+ // specially computed timestamp
+ $gmt = true;
+ }
+
+ // store original value for language with untypical grammars
+ // see http://core.trac.wordpress.org/ticket/9396
+ $req_format = $dateformatstring;
+
+ $datefunc = $gmt? 'gmdate' : 'date';
+
+ if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
+ $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
+ $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
+ $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
+ $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
+ $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
+ $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
+ $dateformatstring = ' '.$dateformatstring;
+ $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
+ $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
+ $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
+ $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
+ $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
+ $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
+
+ $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 = @date($dateformatstring, $i);
+ $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);
return $j;
}
-function number_format_i18n($number, $decimals = null) {
+/**
+ * Convert integer number to format based on the locale.
+ *
+ * @since 2.3.0
+ *
+ * @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 = 0 ) {
global $wp_locale;
- // let the user override the precision only
- $decimals = is_null($decimals)? $wp_locale->number_format['decimals'] : intval($decimals);
-
- return number_format($number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep']);
+ $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 );
}
-function size_format($bytes, $decimals = null) {
- // technically the correct unit names for powers of 1024 are KiB, MiB etc
- // see http://en.wikipedia.org/wiki/Byte
+/**
+ * Convert number of bytes largest unit bytes will fit into.
+ *
+ * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
+ * number of bytes to human readable number by taking the number of that unit
+ * that the bytes will go into it. Supports TB value.
+ *
+ * Please note that integers in PHP are limited to 32 bits, unless they are on
+ * 64 bit architecture, then they have 64 bit size. If you need to place the
+ * larger size then what PHP integer type will hold, then use a string. It will
+ * be converted to a double, which should always have 64 bit length.
+ *
+ * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
+ * @link http://en.wikipedia.org/wiki/Byte
+ *
+ * @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. Deprecated.
+ * @return bool|string False on failure. Number string on success.
+ */
+function size_format( $bytes, $decimals = 0 ) {
$quant = array(
- 'TB' => pow(1024, 4),
- 'GB' => pow(1024, 3),
- 'MB' => pow(1024, 2),
- 'kB' => pow(1024, 1),
- 'B' => pow(1024, 0),
+ // ========================= Origin ====
+ 'TB' => 1099511627776, // pow( 1024, 4)
+ 'GB' => 1073741824, // pow( 1024, 3)
+ 'MB' => 1048576, // pow( 1024, 2)
+ '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;
- foreach ($quant as $unit => $mag)
- if ( intval($bytes) >= $mag )
- return number_format_i18n($bytes / $mag, $decimals) . ' ' . $unit;
+ return false;
}
-function get_weekstartend($mysqlstring, $start_of_week) {
- $my = substr($mysqlstring,0,4);
- $mm = substr($mysqlstring,8,2);
- $md = substr($mysqlstring,5,2);
- $day = mktime(0,0,0, $md, $mm, $my);
- $weekday = date('w',$day);
- $i = 86400;
-
- if ( $weekday < get_option('start_of_week') )
- $weekday = 7 - (get_option('start_of_week') - $weekday);
-
- while ($weekday > get_option('start_of_week')) {
- $weekday = date('w',$day);
- if ( $weekday < get_option('start_of_week') )
- $weekday = 7 - (get_option('start_of_week') - $weekday);
-
- $day = $day - 86400;
- $i = 0;
- }
- $week['start'] = $day + 86400 - $i;
- // $week['end'] = $day - $i + 691199;
- $week['end'] = $week['start'] + 604799;
- return $week;
+/**
+ * Get the week start and end from the datetime or date string from mysql.
+ *
+ * @since 0.71
+ *
+ * @param string $mysqlstring Date or datetime field type from mysql.
+ * @param int $start_of_week Optional. Start of the week as an integer.
+ * @return array Keys are 'start' and 'end'.
+ */
+function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
+ $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
+ $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
+ $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
+ if ( !is_numeric($start_of_week) )
+ $start_of_week = get_option( 'start_of_week' );
+
+ if ( $weekday < $start_of_week )
+ $weekday += 7;
+
+ $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' );
}
-function maybe_unserialize($original) {
- if ( is_serialized($original) ) // don't attempt to unserialize data that wasn't serialized going in
- if ( false !== $gm = @ unserialize($original) )
- return $gm;
+/**
+ * Unserialize value only if it was serialized.
+ *
+ * @since 2.0.0
+ *
+ * @param string $original Maybe unserialized original, if is needed.
+ * @return mixed Unserialized data can be any type.
+ */
+function maybe_unserialize( $original ) {
+ if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
+ return @unserialize( $original );
return $original;
}
-function is_serialized($data) {
+/**
+ * Check value to find if it was serialized.
+ *
+ * If $data is not an string, then returned value will always be false.
+ * Serialized data is always a string.
+ *
+ * @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, $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 )
+ $data = trim( $data );
+ if ( 'N;' == $data )
return true;
- if ( !preg_match('/^([adObis]):/', $data, $badions) )
- return false;
- switch ( $badions[1] ) :
- case 'a' :
- case 'O' :
- case 's' :
- if ( preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data) )
- return true;
- break;
- case 'b' :
- case 'i' :
- case 'd' :
- if ( preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data) )
- return true;
- break;
- endswitch;
- return false;
-}
-
-function is_serialized_string($data) {
- // if it isn't a string, it isn't a serialized string
- if ( !is_string($data) )
+ $length = strlen( $data );
+ if ( $length < 4 )
return false;
- $data = trim($data);
- if ( preg_match('/^s:[0-9]+:.*;$/s',$data) ) // this should fetch all serialized strings
- return true;
- return false;
-}
-
-/* Options functions */
-
-// expects $setting to already be SQL-escaped
-function get_option($setting) {
- 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]) )
+ if ( ':' !== $data[1] )
return false;
-
- $alloptions = wp_load_alloptions();
-
- if ( isset($alloptions[$setting]) ) {
- $value = $alloptions[$setting];
+ if ( $strict ) {
+ $lastc = $data[ $length - 1 ];
+ if ( ';' !== $lastc && '}' !== $lastc )
+ return false;
} else {
- $value = wp_cache_get($setting, 'options');
-
- if ( false === $value ) {
- if ( defined('WP_INSTALLING') )
- $show = $wpdb->hide_errors();
- $row = $wpdb->get_row("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1");
- if ( defined('WP_INSTALLING') )
- $wpdb->show_errors($show);
-
- 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');
+ $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;
}
- }
- }
-
- // If home is not set use siteurl.
- if ( 'home' == $setting && '' == $value )
- return get_option('siteurl');
-
- if ( in_array($setting, array('siteurl', 'home', 'category_base', 'tag_base')) )
- $value = untrailingslashit($value);
-
- return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
-}
-
-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'), wp_specialchars($option)));
-}
-
-function form_option($option) {
- echo attribute_escape(get_option($option));
-}
-
-function get_alloptions() {
- global $wpdb, $wp_queries;
- $show = $wpdb->hide_errors();
- if ( !$options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") ) {
- $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
- }
- $wpdb->show_errors($show);
-
- foreach ($options as $option) {
- // "When trying to design a foolproof system,
- // never underestimate the ingenuity of the fools :)" -- Dougal
- if ( 'siteurl' == $option->option_name )
- $option->option_value = preg_replace('|/+$|', '', $option->option_value);
- if ( 'home' == $option->option_name )
- $option->option_value = preg_replace('|/+$|', '', $option->option_value);
- if ( 'category_base' == $option->option_name )
- $option->option_value = preg_replace('|/+$|', '', $option->option_value);
- $value = maybe_unserialize($option->option_value);
- $all_options->{$option->option_name} = apply_filters('pre_option_' . $option->option_name, $value);
- }
- return apply_filters('all_options', $all_options);
-}
-
-function wp_load_alloptions() {
- global $wpdb;
-
- $alloptions = wp_cache_get('alloptions', 'options');
-
- if ( !$alloptions ) {
- $show = $wpdb->hide_errors();
- if ( !$alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") )
- $alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
- $wpdb->show_errors($show);
- $alloptions = array();
- foreach ( (array) $alloptions_db as $o )
- $alloptions[$o->option_name] = $o->option_value;
- wp_cache_add('alloptions', $alloptions, 'options');
+ // or else fall through
+ case 'a' :
+ case 'O' :
+ return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
+ case 'b' :
+ case 'i' :
+ case 'd' :
+ $end = $strict ? '$' : '';
+ return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
}
- return $alloptions;
+ return false;
}
-// expects $option_name to NOT be SQL-escaped
-function update_option($option_name, $newvalue) {
- global $wpdb;
-
- wp_protect_special_option($option_name);
-
- $safe_option_name = $wpdb->escape($option_name);
- $newvalue = sanitize_option($option_name, $newvalue);
-
- if ( is_string($newvalue) )
- $newvalue = trim($newvalue);
-
- // If the new and old values are the same, no need to update.
- $oldvalue = get_option($safe_option_name);
- if ( $newvalue === $oldvalue ) {
+/**
+ * Check whether serialized data is of string type.
+ *
+ * @since 2.0.5
+ *
+ * @param mixed $data Serialized data
+ * @return bool False if not a serialized string, true if it is.
+ */
+function is_serialized_string( $data ) {
+ // if it isn't a string, it isn't a serialized string
+ if ( !is_string( $data ) )
return false;
- }
-
- if ( false === $oldvalue ) {
- add_option($option_name, $newvalue);
- return true;
- }
-
- $notoptions = wp_cache_get('notoptions', 'options');
- if ( is_array($notoptions) && isset($notoptions[$option_name]) ) {
- unset($notoptions[$option_name]);
- wp_cache_set('notoptions', $notoptions, 'options');
- }
-
- $_newvalue = $newvalue;
- $newvalue = maybe_serialize($newvalue);
-
- $alloptions = wp_load_alloptions();
- if ( isset($alloptions[$option_name]) ) {
- $alloptions[$option_name] = $newvalue;
- wp_cache_set('alloptions', $alloptions, 'options');
- } else {
- wp_cache_set($option_name, $newvalue, 'options');
- }
-
- $newvalue = $wpdb->escape($newvalue);
- $option_name = $wpdb->escape($option_name);
- $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
- if ( $wpdb->rows_affected == 1 ) {
- do_action("update_option_{$option_name}", $oldvalue, $_newvalue);
+ $data = trim( $data );
+ $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;
-}
-
-// thx Alex Stapleton, http://alex.vort-x.net/blog/
-// expects $name to NOT be SQL-escaped
-function add_option($name, $value = '', $deprecated = '', $autoload = 'yes') {
- global $wpdb;
-
- wp_protect_special_option($name);
- $safe_name = $wpdb->escape($name);
-
- // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
- $notoptions = wp_cache_get('notoptions', 'options');
- if ( !is_array($notoptions) || !isset($notoptions[$name]) )
- if ( false !== get_option($safe_name) )
- return;
-
- $value = maybe_serialize($value);
- $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
-
- if ( 'yes' == $autoload ) {
- $alloptions = wp_load_alloptions();
- $alloptions[$name] = $value;
- wp_cache_set('alloptions', $alloptions, 'options');
- } else {
- wp_cache_set($name, $value, 'options');
- }
-
- // This option exists now
- $notoptions = wp_cache_get('notoptions', 'options'); // yes, again... we need it to be fresh
- if ( is_array($notoptions) && isset($notoptions[$name]) ) {
- unset($notoptions[$name]);
- wp_cache_set('notoptions', $notoptions, 'options');
- }
-
- $name = $wpdb->escape($name);
- $value = $wpdb->escape($value);
- $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES ('$name', '$value', '$autoload')");
-
- return;
}
-function delete_option($name) {
- global $wpdb;
-
- wp_protect_special_option($name);
-
- // Get the ID, if no ID then return
- $option = $wpdb->get_row("SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'");
- if ( !$option->option_id ) return false;
- $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
- if ( 'yes' == $option->autoload ) {
- $alloptions = wp_load_alloptions();
- if ( isset($alloptions[$name]) ) {
- unset($alloptions[$name]);
- wp_cache_set('alloptions', $alloptions, 'options');
- }
- } else {
- wp_cache_delete($name, 'options');
- }
- return true;
-}
+/**
+ * Serialize data, if needed.
+ *
+ * @since 2.0.5
+ *
+ * @param mixed $data Data that might be serialized.
+ * @return mixed A scalar data
+ */
+function maybe_serialize( $data ) {
+ if ( is_array( $data ) || is_object( $data ) )
+ return serialize( $data );
+
+ // Double serialization is required for backward compatibility.
+ // See http://core.trac.wordpress.org/ticket/12930
+ if ( is_serialized( $data, false ) )
+ return serialize( $data );
-function maybe_serialize($data) {
- if ( is_string($data) )
- $data = trim($data);
- elseif ( is_array($data) || is_object($data) )
- return serialize($data);
- if ( is_serialized($data) )
- return serialize($data);
return $data;
}
-function gzip_compression() {
- if ( !get_option( 'gzipcompression' ) ) {
- return false;
- }
-
- if ( ( ini_get( 'zlib.output_compression' ) == 'On' || ini_get( 'zlib.output_compression_level' ) > 0 ) || ini_get( 'output_handler' ) == 'ob_gzhandler' ) {
- return false;
- }
-
- if ( extension_loaded( 'zlib' ) ) {
- ob_start( 'ob_gzhandler' );
- }
-}
-
-function make_url_footnote($content) {
- preg_match_all('/(.+?)<\/a>/', $content, $matches);
- $j = 0;
- for ($i=0; $isys_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.
+ *
+ * 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 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
+ * directory is not writable by the server.
+ *
+ * On success, the returned array will have many indices:
+ * 'path' - base directory and sub directory or full path to upload directory.
+ * 'url' - base url and sub directory or absolute URL to upload directory.
+ * 'subdir' - sub directory if uploads use year/month folders option is on.
+ * 'basedir' - path without subdir.
+ * 'baseurl' - URL path without subdir.
+ * 'error' - set to false.
+ *
+ * @since 2.0.0
+ * @uses apply_filters() Calls 'upload_dir' on returned array.
+ *
+ * @param string $time Optional. Time formatted in 'yyyy/mm'.
+ * @return array See above for description.
+ */
+function wp_upload_dir( $time = null ) {
+ $siteurl = get_option( 'siteurl' );
+ $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 ( !$url = get_option( 'upload_url_path' ) ) {
+ if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
+ $url = WP_CONTENT_URL . '/uploads';
+ else
+ $url = trailingslashit( $siteurl ) . $upload_path;
+ }
+
+ // 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;
+ $url = trailingslashit( $siteurl ) . UPLOADS;
+ }
+
+ // 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';
+ }
}
- if ( get_option('uploads_use_yearmonth_folders')) {
+ $basedir = $dir;
+ $baseurl = $url;
+
+ $subdir = '';
+ if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
// Generate the yearly and monthly dirs
- $time = current_time( 'mysql' );
+ if ( !$time )
+ $time = current_time( 'mysql' );
$y = substr( $time, 0, 4 );
$m = substr( $time, 5, 2 );
- $dir = $dir . "/$y/$m";
- $url = $url . "/$y/$m";
+ $subdir = "/$y/$m";
}
+ $dir .= $subdir;
+ $url .= $subdir;
+
+ $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( $dir ) ) {
- $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir);
- return array('error' => $message);
+ if ( ! wp_mkdir_p( $uploads['path'] ) ) {
+ 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;
}
- $uploads = array('path' => $dir, 'url' => $url, 'error' => false);
- return apply_filters('upload_dir', $uploads);
+ return $uploads;
}
-function wp_upload_bits($name, $type, $bits) {
- if ( empty($name) )
- return array('error' => __("Empty filename"));
+/**
+ * Get a filename that is sanitized and unique for the given directory.
+ *
+ * If the filename is not unique, then a number will be added to the filename
+ * before the extension, and will continue adding numbers until the filename is
+ * unique.
+ *
+ * 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.0
+ *
+ * @param string $dir
+ * @param string $filename
+ * @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 ) {
+ // sanitize the file name before we begin processing
+ $filename = sanitize_file_name($filename);
+
+ // separate the filename into a name and extension
+ $info = pathinfo($filename);
+ $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 )
+ $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 = '';
+
+ // 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" )
+ $filename = $filename . ++$number . $ext;
+ else
+ $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
+ }
+ }
- $wp_filetype = wp_check_filetype($name);
- if ( !$wp_filetype['ext'] )
- return array('error' => __("Invalid file type"));
+ return $filename;
+}
- $upload = wp_upload_dir();
+/**
+ * Create a file in the upload folder with given content.
+ *
+ * If there is an error, then the key 'error' will exist with the error message.
+ * If success, then the key 'file' will have the unique file path, the 'url' key
+ * will have the link to the new file. and the 'error' key will be set to false.
+ *
+ * This function will not move an uploaded file to the upload folder. It will
+ * create a new file with the content in $bits parameter. If you move the upload
+ * file, read the content of the uploaded file, and then you can give the
+ * filename and content to this function, which will add it to the upload
+ * folder.
+ *
+ * The permissions will be set on the new file automatically by this function.
+ *
+ * @since 2.0.0
+ *
+ * @param string $name
+ * @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'] && ! current_user_can( 'unfiltered_upload' ) )
+ return array( 'error' => __( 'Invalid file type' ) );
+
+ $upload = wp_upload_dir( $time );
if ( $upload['error'] !== false )
return $upload;
- $number = '';
- $filename = $name;
- $path_parts = pathinfo($filename);
- $ext = $path_parts['extension'];
- if ( empty($ext) )
- $ext = '';
- else
- $ext = ".$ext";
- while ( file_exists($upload['path'] . "/$filename") ) {
- if ( '' == "$number$ext" )
- $filename = $filename . ++$number . $ext;
- else
- $filename = str_replace("$number$ext", ++$number . $ext, $filename);
+ $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));
- return array('error' => $message);
+ if ( ! wp_mkdir_p( 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 );
}
- $ifp = @ fopen($new_file, 'wb');
+ $ifp = @ fopen( $new_file, 'wb' );
if ( ! $ifp )
- return array('error' => sprintf(__('Could not write file %s'), $new_file));
+ return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
+
+ @fwrite( $ifp, $bits );
+ fclose( $ifp );
+ clearstatcache();
- $success = @ fwrite($ifp, $bits);
- fclose($ifp);
// Set correct file permissions
- $stat = @ stat(dirname($new_file));
+ $stat = @ stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0007777;
$perms = $perms & 0000666;
- @ chmod($new_file, $perms);
+ @ chmod( $new_file, $perms );
+ clearstatcache();
// Compute the URL
$url = $upload['url'] . "/$filename";
- return array('file' => $new_file, 'url' => $url, 'error' => false);
+ return array( 'file' => $new_file, 'url' => $url, 'error' => false );
}
-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',
- '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|mp4' => 'audio/mpeg',
- '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' => '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',
- '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',
-
- ));
+/**
+ * Retrieve the file type based on the extension name.
+ *
+ * @package WordPress
+ * @since 2.5.0
+ * @uses apply_filters() Calls 'ext2type' hook on default supported types.
+ *
+ * @param string $ext The extension to search.
+ * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
+ */
+function wp_ext2type( $ext ) {
+ $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 ) )
+ return $type;
+
+ return null;
+}
+/**
+ * Retrieve the file type from the file name.
+ *
+ * You can optionally define the mime array, if needed.
+ *
+ * @since 2.0.4
+ *
+ * @param string $filename File name or path.
+ * @param array $mimes Optional. Key is the file extension with value as the mime type.
+ * @return array Values with extension first and mime type.
+ */
+function wp_check_filetype( $filename, $mimes = null ) {
+ if ( empty($mimes) )
+ $mimes = get_allowed_mime_types();
$type = false;
$ext = false;
- foreach ($mimes as $ext_preg => $mime_match) {
+ foreach ( $mimes as $ext_preg => $mime_match ) {
$ext_preg = '!\.(' . $ext_preg . ')$!i';
- if ( preg_match($ext_preg, $filename, $ext_matches) ) {
+ if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
$type = $mime_match;
$ext = $ext_matches[1];
break;
}
}
- return compact('ext', 'type');
-}
-
-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(__('Are you sure you want to edit this attachment: "%s"?'), 'get_the_title');
-
- $trans['add']['category'] = array(__('Are you sure you want to add this category?'), false);
- $trans['delete']['category'] = array(__('Are you sure you want to delete this category: "%s"?'), 'get_catname');
- $trans['update']['category'] = array(__('Are you sure you want to edit this category: "%s"?'), 'get_catname');
-
- $trans['delete']['comment'] = array(__('Are you sure you want to delete this comment: "%s"?'), 'use_id');
- $trans['unapprove']['comment'] = array(__('Are you sure you want to unapprove this comment: "%s"?'), 'use_id');
- $trans['approve']['comment'] = array(__('Are you sure you want to approve this comment: "%s"?'), 'use_id');
- $trans['update']['comment'] = array(__('Are you sure you want to edit this comment: "%s"?'), 'use_id');
- $trans['bulk']['comments'] = array(__('Are you sure you want to bulk modify comments?'), false);
- $trans['moderate']['comments'] = array(__('Are you sure you want to moderate comments?'), false);
-
- $trans['add']['bookmark'] = array(__('Are you sure you want to add this link?'), false);
- $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this link: "%s"?'), 'use_id');
- $trans['update']['bookmark'] = array(__('Are you sure you want to edit this link: "%s"?'), 'use_id');
- $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify links?'), false);
-
- $trans['add']['page'] = array(__('Are you sure you want to add this page?'), false);
- $trans['delete']['page'] = array(__('Are you sure you want to delete this page: "%s"?'), 'get_the_title');
- $trans['update']['page'] = array(__('Are you sure you want to edit this page: "%s"?'), 'get_the_title');
-
- $trans['edit']['plugin'] = array(__('Are you sure you want to edit this plugin file: "%s"?'), 'use_id');
- $trans['activate']['plugin'] = array(__('Are you sure you want to activate this plugin: "%s"?'), 'use_id');
- $trans['deactivate']['plugin'] = array(__('Are you sure you want to deactivate this plugin: "%s"?'), 'use_id');
-
- $trans['add']['post'] = array(__('Are you sure you want to add this post?'), false);
- $trans['delete']['post'] = array(__('Are you sure you want to delete this post: "%s"?'), 'get_the_title');
- $trans['update']['post'] = array(__('Are you sure you want to edit this post: "%s"?'), 'get_the_title');
-
- $trans['add']['user'] = array(__('Are you sure you want to add this user?'), false);
- $trans['delete']['users'] = array(__('Are you sure you want to delete users?'), false);
- $trans['bulk']['users'] = array(__('Are you sure you want to bulk modify users?'), false);
- $trans['update']['user'] = array(__('Are you sure you want to edit this user: "%s"?'), 'get_author_name');
- $trans['update']['profile'] = array(__('Are you sure you want to modify the profile for: "%s"?'), 'get_author_name');
-
- $trans['update']['options'] = array(__('Are you sure you want to edit your settings?'), false);
- $trans['update']['permalink'] = array(__('Are you sure you want to change your permalink structure to: %s?'), 'use_id');
- $trans['edit']['file'] = array(__('Are you sure you want to edit this file: "%s"?'), 'use_id');
- $trans['edit']['theme'] = array(__('Are you sure you want to edit this theme file: "%s"?'), 'use_id');
- $trans['switch']['theme'] = array(__('Are you sure you want to switch to this theme: "%s"?'), 'use_id');
-
- if ( isset($trans[$verb][$noun]) ) {
- if ( !empty($trans[$verb][$noun][1]) ) {
- $lookup = $trans[$verb][$noun][1];
- $object = $matches[4];
- if ( 'use_id' != $lookup )
- $object = call_user_func($lookup, $object);
- return sprintf($trans[$verb][$noun][0], $object);
- } else {
- return $trans[$verb][$noun][0];
+ return compact( 'ext', 'type' );
+}
+
+/**
+ * Attempt to determine the real file type of a file.
+ * If unable to, the file name extension will be used to determine type.
+ *
+ * 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.
+ *
+ * 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 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] );
+ // 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 );
}
-function wp_nonce_ays($action) {
- global $pagenow, $menu, $submenu, $parent_file, $submenu_file;
-
- $adminurl = get_option('siteurl') . '/wp-admin';
- if ( wp_get_referer() )
- $adminurl = clean_url(wp_get_referer());
+/**
+ * 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 );
+}
- $title = __('WordPress Confirmation');
- // Remove extra layer of slashes.
- $_POST = stripslashes_deep($_POST );
- if ( $_POST ) {
- $q = http_build_query($_POST);
- $q = explode( ini_get('arg_separator.output'), $q);
- $html .= "\t\n";
+/**
+ * Display "Are You Sure" message to confirm the action being taken.
+ *
+ * If the action has the nonce explain message, then it will be displayed along
+ * with the "Are you sure?" message.
+ *
+ * @package WordPress
+ * @subpackage Security
+ * @since 2.0.4
+ *
+ * @param string $action The nonce action.
+ */
+function wp_nonce_ays( $action ) {
+ $title = __( 'WordPress Failure Notice' );
+ 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 .= "\t
" . wp_specialchars(wp_explain_nonce($action)) . "
\n\t\n\t" . __( 'Please try again.' ) . ""; } - $html .= "