9 * Converts MySQL DATETIME field to user specified date format.
11 * If $dateformatstring has 'G' value, then gmmktime() function will be used to
12 * make the time. If $dateformatstring is set to 'U', then mktime() function
13 * will be used to make the time.
15 * The $translate will only be used, if it is set to true and it is by default
16 * and if the $wp_locale object has the month and weekday set.
20 * @param string $dateformatstring Either 'G', 'U', or php date format.
21 * @param string $mysqlstring Time from mysql DATETIME field.
22 * @param bool $translate Optional. Default is true. Will switch format to locale.
23 * @return string Date formated by $dateformatstring or locale (if available).
25 function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
30 if ( 'G' == $dateformatstring )
31 return strtotime( $m . ' +0000' );
35 if ( 'U' == $dateformatstring )
39 return date_i18n( $dateformatstring, $i );
41 return date( $dateformatstring, $i );
45 * Retrieve the current time based on specified type.
47 * The 'mysql' type will return the time in the format for MySQL DATETIME field.
48 * The 'timestamp' type will return the current timestamp.
50 * If $gmt is set to either '1' or 'true', then both types will use GMT time.
51 * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
55 * @param string $type Either 'mysql' or 'timestamp'.
56 * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
57 * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
59 function current_time( $type, $gmt = 0 ) {
62 return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
65 return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
71 * Retrieve the date in localized format, based on timestamp.
73 * If the locale specifies the locale month and weekday, then the locale will
74 * take over the format for the date. If it isn't, then the date format string
75 * will be used instead.
79 * @param string $dateformatstring Format to display the date.
80 * @param int $unixtimestamp Optional. Unix timestamp.
81 * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
82 * @return string The date, translated if locale specifies it.
84 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
87 // Sanity check for PHP 5.1.0-
88 if ( false === $i || intval($i) < 0 ) {
90 $i = current_time( 'timestamp' );
93 // we should not let date() interfere with our
94 // specially computed timestamp
98 // store original value for language with untypical grammars
99 // see http://core.trac.wordpress.org/ticket/9396
100 $req_format = $dateformatstring;
102 $datefunc = $gmt? 'gmdate' : 'date';
104 if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
105 $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
106 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
107 $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
108 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
109 $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
110 $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
111 $dateformatstring = ' '.$dateformatstring;
112 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
113 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
114 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
115 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
116 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
117 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
119 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
121 $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
122 $timezone_formats_re = implode( '|', $timezone_formats );
123 if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) && wp_timezone_supported() ) {
124 $timezone_string = get_option( 'timezone_string' );
125 if ( $timezone_string ) {
126 $timezone_object = timezone_open( $timezone_string );
127 $date_object = date_create( null, $timezone_object );
128 foreach( $timezone_formats as $timezone_format ) {
129 if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
130 $formatted = date_format( $date_object, $timezone_format );
131 $dateformatstring = ' '.$dateformatstring;
132 $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
133 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
138 $j = @$datefunc( $dateformatstring, $i );
139 // allow plugins to redo this entirely for languages with untypical grammars
140 $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
145 * Convert integer number to format based on the locale.
149 * @param int $number The number to convert based on locale.
150 * @param int $decimals Precision of the number of decimal places.
151 * @return string Converted number in string format.
153 function number_format_i18n( $number, $decimals = 0 ) {
155 $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
156 return apply_filters( 'number_format_i18n', $formatted );
160 * Convert number of bytes largest unit bytes will fit into.
162 * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
163 * number of bytes to human readable number by taking the number of that unit
164 * that the bytes will go into it. Supports TB value.
166 * Please note that integers in PHP are limited to 32 bits, unless they are on
167 * 64 bit architecture, then they have 64 bit size. If you need to place the
168 * larger size then what PHP integer type will hold, then use a string. It will
169 * be converted to a double, which should always have 64 bit length.
171 * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
172 * @link http://en.wikipedia.org/wiki/Byte
176 * @param int|string $bytes Number of bytes. Note max integer size for integers.
177 * @param int $decimals Precision of number of decimal places. Deprecated.
178 * @return bool|string False on failure. Number string on success.
180 function size_format( $bytes, $decimals = 0 ) {
182 // ========================= Origin ====
183 'TB' => 1099511627776, // pow( 1024, 4)
184 'GB' => 1073741824, // pow( 1024, 3)
185 'MB' => 1048576, // pow( 1024, 2)
186 'kB' => 1024, // pow( 1024, 1)
187 'B ' => 1, // pow( 1024, 0)
189 foreach ( $quant as $unit => $mag )
190 if ( doubleval($bytes) >= $mag )
191 return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
197 * Get the week start and end from the datetime or date string from mysql.
201 * @param string $mysqlstring Date or datetime field type from mysql.
202 * @param int $start_of_week Optional. Start of the week as an integer.
203 * @return array Keys are 'start' and 'end'.
205 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
206 $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
207 $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
208 $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
209 $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
210 $weekday = date( 'w', $day ); // The day of the week from the timestamp
211 if ( !is_numeric($start_of_week) )
212 $start_of_week = get_option( 'start_of_week' );
214 if ( $weekday < $start_of_week )
217 $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
218 $end = $start + 604799; // $start + 7 days - 1 second
219 return compact( 'start', 'end' );
223 * Unserialize value only if it was serialized.
227 * @param string $original Maybe unserialized original, if is needed.
228 * @return mixed Unserialized data can be any type.
230 function maybe_unserialize( $original ) {
231 if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
232 return @unserialize( $original );
237 * Check value to find if it was serialized.
239 * If $data is not an string, then returned value will always be false.
240 * Serialized data is always a string.
244 * @param mixed $data Value to check to see if was serialized.
245 * @return bool False if not serialized and true if it was.
247 function is_serialized( $data ) {
248 // if it isn't a string, it isn't serialized
249 if ( ! is_string( $data ) )
251 $data = trim( $data );
254 $length = strlen( $data );
257 if ( ':' !== $data[1] )
259 $lastc = $data[$length-1];
260 if ( ';' !== $lastc && '}' !== $lastc )
265 if ( '"' !== $data[$length-2] )
269 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
273 return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
279 * Check whether serialized data is of string type.
283 * @param mixed $data Serialized data
284 * @return bool False if not a serialized string, true if it is.
286 function is_serialized_string( $data ) {
287 // if it isn't a string, it isn't a serialized string
288 if ( !is_string( $data ) )
290 $data = trim( $data );
291 if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
297 * Retrieve option value based on name of option.
299 * If the option does not exist or does not have a value, then the return value
300 * will be false. This is useful to check whether you need to install an option
301 * and is commonly used during installation of plugin options and to test
302 * whether upgrading is required.
304 * If the option was serialized then it will be unserialized when it is returned.
309 * @uses apply_filters() Calls 'pre_option_$option' before checking the option.
310 * Any value other than false will "short-circuit" the retrieval of the option
311 * and return the returned value. You should not try to override special options,
312 * but you will not be prevented from doing so.
313 * @uses apply_filters() Calls 'option_$option', after checking the option, with
316 * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
317 * @return mixed Value set for the option.
319 function get_option( $option, $default = false ) {
322 // Allow plugins to short-circuit options.
323 $pre = apply_filters( 'pre_option_' . $option, false );
324 if ( false !== $pre )
327 $option = trim($option);
328 if ( empty($option) )
331 if ( defined( 'WP_SETUP_CONFIG' ) )
334 if ( ! defined( 'WP_INSTALLING' ) ) {
335 // prevent non-existent options from triggering multiple queries
336 $notoptions = wp_cache_get( 'notoptions', 'options' );
337 if ( isset( $notoptions[$option] ) )
340 $alloptions = wp_load_alloptions();
342 if ( isset( $alloptions[$option] ) ) {
343 $value = $alloptions[$option];
345 $value = wp_cache_get( $option, 'options' );
347 if ( false === $value ) {
348 $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
350 // Has to be get_row instead of get_var because of funkiness with 0, false, null values
351 if ( is_object( $row ) ) {
352 $value = $row->option_value;
353 wp_cache_add( $option, $value, 'options' );
354 } else { // option does not exist, so we must cache its non-existence
355 $notoptions[$option] = true;
356 wp_cache_set( 'notoptions', $notoptions, 'options' );
362 $suppress = $wpdb->suppress_errors();
363 $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
364 $wpdb->suppress_errors( $suppress );
365 if ( is_object( $row ) )
366 $value = $row->option_value;
371 // If home is not set use siteurl.
372 if ( 'home' == $option && '' == $value )
373 return get_option( 'siteurl' );
375 if ( in_array( $option, array('siteurl', 'home', 'category_base', 'tag_base') ) )
376 $value = untrailingslashit( $value );
378 return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
382 * Protect WordPress special option from being modified.
384 * Will die if $option is in protected list. Protected options are 'alloptions'
385 * and 'notoptions' options.
391 * @param string $option Option name.
393 function wp_protect_special_option( $option ) {
394 $protected = array( 'alloptions', 'notoptions' );
395 if ( in_array( $option, $protected ) )
396 wp_die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
400 * Print option value after sanitizing for forms.
402 * @uses attr Sanitizes value.
407 * @param string $option Option name.
409 function form_option( $option ) {
410 echo esc_attr( get_option( $option ) );
414 * Loads and caches all autoloaded options, if available or all options.
420 * @return array List of all options.
422 function wp_load_alloptions() {
425 if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
426 $alloptions = wp_cache_get( 'alloptions', 'options' );
430 if ( !$alloptions ) {
431 $suppress = $wpdb->suppress_errors();
432 if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
433 $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
434 $wpdb->suppress_errors($suppress);
435 $alloptions = array();
436 foreach ( (array) $alloptions_db as $o ) {
437 $alloptions[$o->option_name] = $o->option_value;
439 if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
440 wp_cache_add( 'alloptions', $alloptions, 'options' );
447 * Loads and caches certain often requested site options if is_multisite() and a peristent cache is not being used.
453 * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
455 function wp_load_core_site_options( $site_id = null ) {
456 global $wpdb, $_wp_using_ext_object_cache;
458 if ( !is_multisite() || $_wp_using_ext_object_cache || defined( 'WP_INSTALLING' ) )
461 if ( empty($site_id) )
462 $site_id = $wpdb->siteid;
464 $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled' );
466 $core_options_in = "'" . implode("', '", $core_options) . "'";
467 $options = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->sitemeta WHERE meta_key IN ($core_options_in) AND site_id = %d", $site_id) );
469 foreach ( $options as $option ) {
470 $key = $option->meta_key;
471 $cache_key = "{$site_id}:$key";
472 $option->meta_value = maybe_unserialize( $option->meta_value );
474 wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
479 * Update the value of an option that was already added.
481 * You do not need to serialize values. If the value needs to be serialized, then
482 * it will be serialized before it is inserted into the database. Remember,
483 * resources can not be serialized or added as an option.
485 * If the option does not exist, then the option will be added with the option
486 * value, but you will not be able to set whether it is autoloaded. If you want
487 * to set whether an option is autoloaded, then you need to use the add_option().
493 * @uses apply_filters() Calls 'pre_update_option_$option' hook to allow overwriting the
494 * option value to be stored.
495 * @uses do_action() Calls 'update_option' hook before updating the option.
496 * @uses do_action() Calls 'update_option_$option' and 'updated_option' hooks on success.
498 * @param string $option Option name. Expected to not be SQL-escaped.
499 * @param mixed $newvalue Option value. Expected to not be SQL-escaped.
500 * @return bool False if value was not updated and true if value was updated.
502 function update_option( $option, $newvalue ) {
505 $option = trim($option);
506 if ( empty($option) )
509 wp_protect_special_option( $option );
511 if ( is_object($newvalue) )
512 $newvalue = wp_clone($newvalue);
514 $newvalue = sanitize_option( $option, $newvalue );
515 $oldvalue = get_option( $option );
516 $newvalue = apply_filters( 'pre_update_option_' . $option, $newvalue, $oldvalue );
518 // If the new and old values are the same, no need to update.
519 if ( $newvalue === $oldvalue )
522 if ( false === $oldvalue )
523 return add_option( $option, $newvalue );
525 $notoptions = wp_cache_get( 'notoptions', 'options' );
526 if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
527 unset( $notoptions[$option] );
528 wp_cache_set( 'notoptions', $notoptions, 'options' );
531 $_newvalue = $newvalue;
532 $newvalue = maybe_serialize( $newvalue );
534 do_action( 'update_option', $option, $oldvalue, $_newvalue );
535 if ( ! defined( 'WP_INSTALLING' ) ) {
536 $alloptions = wp_load_alloptions();
537 if ( isset( $alloptions[$option] ) ) {
538 $alloptions[$option] = $_newvalue;
539 wp_cache_set( 'alloptions', $alloptions, 'options' );
541 wp_cache_set( $option, $_newvalue, 'options' );
545 $result = $wpdb->update( $wpdb->options, array( 'option_value' => $newvalue ), array( 'option_name' => $option ) );
548 do_action( "update_option_{$option}", $oldvalue, $_newvalue );
549 do_action( 'updated_option', $option, $oldvalue, $_newvalue );
558 * You do not need to serialize values. If the value needs to be serialized, then
559 * it will be serialized before it is inserted into the database. Remember,
560 * resources can not be serialized or added as an option.
562 * You can create options without values and then add values later. Does not
563 * check whether the option has already been added, but does check that you
564 * aren't adding a protected WordPress option. Care should be taken to not name
565 * options the same as the ones which are protected and to not add options
566 * that were already added.
572 * @uses do_action() Calls 'add_option' hook before adding the option.
573 * @uses do_action() Calls 'add_option_$option' and 'added_option' hooks on success.
575 * @param string $option Name of option to add. Expected to not be SQL-escaped.
576 * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
577 * @param mixed $deprecated Optional. Description. Not used anymore.
578 * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
579 * @return null returns when finished.
581 function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
584 if ( !empty( $deprecated ) )
585 _deprecated_argument( __FUNCTION__, '2.3' );
587 $option = trim($option);
588 if ( empty($option) )
591 wp_protect_special_option( $option );
593 if ( is_object($value) )
594 $value = wp_clone($value);
596 $value = sanitize_option( $option, $value );
598 // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
599 $notoptions = wp_cache_get( 'notoptions', 'options' );
600 if ( !is_array( $notoptions ) || !isset( $notoptions[$option] ) )
601 if ( false !== get_option( $option ) )
605 $value = maybe_serialize( $value );
606 $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
607 do_action( 'add_option', $option, $_value );
608 if ( ! defined( 'WP_INSTALLING' ) ) {
609 if ( 'yes' == $autoload ) {
610 $alloptions = wp_load_alloptions();
611 $alloptions[$option] = $value;
612 wp_cache_set( 'alloptions', $alloptions, 'options' );
614 wp_cache_set( $option, $value, 'options' );
618 // This option exists now
619 $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
620 if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
621 unset( $notoptions[$option] );
622 wp_cache_set( 'notoptions', $notoptions, 'options' );
625 $result = $wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", $option, $value, $autoload ) );
628 do_action( "add_option_{$option}", $option, $_value );
629 do_action( 'added_option', $option, $_value );
636 * Removes option by name. Prevents removal of protected WordPress options.
642 * @uses do_action() Calls 'delete_option' hook before option is deleted.
643 * @uses do_action() Calls 'deleted_option' and 'delete_option_$option' hooks on success.
645 * @param string $option Name of option to remove. Expected to not be SQL-escaped.
646 * @return bool True, if option is successfully deleted. False on failure.
648 function delete_option( $option ) {
651 wp_protect_special_option( $option );
653 // Get the ID, if no ID then return
654 $row = $wpdb->get_row( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option ) );
655 if ( is_null( $row ) )
657 do_action( 'delete_option', $option );
658 $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name = %s", $option) );
659 if ( ! defined( 'WP_INSTALLING' ) ) {
660 if ( 'yes' == $row->autoload ) {
661 $alloptions = wp_load_alloptions();
662 if ( is_array( $alloptions ) && isset( $alloptions[$option] ) ) {
663 unset( $alloptions[$option] );
664 wp_cache_set( 'alloptions', $alloptions, 'options' );
667 wp_cache_delete( $option, 'options' );
671 do_action( "delete_option_$option", $option );
672 do_action( 'deleted_option', $option );
683 * @subpackage Transient
685 * @uses do_action() Calls 'delete_transient_$transient' hook before transient is deleted.
686 * @uses do_action() Calls 'deleted_transient' hook on success.
688 * @param string $transient Transient name. Expected to not be SQL-escaped.
689 * @return bool true if successful, false otherwise
691 function delete_transient( $transient ) {
692 global $_wp_using_ext_object_cache;
694 do_action( 'delete_transient_' . $transient, $transient );
696 if ( $_wp_using_ext_object_cache ) {
697 $result = wp_cache_delete( $transient, 'transient' );
699 $option_timeout = '_transient_timeout_' . $transient;
700 $option = '_transient_' . $transient;
701 $result = delete_option( $option );
703 delete_option( $option_timeout );
707 do_action( 'deleted_transient', $transient );
712 * Get the value of a transient
714 * If the transient does not exist or does not have a value, then the return value
717 * @uses apply_filters() Calls 'pre_transient_$transient' hook before checking the transient.
718 * Any value other than false will "short-circuit" the retrieval of the transient
719 * and return the returned value.
720 * @uses apply_filters() Calls 'transient_$option' hook, after checking the transient, with
721 * the transient value.
725 * @subpackage Transient
727 * @param string $transient Transient name. Expected to not be SQL-escaped
728 * @return mixed Value of transient
730 function get_transient( $transient ) {
731 global $_wp_using_ext_object_cache;
733 $pre = apply_filters( 'pre_transient_' . $transient, false );
734 if ( false !== $pre )
737 if ( $_wp_using_ext_object_cache ) {
738 $value = wp_cache_get( $transient, 'transient' );
740 $transient_option = '_transient_' . $transient;
741 if ( ! defined( 'WP_INSTALLING' ) ) {
742 // If option is not in alloptions, it is not autoloaded and thus has a timeout
743 $alloptions = wp_load_alloptions();
744 if ( !isset( $alloptions[$transient_option] ) ) {
745 $transient_timeout = '_transient_timeout_' . $transient;
746 if ( get_option( $transient_timeout ) < time() ) {
747 delete_option( $transient_option );
748 delete_option( $transient_timeout );
754 $value = get_option( $transient_option );
757 return apply_filters( 'transient_' . $transient, $value );
761 * Set/update the value of a transient
763 * You do not need to serialize values. If the value needs to be serialized, then
764 * it will be serialized before it is set.
768 * @subpackage Transient
770 * @uses apply_filters() Calls 'pre_set_transient_$transient' hook to allow overwriting the
771 * transient value to be stored.
772 * @uses do_action() Calls 'set_transient_$transient' and 'setted_transient' hooks on success.
774 * @param string $transient Transient name. Expected to not be SQL-escaped.
775 * @param mixed $value Transient value. Expected to not be SQL-escaped.
776 * @param int $expiration Time until expiration in seconds, default 0
777 * @return bool False if value was not set and true if value was set.
779 function set_transient( $transient, $value, $expiration = 0 ) {
780 global $_wp_using_ext_object_cache;
782 $value = apply_filters( 'pre_set_transient_' . $transient, $value );
784 if ( $_wp_using_ext_object_cache ) {
785 $result = wp_cache_set( $transient, $value, 'transient', $expiration );
787 $transient_timeout = '_transient_timeout_' . $transient;
788 $transient = '_transient_' . $transient;
789 if ( false === get_option( $transient ) ) {
793 add_option( $transient_timeout, time() + $expiration, '', 'no' );
795 $result = add_option( $transient, $value, '', $autoload );
798 update_option( $transient_timeout, time() + $expiration );
799 $result = update_option( $transient, $value );
803 do_action( 'set_transient_' . $transient );
804 do_action( 'setted_transient', $transient );
810 * Saves and restores user interface settings stored in a cookie.
812 * Checks if the current user-settings cookie is updated and stores it. When no
813 * cookie exists (different browser used), adds the last saved cookie restoring
820 function wp_user_settings() {
825 if ( defined('DOING_AJAX') )
828 if ( ! $user = wp_get_current_user() )
831 $settings = get_user_option( 'user-settings', $user->ID );
833 if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
834 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
836 if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
837 if ( $cookie == $settings )
840 $last_time = (int) get_user_option( 'user-settings-time', $user->ID );
841 $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
843 if ( $saved > $last_time ) {
844 update_user_option( $user->ID, 'user-settings', $cookie, false );
845 update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
851 setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
852 setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
853 $_COOKIE['wp-settings-' . $user->ID] = $settings;
857 * Retrieve user interface setting value based on setting name.
863 * @param string $name The name of the setting.
864 * @param string $default Optional default value to return when $name is not set.
865 * @return mixed the last saved user setting or the default value/false if it doesn't exist.
867 function get_user_setting( $name, $default = false ) {
869 $all = get_all_user_settings();
871 return isset($all[$name]) ? $all[$name] : $default;
875 * Add or update user interface setting.
877 * Both $name and $value can contain only ASCII letters, numbers and underscores.
878 * This function has to be used before any output has started as it calls setcookie().
884 * @param string $name The name of the setting.
885 * @param string $value The value for the setting.
886 * @return bool true if set successfully/false if not.
888 function set_user_setting( $name, $value ) {
890 if ( headers_sent() )
893 $all = get_all_user_settings();
894 $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
899 $all[$name] = $value;
901 return wp_set_all_user_settings($all);
905 * Delete user interface settings.
907 * Deleting settings would reset them to the defaults.
908 * This function has to be used before any output has started as it calls setcookie().
914 * @param mixed $names The name or array of names of the setting to be deleted.
915 * @return bool true if deleted successfully/false if not.
917 function delete_user_setting( $names ) {
919 if ( headers_sent() )
922 $all = get_all_user_settings();
923 $names = (array) $names;
925 foreach ( $names as $name ) {
926 if ( isset($all[$name]) ) {
932 if ( isset($deleted) )
933 return wp_set_all_user_settings($all);
939 * Retrieve all user interface settings.
945 * @return array the last saved user settings or empty array.
947 function get_all_user_settings() {
948 global $_updated_user_settings;
950 if ( ! $user = wp_get_current_user() )
953 if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
954 return $_updated_user_settings;
957 if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
958 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
960 if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
961 parse_str($cookie, $all);
964 $option = get_user_option('user-settings', $user->ID);
965 if ( $option && is_string($option) )
966 parse_str( $option, $all );
973 * Private. Set all user interface settings.
979 * @param unknown $all
982 function wp_set_all_user_settings($all) {
983 global $_updated_user_settings;
985 if ( ! $user = wp_get_current_user() )
988 $_updated_user_settings = $all;
990 foreach ( $all as $k => $v ) {
991 $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
992 $settings .= $k . '=' . $v . '&';
995 $settings = rtrim($settings, '&');
997 update_user_option( $user->ID, 'user-settings', $settings, false );
998 update_user_option( $user->ID, 'user-settings-time', time(), false );
1004 * Delete the user settings of the current user.
1006 * @package WordPress
1007 * @subpackage Option
1010 function delete_all_user_settings() {
1011 if ( ! $user = wp_get_current_user() )
1014 update_user_option( $user->ID, 'user-settings', '', false );
1015 setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
1019 * Serialize data, if needed.
1023 * @param mixed $data Data that might be serialized.
1024 * @return mixed A scalar data
1026 function maybe_serialize( $data ) {
1027 if ( is_array( $data ) || is_object( $data ) )
1028 return serialize( $data );
1030 if ( is_serialized( $data ) )
1031 return serialize( $data );
1037 * Retrieve post title from XMLRPC XML.
1039 * If the title element is not part of the XML, then the default post title from
1040 * the $post_default_title will be used instead.
1042 * @package WordPress
1043 * @subpackage XMLRPC
1046 * @global string $post_default_title Default XMLRPC post title.
1048 * @param string $content XMLRPC XML Request content
1049 * @return string Post title
1051 function xmlrpc_getposttitle( $content ) {
1052 global $post_default_title;
1053 if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
1054 $post_title = $matchtitle[1];
1056 $post_title = $post_default_title;
1062 * Retrieve the post category or categories from XMLRPC XML.
1064 * If the category element is not found, then the default post category will be
1065 * used. The return type then would be what $post_default_category. If the
1066 * category is found, then it will always be an array.
1068 * @package WordPress
1069 * @subpackage XMLRPC
1072 * @global string $post_default_category Default XMLRPC post category.
1074 * @param string $content XMLRPC XML Request content
1075 * @return string|array List of categories or category name.
1077 function xmlrpc_getpostcategory( $content ) {
1078 global $post_default_category;
1079 if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
1080 $post_category = trim( $matchcat[1], ',' );
1081 $post_category = explode( ',', $post_category );
1083 $post_category = $post_default_category;
1085 return $post_category;
1089 * XMLRPC XML content without title and category elements.
1091 * @package WordPress
1092 * @subpackage XMLRPC
1095 * @param string $content XMLRPC XML Request content
1096 * @return string XMLRPC XML Request content without title and category elements.
1098 function xmlrpc_removepostdata( $content ) {
1099 $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
1100 $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
1101 $content = trim( $content );
1106 * Open the file handle for debugging.
1108 * This function is used for XMLRPC feature, but it is general purpose enough
1109 * to be used in anywhere.
1111 * @see fopen() for mode options.
1112 * @package WordPress
1115 * @uses $debug Used for whether debugging is enabled.
1117 * @param string $filename File path to debug file.
1118 * @param string $mode Same as fopen() mode parameter.
1119 * @return bool|resource File handle. False on failure.
1121 function debug_fopen( $filename, $mode ) {
1123 if ( 1 == $debug ) {
1124 $fp = fopen( $filename, $mode );
1132 * Write contents to the file used for debugging.
1134 * Technically, this can be used to write to any file handle when the global
1135 * $debug is set to 1 or true.
1137 * @package WordPress
1140 * @uses $debug Used for whether debugging is enabled.
1142 * @param resource $fp File handle for debugging file.
1143 * @param string $string Content to write to debug file.
1145 function debug_fwrite( $fp, $string ) {
1148 fwrite( $fp, $string );
1152 * Close the debugging file handle.
1154 * Technically, this can be used to close any file handle when the global $debug
1155 * is set to 1 or true.
1157 * @package WordPress
1160 * @uses $debug Used for whether debugging is enabled.
1162 * @param resource $fp Debug File handle.
1164 function debug_fclose( $fp ) {
1171 * Check content for video and audio links to add as enclosures.
1173 * Will not add enclosures that have already been added and will
1174 * remove enclosures that are no longer in the post. This is called as
1175 * pingbacks and trackbacks.
1177 * @package WordPress
1182 * @param string $content Post Content
1183 * @param int $post_ID Post ID
1185 function do_enclose( $content, $post_ID ) {
1188 //TODO: Tidy this ghetto code up and make the debug code optional
1189 include_once( ABSPATH . WPINC . '/class-IXR.php' );
1191 $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
1192 $post_links = array();
1193 debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
1195 $pung = get_enclosed( $post_ID );
1198 $gunk = '/#~:.?+=&%@!\-';
1200 $any = $ltrs . $gunk . $punc;
1202 preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
1204 debug_fwrite( $log, 'Post contents:' );
1205 debug_fwrite( $log, $content . "\n" );
1207 foreach ( $pung as $link_test ) {
1208 if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
1209 $mid = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
1210 do_action( 'delete_postmeta', $mid );
1211 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN(%s)", implode( ',', $mid ) ) );
1212 do_action( 'deleted_postmeta', $mid );
1216 foreach ( (array) $post_links_temp[0] as $link_test ) {
1217 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
1218 $test = @parse_url( $link_test );
1219 if ( false === $test )
1221 if ( isset( $test['query'] ) )
1222 $post_links[] = $link_test;
1223 elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
1224 $post_links[] = $link_test;
1228 foreach ( (array) $post_links as $url ) {
1229 if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
1231 if ( $headers = wp_get_http_headers( $url) ) {
1232 $len = (int) $headers['content-length'];
1233 $type = $headers['content-type'];
1234 $allowed_types = array( 'video', 'audio' );
1236 // Check to see if we can figure out the mime type from
1238 $url_parts = @parse_url( $url );
1239 if ( false !== $url_parts ) {
1240 $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
1241 if ( !empty( $extension ) ) {
1242 foreach ( get_allowed_mime_types( ) as $exts => $mime ) {
1243 if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
1251 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
1252 $meta_value = "$url\n$len\n$type\n";
1253 $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
1254 do_action( 'added_postmeta', $wpdb->insert_id, $post_ID, 'enclosure', $meta_value );
1262 * Perform a HTTP HEAD or GET request.
1264 * If $file_path is a writable filename, this will do a GET request and write
1265 * the file to that path.
1269 * @param string $url URL to fetch.
1270 * @param string|bool $file_path Optional. File path to write request to.
1271 * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
1272 * @return bool|string False on failure and string of headers if HEAD request.
1274 function wp_get_http( $url, $file_path = false, $red = 1 ) {
1275 @set_time_limit( 60 );
1281 $options['redirection'] = 5;
1283 if ( false == $file_path )
1284 $options['method'] = 'HEAD';
1286 $options['method'] = 'GET';
1288 $response = wp_remote_request($url, $options);
1290 if ( is_wp_error( $response ) )
1293 $headers = wp_remote_retrieve_headers( $response );
1294 $headers['response'] = $response['response']['code'];
1296 // WP_HTTP no longer follows redirects for HEAD requests.
1297 if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
1298 return wp_get_http( $headers['location'], $file_path, ++$red );
1301 if ( false == $file_path )
1304 // GET request - write it to the supplied filename
1305 $out_fp = fopen($file_path, 'w');
1309 fwrite( $out_fp, $response['body']);
1317 * Retrieve HTTP Headers from URL.
1321 * @param string $url
1322 * @param bool $deprecated Not Used.
1323 * @return bool|string False on failure, headers on success.
1325 function wp_get_http_headers( $url, $deprecated = false ) {
1326 if ( !empty( $deprecated ) )
1327 _deprecated_argument( __FUNCTION__, '2.7' );
1329 $response = wp_remote_head( $url );
1331 if ( is_wp_error( $response ) )
1334 return wp_remote_retrieve_headers( $response );
1338 * Whether today is a new day.
1342 * @uses $previousday Previous day
1344 * @return int 1 when new day, 0 if not a new day.
1346 function is_new_day() {
1347 global $currentday, $previousday;
1348 if ( $currentday != $previousday )
1355 * Build URL query based on an associative and, or indexed array.
1357 * This is a convenient function for easily building url queries. It sets the
1358 * separator to '&' and uses _http_build_query() function.
1360 * @see _http_build_query() Used to build the query
1361 * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
1362 * http_build_query() does.
1366 * @param array $data URL-encode key/value pairs.
1367 * @return string URL encoded string
1369 function build_query( $data ) {
1370 return _http_build_query( $data, null, '&', '', false );
1374 * Retrieve a modified URL query string.
1376 * You can rebuild the URL and append a new query variable to the URL query by
1377 * using this function. You can also retrieve the full URL with query data.
1379 * Adding a single key & value or an associative array. Setting a key value to
1380 * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
1385 * @param mixed $param1 Either newkey or an associative_array
1386 * @param mixed $param2 Either newvalue or oldquery or uri
1387 * @param mixed $param3 Optional. Old query or uri
1388 * @return string New URL query string.
1390 function add_query_arg() {
1392 if ( is_array( func_get_arg(0) ) ) {
1393 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
1394 $uri = $_SERVER['REQUEST_URI'];
1396 $uri = @func_get_arg( 1 );
1398 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
1399 $uri = $_SERVER['REQUEST_URI'];
1401 $uri = @func_get_arg( 2 );
1404 if ( $frag = strstr( $uri, '#' ) )
1405 $uri = substr( $uri, 0, -strlen( $frag ) );
1409 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
1410 $protocol = $matches[0];
1411 $uri = substr( $uri, strlen( $protocol ) );
1416 if ( strpos( $uri, '?' ) !== false ) {
1417 $parts = explode( '?', $uri, 2 );
1418 if ( 1 == count( $parts ) ) {
1422 $base = $parts[0] . '?';
1425 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
1433 wp_parse_str( $query, $qs );
1434 $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
1435 if ( is_array( func_get_arg( 0 ) ) ) {
1436 $kayvees = func_get_arg( 0 );
1437 $qs = array_merge( $qs, $kayvees );
1439 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1442 foreach ( (array) $qs as $k => $v ) {
1447 $ret = build_query( $qs );
1448 $ret = trim( $ret, '?' );
1449 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1450 $ret = $protocol . $base . $ret . $frag;
1451 $ret = rtrim( $ret, '?' );
1456 * Removes an item or list from the query string.
1460 * @param string|array $key Query key or keys to remove.
1461 * @param bool $query When false uses the $_SERVER value.
1462 * @return string New URL query string.
1464 function remove_query_arg( $key, $query=false ) {
1465 if ( is_array( $key ) ) { // removing multiple keys
1466 foreach ( $key as $k )
1467 $query = add_query_arg( $k, false, $query );
1470 return add_query_arg( $key, false, $query );
1474 * Walks the array while sanitizing the contents.
1478 * @param array $array Array to used to walk while sanitizing contents.
1479 * @return array Sanitized $array.
1481 function add_magic_quotes( $array ) {
1482 foreach ( (array) $array as $k => $v ) {
1483 if ( is_array( $v ) ) {
1484 $array[$k] = add_magic_quotes( $v );
1486 $array[$k] = addslashes( $v );
1493 * HTTP request for URI to retrieve content.
1496 * @uses wp_remote_get()
1498 * @param string $uri URI/URL of web page to retrieve.
1499 * @return bool|string HTTP content. False on failure.
1501 function wp_remote_fopen( $uri ) {
1502 $parsed_url = @parse_url( $uri );
1504 if ( !$parsed_url || !is_array( $parsed_url ) )
1508 $options['timeout'] = 10;
1510 $response = wp_remote_get( $uri, $options );
1512 if ( is_wp_error( $response ) )
1515 return $response['body'];
1519 * Set up the WordPress query.
1523 * @param string $query_vars Default WP_Query arguments.
1525 function wp( $query_vars = '' ) {
1526 global $wp, $wp_query, $wp_the_query;
1527 $wp->main( $query_vars );
1529 if ( !isset($wp_the_query) )
1530 $wp_the_query = $wp_query;
1534 * Retrieve the description for the HTTP status.
1538 * @param int $code HTTP status code.
1539 * @return string Empty string if not found, or description if found.
1541 function get_status_header_desc( $code ) {
1542 global $wp_header_to_desc;
1544 $code = absint( $code );
1546 if ( !isset( $wp_header_to_desc ) ) {
1547 $wp_header_to_desc = array(
1549 101 => 'Switching Protocols',
1550 102 => 'Processing',
1555 203 => 'Non-Authoritative Information',
1556 204 => 'No Content',
1557 205 => 'Reset Content',
1558 206 => 'Partial Content',
1559 207 => 'Multi-Status',
1562 300 => 'Multiple Choices',
1563 301 => 'Moved Permanently',
1566 304 => 'Not Modified',
1569 307 => 'Temporary Redirect',
1571 400 => 'Bad Request',
1572 401 => 'Unauthorized',
1573 402 => 'Payment Required',
1576 405 => 'Method Not Allowed',
1577 406 => 'Not Acceptable',
1578 407 => 'Proxy Authentication Required',
1579 408 => 'Request Timeout',
1582 411 => 'Length Required',
1583 412 => 'Precondition Failed',
1584 413 => 'Request Entity Too Large',
1585 414 => 'Request-URI Too Long',
1586 415 => 'Unsupported Media Type',
1587 416 => 'Requested Range Not Satisfiable',
1588 417 => 'Expectation Failed',
1589 422 => 'Unprocessable Entity',
1591 424 => 'Failed Dependency',
1592 426 => 'Upgrade Required',
1594 500 => 'Internal Server Error',
1595 501 => 'Not Implemented',
1596 502 => 'Bad Gateway',
1597 503 => 'Service Unavailable',
1598 504 => 'Gateway Timeout',
1599 505 => 'HTTP Version Not Supported',
1600 506 => 'Variant Also Negotiates',
1601 507 => 'Insufficient Storage',
1602 510 => 'Not Extended'
1606 if ( isset( $wp_header_to_desc[$code] ) )
1607 return $wp_header_to_desc[$code];
1613 * Set HTTP status header.
1616 * @uses apply_filters() Calls 'status_header' on status header string, HTTP
1617 * HTTP code, HTTP code description, and protocol string as separate
1620 * @param int $header HTTP status code
1623 function status_header( $header ) {
1624 $text = get_status_header_desc( $header );
1626 if ( empty( $text ) )
1629 $protocol = $_SERVER["SERVER_PROTOCOL"];
1630 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
1631 $protocol = 'HTTP/1.0';
1632 $status_header = "$protocol $header $text";
1633 if ( function_exists( 'apply_filters' ) )
1634 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
1636 return @header( $status_header, true, $header );
1640 * Gets the header information to prevent caching.
1642 * The several different headers cover the different ways cache prevention is handled
1643 * by different browsers
1647 * @uses apply_filters()
1648 * @return array The associative array of header names and field values.
1650 function wp_get_nocache_headers() {
1652 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
1653 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
1654 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
1655 'Pragma' => 'no-cache',
1658 if ( function_exists('apply_filters') ) {
1659 $headers = (array) apply_filters('nocache_headers', $headers);
1665 * Sets the headers to prevent caching for the different browsers.
1667 * Different browsers support different nocache headers, so several headers must
1668 * be sent so that all of them get the point that no caching should occur.
1671 * @uses wp_get_nocache_headers()
1673 function nocache_headers() {
1674 $headers = wp_get_nocache_headers();
1675 foreach( $headers as $name => $field_value )
1676 @header("{$name}: {$field_value}");
1680 * Set the headers for caching for 10 days with JavaScript content type.
1684 function cache_javascript_headers() {
1685 $expiresOffset = 864000; // 10 days
1686 header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
1687 header( "Vary: Accept-Encoding" ); // Handle proxies
1688 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
1692 * Retrieve the number of database queries during the WordPress execution.
1696 * @return int Number of database queries
1698 function get_num_queries() {
1700 return $wpdb->num_queries;
1704 * Whether input is yes or no. Must be 'y' to be true.
1708 * @param string $yn Character string containing either 'y' or 'n'
1709 * @return bool True if yes, false on anything else
1711 function bool_from_yn( $yn ) {
1712 return ( strtolower( $yn ) == 'y' );
1716 * Loads the feed template from the use of an action hook.
1718 * If the feed action does not have a hook, then the function will die with a
1719 * message telling the visitor that the feed is not valid.
1721 * It is better to only have one hook for each feed.
1724 * @uses $wp_query Used to tell if the use a comment feed.
1725 * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
1727 function do_feed() {
1730 $feed = get_query_var( 'feed' );
1732 // Remove the pad, if present.
1733 $feed = preg_replace( '/^_+/', '', $feed );
1735 if ( $feed == '' || $feed == 'feed' )
1736 $feed = get_default_feed();
1738 $hook = 'do_feed_' . $feed;
1739 if ( !has_action($hook) ) {
1740 $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
1741 wp_die( $message, '', array( 'response' => 404 ) );
1744 do_action( $hook, $wp_query->is_comment_feed );
1748 * Load the RDF RSS 0.91 Feed template.
1752 function do_feed_rdf() {
1753 load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1757 * Load the RSS 1.0 Feed Template
1761 function do_feed_rss() {
1762 load_template( ABSPATH . WPINC . '/feed-rss.php' );
1766 * Load either the RSS2 comment feed or the RSS2 posts feed.
1770 * @param bool $for_comments True for the comment feed, false for normal feed.
1772 function do_feed_rss2( $for_comments ) {
1773 if ( $for_comments )
1774 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1776 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1780 * Load either Atom comment feed or Atom posts feed.
1784 * @param bool $for_comments True for the comment feed, false for normal feed.
1786 function do_feed_atom( $for_comments ) {
1788 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1790 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1794 * Display the robot.txt file content.
1796 * The echo content should be with usage of the permalinks or for creating the
1800 * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
1802 function do_robots() {
1803 header( 'Content-Type: text/plain; charset=utf-8' );
1805 do_action( 'do_robotstxt' );
1808 $public = get_option( 'blog_public' );
1809 if ( '0' == $public ) {
1810 $output .= "User-agent: *\n";
1811 $output .= "Disallow: /\n";
1813 $output .= "User-agent: *\n";
1814 $output .= "Disallow:\n";
1817 echo apply_filters('robots_txt', $output, $public);
1821 * Test whether blog is already installed.
1823 * The cache will be checked first. If you have a cache plugin, which saves the
1824 * cache values, then this will work. If you use the default WordPress cache,
1825 * and the database goes away, then you might have problems.
1827 * Checks for the option siteurl for whether WordPress is installed.
1832 * @return bool Whether blog is already installed.
1834 function is_blog_installed() {
1837 // Check cache first. If options table goes away and we have true cached, oh well.
1838 if ( wp_cache_get( 'is_blog_installed' ) )
1841 $suppress = $wpdb->suppress_errors();
1842 if ( ! defined( 'WP_INSTALLING' ) ) {
1843 $alloptions = wp_load_alloptions();
1845 // If siteurl is not set to autoload, check it specifically
1846 if ( !isset( $alloptions['siteurl'] ) )
1847 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1849 $installed = $alloptions['siteurl'];
1850 $wpdb->suppress_errors( $suppress );
1852 $installed = !empty( $installed );
1853 wp_cache_set( 'is_blog_installed', $installed );
1858 $suppress = $wpdb->suppress_errors();
1859 $tables = $wpdb->get_col('SHOW TABLES');
1860 $wpdb->suppress_errors( $suppress );
1862 $wp_tables = $wpdb->tables();
1863 // Loop over the WP tables. If none exist, then scratch install is allowed.
1864 // If one or more exist, suggest table repair since we got here because the options
1865 // table could not be accessed.
1866 foreach ( $wp_tables as $table ) {
1867 // If one of the WP tables exist, then we are in an insane state.
1868 if ( in_array( $table, $tables ) ) {
1869 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1870 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1872 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1875 // If visiting repair.php, return true and let it take over.
1876 if ( defined('WP_REPAIRING') )
1878 // Die with a DB error.
1879 $wpdb->error = sprintf( /*WP_I18N_NO_TABLES*/'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.'/*/WP_I18N_NO_TABLES*/, 'maint/repair.php?referrer=is_blog_installed' );
1884 wp_cache_set( 'is_blog_installed', false );
1890 * Retrieve URL with nonce added to URL query.
1892 * @package WordPress
1893 * @subpackage Security
1896 * @param string $actionurl URL to add nonce action
1897 * @param string $action Optional. Nonce action name
1898 * @return string URL with nonce action added.
1900 function wp_nonce_url( $actionurl, $action = -1 ) {
1901 $actionurl = str_replace( '&', '&', $actionurl );
1902 return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1906 * Retrieve or display nonce hidden field for forms.
1908 * The nonce field is used to validate that the contents of the form came from
1909 * the location on the current site and not somewhere else. The nonce does not
1910 * offer absolute protection, but should protect against most cases. It is very
1911 * important to use nonce field in forms.
1913 * If you set $echo to true and set $referer to true, then you will need to
1914 * retrieve the {@link wp_referer_field() wp referer field}. If you have the
1915 * $referer set to true and are echoing the nonce field, it will also echo the
1918 * The $action and $name are optional, but if you want to have better security,
1919 * it is strongly suggested to set those two parameters. It is easier to just
1920 * call the function without any parameters, because validation of the nonce
1921 * doesn't require any parameters, but since crackers know what the default is
1922 * it won't be difficult for them to find a way around your nonce and cause
1925 * The input name will be whatever $name value you gave. The input value will be
1926 * the nonce creation value.
1928 * @package WordPress
1929 * @subpackage Security
1932 * @param string $action Optional. Action name.
1933 * @param string $name Optional. Nonce name.
1934 * @param bool $referer Optional, default true. Whether to set the referer field for validation.
1935 * @param bool $echo Optional, default true. Whether to display or return hidden form field.
1936 * @return string Nonce field.
1938 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1939 $name = esc_attr( $name );
1940 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1945 wp_referer_field( $echo );
1947 return $nonce_field;
1951 * Retrieve or display referer hidden field for forms.
1953 * The referer link is the current Request URI from the server super global. The
1954 * input name is '_wp_http_referer', in case you wanted to check manually.
1956 * @package WordPress
1957 * @subpackage Security
1960 * @param bool $echo Whether to echo or return the referer field.
1961 * @return string Referer field.
1963 function wp_referer_field( $echo = true ) {
1964 $ref = esc_attr( $_SERVER['REQUEST_URI'] );
1965 $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
1968 echo $referer_field;
1969 return $referer_field;
1973 * Retrieve or display original referer hidden field for forms.
1975 * The input name is '_wp_original_http_referer' and will be either the same
1976 * value of {@link wp_referer_field()}, if that was posted already or it will
1977 * be the current page, if it doesn't exist.
1979 * @package WordPress
1980 * @subpackage Security
1983 * @param bool $echo Whether to echo the original http referer
1984 * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
1985 * @return string Original referer field.
1987 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1988 $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
1989 $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
1990 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
1992 echo $orig_referer_field;
1993 return $orig_referer_field;
1997 * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
1999 * @package WordPress
2000 * @subpackage Security
2003 * @return string|bool False on failure. Referer URL on success.
2005 function wp_get_referer() {
2007 if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
2008 $ref = $_REQUEST['_wp_http_referer'];
2009 else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
2010 $ref = $_SERVER['HTTP_REFERER'];
2012 if ( $ref !== $_SERVER['REQUEST_URI'] )
2018 * Retrieve original referer that was posted, if it exists.
2020 * @package WordPress
2021 * @subpackage Security
2024 * @return string|bool False if no original referer or original referer if set.
2026 function wp_get_original_referer() {
2027 if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
2028 return $_REQUEST['_wp_original_http_referer'];
2033 * Recursive directory creation based on full path.
2035 * Will attempt to set permissions on folders.
2039 * @param string $target Full path to attempt to create.
2040 * @return bool Whether the path was created. True if path already exists.
2042 function wp_mkdir_p( $target ) {
2043 // from php.net/mkdir user contributed notes
2044 $target = str_replace( '//', '/', $target );
2046 // safe mode fails with a trailing slash under certain PHP versions.
2047 $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
2048 if ( empty($target) )
2051 if ( file_exists( $target ) )
2052 return @is_dir( $target );
2054 // Attempting to create the directory may clutter up our display.
2055 if ( @mkdir( $target ) ) {
2056 $stat = @stat( dirname( $target ) );
2057 $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
2058 @chmod( $target, $dir_perms );
2060 } elseif ( is_dir( dirname( $target ) ) ) {
2064 // If the above failed, attempt to create the parent node, then try again.
2065 if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
2066 return wp_mkdir_p( $target );
2072 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
2076 * @param string $path File path
2077 * @return bool True if path is absolute, false is not absolute.
2079 function path_is_absolute( $path ) {
2080 // this is definitive if true but fails if $path does not exist or contains a symbolic link
2081 if ( realpath($path) == $path )
2084 if ( strlen($path) == 0 || $path[0] == '.' )
2087 // windows allows absolute paths like this
2088 if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
2091 // a path starting with / or \ is absolute; anything else is relative
2092 return (bool) preg_match('#^[/\\\\]#', $path);
2096 * Join two filesystem paths together (e.g. 'give me $path relative to $base').
2098 * If the $path is absolute, then it the full path is returned.
2102 * @param string $base
2103 * @param string $path
2104 * @return string The path with the base or absolute path.
2106 function path_join( $base, $path ) {
2107 if ( path_is_absolute($path) )
2110 return rtrim($base, '/') . '/' . ltrim($path, '/');
2114 * Get an array containing the current upload directory's path and url.
2116 * Checks the 'upload_path' option, which should be from the web root folder,
2117 * and if it isn't empty it will be used. If it is empty, then the path will be
2118 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
2119 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
2121 * The upload URL path is set either by the 'upload_url_path' option or by using
2122 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
2124 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
2125 * the administration settings panel), then the time will be used. The format
2126 * will be year first and then month.
2128 * If the path couldn't be created, then an error will be returned with the key
2129 * 'error' containing the error message. The error suggests that the parent
2130 * directory is not writable by the server.
2132 * On success, the returned array will have many indices:
2133 * 'path' - base directory and sub directory or full path to upload directory.
2134 * 'url' - base url and sub directory or absolute URL to upload directory.
2135 * 'subdir' - sub directory if uploads use year/month folders option is on.
2136 * 'basedir' - path without subdir.
2137 * 'baseurl' - URL path without subdir.
2138 * 'error' - set to false.
2141 * @uses apply_filters() Calls 'upload_dir' on returned array.
2143 * @param string $time Optional. Time formatted in 'yyyy/mm'.
2144 * @return array See above for description.
2146 function wp_upload_dir( $time = null ) {
2148 $siteurl = get_option( 'siteurl' );
2149 $upload_path = get_option( 'upload_path' );
2150 $upload_path = trim($upload_path);
2151 $main_override = is_multisite() && defined( 'MULTISITE' ) && is_main_site();
2152 if ( empty($upload_path) ) {
2153 $dir = WP_CONTENT_DIR . '/uploads';
2155 $dir = $upload_path;
2156 if ( 'wp-content/uploads' == $upload_path ) {
2157 $dir = WP_CONTENT_DIR . '/uploads';
2158 } elseif ( 0 !== strpos($dir, ABSPATH) ) {
2159 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
2160 $dir = path_join( ABSPATH, $dir );
2164 if ( !$url = get_option( 'upload_url_path' ) ) {
2165 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
2166 $url = WP_CONTENT_URL . '/uploads';
2168 $url = trailingslashit( $siteurl ) . $upload_path;
2171 if ( defined('UPLOADS') && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
2172 $dir = ABSPATH . UPLOADS;
2173 $url = trailingslashit( $siteurl ) . UPLOADS;
2176 if ( is_multisite() && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
2177 if ( defined( 'BLOGUPLOADDIR' ) )
2178 $dir = untrailingslashit(BLOGUPLOADDIR);
2179 $url = str_replace( UPLOADS, 'files', $url );
2186 if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
2187 // Generate the yearly and monthly dirs
2189 $time = current_time( 'mysql' );
2190 $y = substr( $time, 0, 4 );
2191 $m = substr( $time, 5, 2 );
2198 $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
2200 // Make sure we have an uploads dir
2201 if ( ! wp_mkdir_p( $uploads['path'] ) ) {
2202 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
2203 return array( 'error' => $message );
2210 * Get a filename that is sanitized and unique for the given directory.
2212 * If the filename is not unique, then a number will be added to the filename
2213 * before the extension, and will continue adding numbers until the filename is
2216 * The callback is passed three parameters, the first one is the directory, the
2217 * second is the filename, and the third is the extension.
2221 * @param string $dir
2222 * @param string $filename
2223 * @param mixed $unique_filename_callback Callback.
2224 * @return string New filename, if given wasn't unique.
2226 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
2227 // sanitize the file name before we begin processing
2228 $filename = sanitize_file_name($filename);
2230 // separate the filename into a name and extension
2231 $info = pathinfo($filename);
2232 $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
2233 $name = basename($filename, $ext);
2235 // edge case: if file is named '.ext', treat as an empty name
2236 if ( $name === $ext )
2239 // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
2240 if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
2241 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
2245 // change '.ext' to lower case
2246 if ( $ext && strtolower($ext) != $ext ) {
2247 $ext2 = strtolower($ext);
2248 $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
2250 // check for both lower and upper case extension or image sub-sizes may be overwritten
2251 while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
2252 $new_number = $number + 1;
2253 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
2254 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
2255 $number = $new_number;
2260 while ( file_exists( $dir . "/$filename" ) ) {
2261 if ( '' == "$number$ext" )
2262 $filename = $filename . ++$number . $ext;
2264 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
2272 * Create a file in the upload folder with given content.
2274 * If there is an error, then the key 'error' will exist with the error message.
2275 * If success, then the key 'file' will have the unique file path, the 'url' key
2276 * will have the link to the new file. and the 'error' key will be set to false.
2278 * This function will not move an uploaded file to the upload folder. It will
2279 * create a new file with the content in $bits parameter. If you move the upload
2280 * file, read the content of the uploaded file, and then you can give the
2281 * filename and content to this function, which will add it to the upload
2284 * The permissions will be set on the new file automatically by this function.
2288 * @param string $name
2289 * @param null $deprecated Never used. Set to null.
2290 * @param mixed $bits File content
2291 * @param string $time Optional. Time formatted in 'yyyy/mm'.
2294 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
2295 if ( !empty( $deprecated ) )
2296 _deprecated_argument( __FUNCTION__, '2.0' );
2298 if ( empty( $name ) )
2299 return array( 'error' => __( 'Empty filename' ) );
2301 $wp_filetype = wp_check_filetype( $name );
2302 if ( !$wp_filetype['ext'] )
2303 return array( 'error' => __( 'Invalid file type' ) );
2305 $upload = wp_upload_dir( $time );
2307 if ( $upload['error'] !== false )
2310 $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
2311 if ( !is_array( $upload_bits_error ) ) {
2312 $upload[ 'error' ] = $upload_bits_error;
2316 $filename = wp_unique_filename( $upload['path'], $name );
2318 $new_file = $upload['path'] . "/$filename";
2319 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
2320 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
2321 return array( 'error' => $message );
2324 $ifp = @ fopen( $new_file, 'wb' );
2326 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
2328 @fwrite( $ifp, $bits );
2332 // Set correct file permissions
2333 $stat = @ stat( dirname( $new_file ) );
2334 $perms = $stat['mode'] & 0007777;
2335 $perms = $perms & 0000666;
2336 @ chmod( $new_file, $perms );
2340 $url = $upload['url'] . "/$filename";
2342 return array( 'file' => $new_file, 'url' => $url, 'error' => false );
2346 * Retrieve the file type based on the extension name.
2348 * @package WordPress
2350 * @uses apply_filters() Calls 'ext2type' hook on default supported types.
2352 * @param string $ext The extension to search.
2353 * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
2355 function wp_ext2type( $ext ) {
2356 $ext2type = apply_filters( 'ext2type', array(
2357 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
2358 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
2359 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
2360 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsb', 'xlsm' ),
2361 'interactive' => array( 'key', 'ppt', 'pptx', 'pptm', 'odp', 'swf' ),
2362 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
2363 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip' ),
2364 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
2366 foreach ( $ext2type as $type => $exts )
2367 if ( in_array( $ext, $exts ) )
2372 * Retrieve the file type from the file name.
2374 * You can optionally define the mime array, if needed.
2378 * @param string $filename File name or path.
2379 * @param array $mimes Optional. Key is the file extension with value as the mime type.
2380 * @return array Values with extension first and mime type.
2382 function wp_check_filetype( $filename, $mimes = null ) {
2383 if ( empty($mimes) )
2384 $mimes = get_allowed_mime_types();
2388 foreach ( $mimes as $ext_preg => $mime_match ) {
2389 $ext_preg = '!\.(' . $ext_preg . ')$!i';
2390 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
2391 $type = $mime_match;
2392 $ext = $ext_matches[1];
2397 return compact( 'ext', 'type' );
2401 * Attempt to determine the real file type of a file.
2402 * If unable to, the file name extension will be used to determine type.
2404 * If it's determined that the extension does not match the file's real type,
2405 * then the "proper_filename" value will be set with a proper filename and extension.
2407 * Currently this function only supports validating images known to getimagesize().
2411 * @param string $file Full path to the image.
2412 * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
2413 * @param array $mimes Optional. Key is the file extension with value as the mime type.
2414 * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
2416 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
2418 $proper_filename = false;
2420 // Do basic extension validation and MIME mapping
2421 $wp_filetype = wp_check_filetype( $filename, $mimes );
2422 extract( $wp_filetype );
2424 // We can't do any further validation without a file to work with
2425 if ( ! file_exists( $file ) )
2426 return compact( 'ext', 'type', 'proper_filename' );
2428 // We're able to validate images using GD
2429 if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
2431 // Attempt to figure out what type of image it actually is
2432 $imgstats = @getimagesize( $file );
2434 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
2435 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
2436 // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
2437 // You shouldn't need to use this filter, but it's here just in case
2438 $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
2439 'image/jpeg' => 'jpg',
2440 'image/png' => 'png',
2441 'image/gif' => 'gif',
2442 'image/bmp' => 'bmp',
2443 'image/tiff' => 'tif',
2446 // Replace whatever is after the last period in the filename with the correct extension
2447 if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
2448 $filename_parts = explode( '.', $filename );
2449 array_pop( $filename_parts );
2450 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
2451 $new_filename = implode( '.', $filename_parts );
2453 if ( $new_filename != $filename )
2454 $proper_filename = $new_filename; // Mark that it changed
2456 // Redefine the extension / MIME
2457 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
2458 extract( $wp_filetype );
2463 // Let plugins try and validate other types of files
2464 // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
2465 return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
2469 * Retrieve list of allowed mime types and file extensions.
2473 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
2475 function get_allowed_mime_types() {
2476 static $mimes = false;
2479 // Accepted MIME types are set here as PCRE unless provided.
2480 $mimes = apply_filters( 'upload_mimes', array(
2481 'jpg|jpeg|jpe' => 'image/jpeg',
2482 'gif' => 'image/gif',
2483 'png' => 'image/png',
2484 'bmp' => 'image/bmp',
2485 'tif|tiff' => 'image/tiff',
2486 'ico' => 'image/x-icon',
2487 'asf|asx|wax|wmv|wmx' => 'video/asf',
2488 'avi' => 'video/avi',
2489 'divx' => 'video/divx',
2490 'flv' => 'video/x-flv',
2491 'mov|qt' => 'video/quicktime',
2492 'mpeg|mpg|mpe' => 'video/mpeg',
2493 'txt|asc|c|cc|h' => 'text/plain',
2494 'csv' => 'text/csv',
2495 'tsv' => 'text/tab-separated-values',
2496 'rtx' => 'text/richtext',
2497 'css' => 'text/css',
2498 'htm|html' => 'text/html',
2499 'mp3|m4a|m4b' => 'audio/mpeg',
2500 'mp4|m4v' => 'video/mp4',
2501 'ra|ram' => 'audio/x-realaudio',
2502 'wav' => 'audio/wav',
2503 'ogg|oga' => 'audio/ogg',
2504 'ogv' => 'video/ogg',
2505 'mid|midi' => 'audio/midi',
2506 'wma' => 'audio/wma',
2507 'mka' => 'audio/x-matroska',
2508 'mkv' => 'video/x-matroska',
2509 'rtf' => 'application/rtf',
2510 'js' => 'application/javascript',
2511 'pdf' => 'application/pdf',
2512 'doc|docx' => 'application/msword',
2513 'pot|pps|ppt|pptx|ppam|pptm|sldm|ppsm|potm' => 'application/vnd.ms-powerpoint',
2514 'wri' => 'application/vnd.ms-write',
2515 'xla|xls|xlsx|xlt|xlw|xlam|xlsb|xlsm|xltm' => 'application/vnd.ms-excel',
2516 'mdb' => 'application/vnd.ms-access',
2517 'mpp' => 'application/vnd.ms-project',
2518 'docm|dotm' => 'application/vnd.ms-word',
2519 'pptx|sldx|ppsx|potx' => 'application/vnd.openxmlformats-officedocument.presentationml',
2520 'xlsx|xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml',
2521 'docx|dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml',
2522 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
2523 'swf' => 'application/x-shockwave-flash',
2524 'class' => 'application/java',
2525 'tar' => 'application/x-tar',
2526 'zip' => 'application/zip',
2527 'gz|gzip' => 'application/x-gzip',
2528 'exe' => 'application/x-msdownload',
2529 // openoffice formats
2530 'odt' => 'application/vnd.oasis.opendocument.text',
2531 'odp' => 'application/vnd.oasis.opendocument.presentation',
2532 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
2533 'odg' => 'application/vnd.oasis.opendocument.graphics',
2534 'odc' => 'application/vnd.oasis.opendocument.chart',
2535 'odb' => 'application/vnd.oasis.opendocument.database',
2536 'odf' => 'application/vnd.oasis.opendocument.formula',
2537 // wordperfect formats
2538 'wp|wpd' => 'application/wordperfect',
2546 * Retrieve nonce action "Are you sure" message.
2548 * The action is split by verb and noun. The action format is as follows:
2549 * verb-action_extra. The verb is before the first dash and has the format of
2550 * letters and no spaces and numbers. The noun is after the dash and before the
2551 * underscore, if an underscore exists. The noun is also only letters.
2553 * The filter will be called for any action, which is not defined by WordPress.
2554 * You may use the filter for your plugin to explain nonce actions to the user,
2555 * when they get the "Are you sure?" message. The filter is in the format of
2556 * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
2557 * $noun replaced by the found noun. The two parameters that are given to the
2558 * hook are the localized "Are you sure you want to do this?" message with the
2559 * extra text (the text after the underscore).
2561 * @package WordPress
2562 * @subpackage Security
2565 * @param string $action Nonce action.
2566 * @return string Are you sure message.
2568 function wp_explain_nonce( $action ) {
2569 if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
2570 $verb = $matches[1];
2571 $noun = $matches[2];
2574 $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: “%s” has failed.' ), 'get_the_title' );
2576 $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false );
2577 $trans['delete']['category'] = array( __( 'Your attempt to delete this category: “%s” has failed.' ), 'get_cat_name' );
2578 $trans['update']['category'] = array( __( 'Your attempt to edit this category: “%s” has failed.' ), 'get_cat_name' );
2580 $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: “%s” has failed.' ), 'use_id' );
2581 $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: “%s” has failed.' ), 'use_id' );
2582 $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: “%s” has failed.' ), 'use_id' );
2583 $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: “%s” has failed.' ), 'use_id' );
2584 $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
2585 $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
2587 $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false );
2588 $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: “%s” has failed.' ), 'use_id' );
2589 $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: “%s” has failed.' ), 'use_id' );
2590 $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false );
2592 $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false );
2593 $trans['delete']['page'] = array( __( 'Your attempt to delete this page: “%s” has failed.' ), 'get_the_title' );
2594 $trans['update']['page'] = array( __( 'Your attempt to edit this page: “%s” has failed.' ), 'get_the_title' );
2596 $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: “%s” has failed.' ), 'use_id' );
2597 $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: “%s” has failed.' ), 'use_id' );
2598 $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: “%s” has failed.' ), 'use_id' );
2599 $trans['upgrade']['plugin'] = array( __( 'Your attempt to update this plugin: “%s” has failed.' ), 'use_id' );
2601 $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false );
2602 $trans['delete']['post'] = array( __( 'Your attempt to delete this post: “%s” has failed.' ), 'get_the_title' );
2603 $trans['update']['post'] = array( __( 'Your attempt to edit this post: “%s” has failed.' ), 'get_the_title' );
2605 $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false );
2606 $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false );
2607 $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false );
2608 $trans['update']['user'] = array( __( 'Your attempt to edit this user: “%s” has failed.' ), 'get_the_author_meta', 'display_name' );
2609 $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: “%s” has failed.' ), 'get_the_author_meta', 'display_name' );
2611 $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false );
2612 $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
2613 $trans['edit']['file'] = array( __( 'Your attempt to edit this file: “%s” has failed.' ), 'use_id' );
2614 $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: “%s” has failed.' ), 'use_id' );
2615 $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: “%s” has failed.' ), 'use_id' );
2617 $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
2619 if ( isset( $trans[$verb][$noun] ) ) {
2620 if ( !empty( $trans[$verb][$noun][1] ) ) {
2621 $lookup = $trans[$verb][$noun][1];
2622 if ( isset($trans[$verb][$noun][2]) )
2623 $lookup_value = $trans[$verb][$noun][2];
2624 $object = $matches[4];
2625 if ( 'use_id' != $lookup ) {
2626 if ( isset( $lookup_value ) )
2627 $object = call_user_func( $lookup, $lookup_value, $object );
2629 $object = call_user_func( $lookup, $object );
2631 return sprintf( $trans[$verb][$noun][0], esc_html($object) );
2633 return $trans[$verb][$noun][0];
2637 return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), isset($matches[4]) ? $matches[4] : '' );
2639 return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
2644 * Display "Are You Sure" message to confirm the action being taken.
2646 * If the action has the nonce explain message, then it will be displayed along
2647 * with the "Are you sure?" message.
2649 * @package WordPress
2650 * @subpackage Security
2653 * @param string $action The nonce action.
2655 function wp_nonce_ays( $action ) {
2656 $title = __( 'WordPress Failure Notice' );
2657 $html = esc_html( wp_explain_nonce( $action ) );
2658 if ( 'log-out' == $action )
2659 $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
2660 elseif ( wp_get_referer() )
2661 $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
2663 wp_die( $html, $title, array('response' => 403) );
2668 * Kill WordPress execution and display HTML message with error message.
2670 * This function complements the die() PHP function. The difference is that
2671 * HTML will be displayed to the user. It is recommended to use this function
2672 * only, when the execution should not continue any further. It is not
2673 * recommended to call this function very often and try to handle as many errors
2674 * as possible siliently.
2678 * @param string $message Error message.
2679 * @param string $title Error title.
2680 * @param string|array $args Optional arguements to control behaviour.
2682 function wp_die( $message, $title = '', $args = array() ) {
2683 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2686 if ( function_exists( 'apply_filters' ) ) {
2687 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
2689 $function = '_default_wp_die_handler';
2692 call_user_func( $function, $message, $title, $args );
2696 * Kill WordPress execution and display HTML message with error message.
2698 * This is the default handler for wp_die if you want a custom one for your
2699 * site then you can overload using the wp_die_handler filter in wp_die
2704 * @param string $message Error message.
2705 * @param string $title Error title.
2706 * @param string|array $args Optional arguements to control behaviour.
2708 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
2709 $defaults = array( 'response' => 500 );
2710 $r = wp_parse_args($args, $defaults);
2712 $have_gettext = function_exists('__');
2714 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
2715 if ( empty( $title ) ) {
2716 $error_data = $message->get_error_data();
2717 if ( is_array( $error_data ) && isset( $error_data['title'] ) )
2718 $title = $error_data['title'];
2720 $errors = $message->get_error_messages();
2721 switch ( count( $errors ) ) :
2726 $message = "<p>{$errors[0]}</p>";
2729 $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
2732 } elseif ( is_string( $message ) ) {
2733 $message = "<p>$message</p>";
2736 if ( isset( $r['back_link'] ) && $r['back_link'] ) {
2737 $back_text = $have_gettext? __('« Back') : '« Back';
2738 $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>";
2741 if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
2742 $admin_dir = WP_SITEURL . '/wp-admin/';
2743 elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
2744 $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
2745 elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
2748 $admin_dir = 'wp-admin/';
2750 if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
2751 if ( !headers_sent() ) {
2752 status_header( $r['response'] );
2754 header( 'Content-Type: text/html; charset=utf-8' );
2757 if ( empty($title) )
2758 $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error';
2760 $text_direction = 'ltr';
2761 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
2762 $text_direction = 'rtl';
2763 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
2764 $text_direction = 'rtl';
2766 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2767 <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono -->
2768 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) language_attributes(); else echo "dir='$text_direction'"; ?>>
2770 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2771 <title><?php echo $title ?></title>
2772 <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
2774 if ( 'rtl' == $text_direction ) : ?>
2775 <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
2778 <body id="error-page">
2780 <?php echo $message; ?>
2788 * Retrieve the WordPress home page URL.
2790 * If the constant named 'WP_HOME' exists, then it willl be used and returned by
2791 * the function. This can be used to counter the redirection on your local
2792 * development environment.
2795 * @package WordPress
2798 * @param string $url URL for the home location
2799 * @return string Homepage location.
2801 function _config_wp_home( $url = '' ) {
2802 if ( defined( 'WP_HOME' ) )
2808 * Retrieve the WordPress site URL.
2810 * If the constant named 'WP_SITEURL' is defined, then the value in that
2811 * constant will always be returned. This can be used for debugging a site on
2812 * your localhost while not having to change the database to your URL.
2815 * @package WordPress
2818 * @param string $url URL to set the WordPress site location.
2819 * @return string The WordPress Site URL
2821 function _config_wp_siteurl( $url = '' ) {
2822 if ( defined( 'WP_SITEURL' ) )
2828 * Set the localized direction for MCE plugin.
2830 * Will only set the direction to 'rtl', if the WordPress locale has the text
2831 * direction set to 'rtl'.
2833 * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
2834 * keys. These keys are then returned in the $input array.
2837 * @package WordPress
2841 * @param array $input MCE plugin array.
2842 * @return array Direction set for 'rtl', if needed by locale.
2844 function _mce_set_direction( $input ) {
2846 $input['directionality'] = 'rtl';
2847 $input['plugins'] .= ',directionality';
2848 $input['theme_advanced_buttons1'] .= ',ltr';
2856 * Convert smiley code to the icon graphic file equivalent.
2858 * You can turn off smilies, by going to the write setting screen and unchecking
2859 * the box, or by setting 'use_smilies' option to false or removing the option.
2861 * Plugins may override the default smiley list by setting the $wpsmiliestrans
2862 * to an array, with the key the code the blogger types in and the value the
2865 * The $wp_smiliessearch global is for the regular expression and is set each
2866 * time the function is called.
2868 * The full list of smilies can be found in the function and won't be listed in
2869 * the description. Probably should create a Codex page for it, so that it is
2872 * @global array $wpsmiliestrans
2873 * @global array $wp_smiliessearch
2876 function smilies_init() {
2877 global $wpsmiliestrans, $wp_smiliessearch;
2879 // don't bother setting up smilies if they are disabled
2880 if ( !get_option( 'use_smilies' ) )
2883 if ( !isset( $wpsmiliestrans ) ) {
2884 $wpsmiliestrans = array(
2885 ':mrgreen:' => 'icon_mrgreen.gif',
2886 ':neutral:' => 'icon_neutral.gif',
2887 ':twisted:' => 'icon_twisted.gif',
2888 ':arrow:' => 'icon_arrow.gif',
2889 ':shock:' => 'icon_eek.gif',
2890 ':smile:' => 'icon_smile.gif',
2891 ':???:' => 'icon_confused.gif',
2892 ':cool:' => 'icon_cool.gif',
2893 ':evil:' => 'icon_evil.gif',
2894 ':grin:' => 'icon_biggrin.gif',
2895 ':idea:' => 'icon_idea.gif',
2896 ':oops:' => 'icon_redface.gif',
2897 ':razz:' => 'icon_razz.gif',
2898 ':roll:' => 'icon_rolleyes.gif',
2899 ':wink:' => 'icon_wink.gif',
2900 ':cry:' => 'icon_cry.gif',
2901 ':eek:' => 'icon_surprised.gif',
2902 ':lol:' => 'icon_lol.gif',
2903 ':mad:' => 'icon_mad.gif',
2904 ':sad:' => 'icon_sad.gif',
2905 '8-)' => 'icon_cool.gif',
2906 '8-O' => 'icon_eek.gif',
2907 ':-(' => 'icon_sad.gif',
2908 ':-)' => 'icon_smile.gif',
2909 ':-?' => 'icon_confused.gif',
2910 ':-D' => 'icon_biggrin.gif',
2911 ':-P' => 'icon_razz.gif',
2912 ':-o' => 'icon_surprised.gif',
2913 ':-x' => 'icon_mad.gif',
2914 ':-|' => 'icon_neutral.gif',
2915 ';-)' => 'icon_wink.gif',
2916 '8)' => 'icon_cool.gif',
2917 '8O' => 'icon_eek.gif',
2918 ':(' => 'icon_sad.gif',
2919 ':)' => 'icon_smile.gif',
2920 ':?' => 'icon_confused.gif',
2921 ':D' => 'icon_biggrin.gif',
2922 ':P' => 'icon_razz.gif',
2923 ':o' => 'icon_surprised.gif',
2924 ':x' => 'icon_mad.gif',
2925 ':|' => 'icon_neutral.gif',
2926 ';)' => 'icon_wink.gif',
2927 ':!:' => 'icon_exclaim.gif',
2928 ':?:' => 'icon_question.gif',
2932 if (count($wpsmiliestrans) == 0) {
2937 * NOTE: we sort the smilies in reverse key order. This is to make sure
2938 * we match the longest possible smilie (:???: vs :?) as the regular
2939 * expression used below is first-match
2941 krsort($wpsmiliestrans);
2943 $wp_smiliessearch = '/(?:\s|^)';
2946 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
2947 $firstchar = substr($smiley, 0, 1);
2948 $rest = substr($smiley, 1);
2951 if ($firstchar != $subchar) {
2952 if ($subchar != '') {
2953 $wp_smiliessearch .= ')|(?:\s|^)';
2955 $subchar = $firstchar;
2956 $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
2958 $wp_smiliessearch .= '|';
2960 $wp_smiliessearch .= preg_quote($rest, '/');
2963 $wp_smiliessearch .= ')(?:\s|$)/m';
2967 * Merge user defined arguments into defaults array.
2969 * This function is used throughout WordPress to allow for both string or array
2970 * to be merged into another array.
2974 * @param string|array $args Value to merge with $defaults
2975 * @param array $defaults Array that serves as the defaults.
2976 * @return array Merged user defined values with defaults.
2978 function wp_parse_args( $args, $defaults = '' ) {
2979 if ( is_object( $args ) )
2980 $r = get_object_vars( $args );
2981 elseif ( is_array( $args ) )
2984 wp_parse_str( $args, $r );
2986 if ( is_array( $defaults ) )
2987 return array_merge( $defaults, $r );
2992 * Clean up an array, comma- or space-separated list of IDs
2996 * @param array|string $list
2997 * @return array Sanitized array of IDs
2999 function wp_parse_id_list( $list ) {
3000 if ( !is_array($list) )
3001 $list = preg_split('/[\s,]+/', $list);
3003 return array_unique(array_map('absint', $list));
3007 * Extract a slice of an array, given a list of keys
3011 * @param array $array The original array
3012 * @param array $keys The list of keys
3013 * @return array The array slice
3015 function wp_array_slice_assoc( $array, $keys ) {
3017 foreach ( $keys as $key )
3018 if ( isset( $array[ $key ] ) )
3019 $slice[ $key ] = $array[ $key ];
3025 * Filters a list of objects, based on a set of key => value arguments
3029 * @param array $list An array of objects to filter
3030 * @param array $args An array of key => value arguments to match against each object
3031 * @param string $operator The logical operation to perform. 'or' means only one element
3032 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
3033 * @param bool|string $field A field from the object to place instead of the entire object
3034 * @return array A list of objects or object fields
3036 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
3037 if ( ! is_array( $list ) )
3040 $list = wp_list_filter( $list, $args, $operator );
3043 $list = wp_list_pluck( $list, $field );
3049 * Filters a list of objects, based on a set of key => value arguments
3053 * @param array $list An array of objects to filter
3054 * @param array $args An array of key => value arguments to match against each object
3055 * @param string $operator The logical operation to perform:
3056 * 'AND' means all elements from the array must match;
3057 * 'OR' means only one element needs to match;
3058 * 'NOT' means no elements may match.
3059 * The default is 'AND'.
3062 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
3063 if ( ! is_array( $list ) )
3066 if ( empty( $args ) )
3069 $operator = strtoupper( $operator );
3070 $count = count( $args );
3071 $filtered = array();
3073 foreach ( $list as $key => $obj ) {
3074 $matched = count( array_intersect_assoc( (array) $obj, $args ) );
3075 if ( ( 'AND' == $operator && $matched == $count )
3076 || ( 'OR' == $operator && $matched <= $count )
3077 || ( 'NOT' == $operator && 0 == $matched ) ) {
3078 $filtered[$key] = $obj;
3086 * Pluck a certain field out of each object in a list
3090 * @param array $list A list of objects or arrays
3091 * @param int|string $field A field from the object to place instead of the entire object
3094 function wp_list_pluck( $list, $field ) {
3095 foreach ( $list as $key => $value ) {
3096 $value = (array) $value;
3097 $list[ $key ] = $value[ $field ];
3104 * Determines if default embed handlers should be loaded.
3106 * Checks to make sure that the embeds library hasn't already been loaded. If
3107 * it hasn't, then it will load the embeds library.
3111 function wp_maybe_load_embeds() {
3112 if ( ! apply_filters('load_default_embeds', true) )
3114 require_once( ABSPATH . WPINC . '/default-embeds.php' );
3118 * Determines if Widgets library should be loaded.
3120 * Checks to make sure that the widgets library hasn't already been loaded. If
3121 * it hasn't, then it will load the widgets library and run an action hook.
3124 * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
3126 function wp_maybe_load_widgets() {
3127 if ( ! apply_filters('load_default_widgets', true) )
3129 require_once( ABSPATH . WPINC . '/default-widgets.php' );
3130 add_action( '_admin_menu', 'wp_widgets_add_menu' );
3134 * Append the Widgets menu to the themes main menu.
3137 * @uses $submenu The administration submenu list.
3139 function wp_widgets_add_menu() {
3141 $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
3142 ksort( $submenu['themes.php'], SORT_NUMERIC );
3146 * Flush all output buffers for PHP 5.2.
3148 * Make sure all output buffers are flushed before our singletons our destroyed.
3152 function wp_ob_end_flush_all() {
3153 $levels = ob_get_level();
3154 for ($i=0; $i<$levels; $i++)
3159 * Load custom DB error or display WordPress DB error.
3161 * If a file exists in the wp-content directory named db-error.php, then it will
3162 * be loaded instead of displaying the WordPress DB error. If it is not found,
3163 * then the WordPress DB error will be displayed instead.
3165 * The WordPress DB error sets the HTTP status header to 500 to try to prevent
3166 * search engines from caching the message. Custom DB messages should do the
3169 * This function was backported to the the WordPress 2.3.2, but originally was
3170 * added in WordPress 2.5.0.
3175 function dead_db() {
3178 // Load custom DB error template, if present.
3179 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
3180 require_once( WP_CONTENT_DIR . '/db-error.php' );
3184 // If installing or in the admin, provide the verbose message.
3185 if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
3186 wp_die($wpdb->error);
3188 // Otherwise, be terse.
3189 status_header( 500 );
3191 header( 'Content-Type: text/html; charset=utf-8' );
3193 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3194 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
3196 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3197 <title>Database Error</title>
3201 <h1>Error establishing a database connection</h1>
3209 * Converts value to nonnegative integer.
3213 * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
3214 * @return int An nonnegative integer
3216 function absint( $maybeint ) {
3217 return abs( intval( $maybeint ) );
3221 * Determines if the blog can be accessed over SSL.
3223 * Determines if blog can be accessed over SSL by using cURL to access the site
3224 * using the https in the siteurl. Requires cURL extension to work correctly.
3228 * @param string $url
3229 * @return bool Whether SSL access is available
3231 function url_is_accessable_via_ssl($url)
3233 if (in_array('curl', get_loaded_extensions())) {
3234 $ssl = preg_replace( '/^http:\/\//', 'https://', $url );
3237 curl_setopt($ch, CURLOPT_URL, $ssl);
3238 curl_setopt($ch, CURLOPT_FAILONERROR, true);
3239 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3240 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
3241 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
3245 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
3248 if ($status == 200 || $status == 401) {
3256 * Secure URL, if available or the given URL.
3260 * @param string $url Complete URL path with transport.
3261 * @return string Secure or regular URL path.
3263 function atom_service_url_filter($url)
3265 if ( url_is_accessable_via_ssl($url) )
3266 return preg_replace( '/^http:\/\//', 'https://', $url );
3272 * Marks a function as deprecated and informs when it has been used.
3274 * There is a hook deprecated_function_run that will be called that can be used
3275 * to get the backtrace up to what file and function called the deprecated
3278 * The current behavior is to trigger a user error if WP_DEBUG is true.
3280 * This function is to be used in every function that is deprecated.
3282 * @package WordPress
3287 * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
3288 * and the version the function was deprecated in.
3289 * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
3290 * trigger or false to not trigger error.
3292 * @param string $function The function that was called
3293 * @param string $version The version of WordPress that deprecated the function
3294 * @param string $replacement Optional. The function that should have been called
3296 function _deprecated_function( $function, $version, $replacement=null ) {
3298 do_action( 'deprecated_function_run', $function, $replacement, $version );
3300 // Allow plugin to filter the output error trigger
3301 if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
3302 if ( ! is_null($replacement) )
3303 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
3305 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
3310 * Marks a file as deprecated and informs when it has been used.
3312 * There is a hook deprecated_file_included that will be called that can be used
3313 * to get the backtrace up to what file and function included the deprecated
3316 * The current behavior is to trigger a user error if WP_DEBUG is true.
3318 * This function is to be used in every file that is deprecated.
3320 * @package WordPress
3325 * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
3326 * the version in which the file was deprecated, and any message regarding the change.
3327 * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
3328 * trigger or false to not trigger error.
3330 * @param string $file The file that was included
3331 * @param string $version The version of WordPress that deprecated the file
3332 * @param string $replacement Optional. The file that should have been included based on ABSPATH
3333 * @param string $message Optional. A message regarding the change
3335 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
3337 do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
3339 // Allow plugin to filter the output error trigger
3340 if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
3341 $message = empty( $message ) ? '' : ' ' . $message;
3342 if ( ! is_null( $replacement ) )
3343 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
3345 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
3349 * Marks a function argument as deprecated and informs when it has been used.
3351 * This function is to be used whenever a deprecated function argument is used.
3352 * Before this function is called, the argument must be checked for whether it was
3353 * used by comparing it to its default value or evaluating whether it is empty.
3356 * if ( !empty($deprecated) )
3357 * _deprecated_argument( __FUNCTION__, '3.0' );
3360 * There is a hook deprecated_argument_run that will be called that can be used
3361 * to get the backtrace up to what file and function used the deprecated
3364 * The current behavior is to trigger a user error if WP_DEBUG is true.
3366 * @package WordPress
3371 * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
3372 * and the version in which the argument was deprecated.
3373 * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
3374 * trigger or false to not trigger error.
3376 * @param string $function The function that was called
3377 * @param string $version The version of WordPress that deprecated the argument used
3378 * @param string $message Optional. A message regarding the change.
3380 function _deprecated_argument( $function, $version, $message = null ) {
3382 do_action( 'deprecated_argument_run', $function, $message, $version );
3384 // Allow plugin to filter the output error trigger
3385 if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
3386 if ( ! is_null( $message ) )
3387 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
3389 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
3394 * Marks something as being incorrectly called.
3396 * There is a hook doing_it_wrong_run that will be called that can be used
3397 * to get the backtrace up to what file and function called the deprecated
3400 * The current behavior is to trigger a user error if WP_DEBUG is true.
3402 * @package WordPress
3407 * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
3408 * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
3409 * trigger or false to not trigger error.
3411 * @param string $function The function that was called.
3412 * @param string $message A message explaining what has been done incorrectly.
3413 * @param string $version The version of WordPress where the message was added.
3415 function _doing_it_wrong( $function, $message, $version ) {
3417 do_action( 'doing_it_wrong_run', $function, $message, $version );
3419 // Allow plugin to filter the output error trigger
3420 if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
3421 $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
3422 trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
3427 * Is the server running earlier than 1.5.0 version of lighttpd
3431 * @return bool Whether the server is running lighttpd < 1.5.0
3433 function is_lighttpd_before_150() {
3434 $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
3435 $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
3436 return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
3440 * Does the specified module exist in the apache config?
3444 * @param string $mod e.g. mod_rewrite
3445 * @param bool $default The default return value if the module is not found
3448 function apache_mod_loaded($mod, $default = false) {
3454 if ( function_exists('apache_get_modules') ) {
3455 $mods = apache_get_modules();
3456 if ( in_array($mod, $mods) )
3458 } elseif ( function_exists('phpinfo') ) {
3461 $phpinfo = ob_get_clean();
3462 if ( false !== strpos($phpinfo, $mod) )
3469 * Check if IIS 7 supports pretty permalinks
3475 function iis7_supports_permalinks() {
3478 $supports_permalinks = false;
3480 /* First we check if the DOMDocument class exists. If it does not exist,
3481 * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
3482 * hence we just bail out and tell user that pretty permalinks cannot be used.
3483 * This is not a big issue because PHP 4.X is going to be depricated and for IIS it
3484 * is recommended to use PHP 5.X NTS.
3485 * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
3486 * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
3487 * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
3488 * via ISAPI then pretty permalinks will not work.
3490 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
3493 return apply_filters('iis7_supports_permalinks', $supports_permalinks);
3497 * File validates against allowed set of defined rules.
3499 * A return value of '1' means that the $file contains either '..' or './'. A
3500 * return value of '2' means that the $file contains ':' after the first
3501 * character. A return value of '3' means that the file is not in the allowed
3506 * @param string $file File path.
3507 * @param array $allowed_files List of allowed files.
3508 * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
3510 function validate_file( $file, $allowed_files = '' ) {
3511 if ( false !== strpos( $file, '..' ))
3514 if ( false !== strpos( $file, './' ))
3517 if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
3520 if (':' == substr( $file, 1, 1 ))
3527 * Determine if SSL is used.
3531 * @return bool True if SSL, false if not used.
3534 if ( isset($_SERVER['HTTPS']) ) {
3535 if ( 'on' == strtolower($_SERVER['HTTPS']) )
3537 if ( '1' == $_SERVER['HTTPS'] )
3539 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
3546 * Whether SSL login should be forced.
3550 * @param string|bool $force Optional.
3551 * @return bool True if forced, false if not forced.
3553 function force_ssl_login( $force = null ) {
3554 static $forced = false;
3556 if ( !is_null( $force ) ) {
3557 $old_forced = $forced;
3566 * Whether to force SSL used for the Administration Panels.
3570 * @param string|bool $force
3571 * @return bool True if forced, false if not forced.
3573 function force_ssl_admin( $force = null ) {
3574 static $forced = false;
3576 if ( !is_null( $force ) ) {
3577 $old_forced = $forced;
3586 * Guess the URL for the site.
3588 * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
3595 function wp_guess_url() {
3596 if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
3599 $schema = is_ssl() ? 'https://' : 'http://';
3600 $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
3602 return rtrim($url, '/');
3606 * Suspend cache invalidation.
3608 * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
3609 * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
3610 * cache when invalidation is suspended.
3614 * @param bool $suspend Whether to suspend or enable cache invalidation
3615 * @return bool The current suspend setting
3617 function wp_suspend_cache_invalidation($suspend = true) {
3618 global $_wp_suspend_cache_invalidation;
3620 $current_suspend = $_wp_suspend_cache_invalidation;
3621 $_wp_suspend_cache_invalidation = $suspend;
3622 return $current_suspend;
3626 * Retrieve site option value based on name of option.
3629 * @package WordPress
3630 * @subpackage Option
3633 * @uses apply_filters() Calls 'pre_site_option_$option' before checking the option.
3634 * Any value other than false will "short-circuit" the retrieval of the option
3635 * and return the returned value.
3636 * @uses apply_filters() Calls 'site_option_$option', after checking the option, with
3639 * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
3640 * @param mixed $default Optional value to return if option doesn't exist. Default false.
3641 * @param bool $use_cache Whether to use cache. Multisite only. Default true.
3642 * @return mixed Value set for the option.
3644 function get_site_option( $option, $default = false, $use_cache = true ) {
3647 // Allow plugins to short-circuit site options.
3648 $pre = apply_filters( 'pre_site_option_' . $option, false );
3649 if ( false !== $pre )
3652 if ( !is_multisite() ) {
3653 $value = get_option($option, $default);
3655 $cache_key = "{$wpdb->siteid}:$option";
3657 $value = wp_cache_get($cache_key, 'site-options');
3659 if ( !isset($value) || (false === $value) ) {
3660 $row = $wpdb->get_row( $wpdb->prepare("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
3662 // Has to be get_row instead of get_var because of funkiness with 0, false, null values
3663 if ( is_object( $row ) )
3664 $value = $row->meta_value;
3668 $value = maybe_unserialize( $value );
3670 wp_cache_set( $cache_key, $value, 'site-options' );
3674 return apply_filters( 'site_option_' . $option, $value );
3678 * Add a new site option.
3681 * @package WordPress
3682 * @subpackage Option
3685 * @uses apply_filters() Calls 'pre_add_site_option_$option' hook to allow overwriting the
3686 * option value to be stored.
3687 * @uses do_action() Calls 'add_site_option_$option' and 'add_site_option' hooks on success.
3689 * @param string $option Name of option to add. Expected to not be SQL-escaped.
3690 * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
3691 * @return bool False if option was not added and true if option was added.
3693 function add_site_option( $option, $value ) {
3696 $value = apply_filters( 'pre_add_site_option_' . $option, $value );
3698 if ( !is_multisite() ) {
3699 $result = add_option( $option, $value );
3701 $cache_key = "{$wpdb->siteid}:$option";
3703 if ( $wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
3704 return update_site_option( $option, $value );
3706 $value = sanitize_option( $option, $value );
3707 wp_cache_set( $cache_key, $value, 'site-options' );
3710 $value = maybe_serialize($value);
3711 $result = $wpdb->insert( $wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $value ) );
3715 do_action( "add_site_option_{$option}", $option, $value );
3716 do_action( "add_site_option", $option, $value );
3722 * Removes site option by name.
3724 * @see delete_option()
3725 * @package WordPress
3726 * @subpackage Option
3729 * @uses do_action() Calls 'pre_delete_site_option_$option' hook before option is deleted.
3730 * @uses do_action() Calls 'delete_site_option' and 'delete_site_option_$option'
3733 * @param string $option Name of option to remove. Expected to not be SQL-escaped.
3734 * @return bool True, if succeed. False, if failure.
3736 function delete_site_option( $option ) {
3739 // ms_protect_special_option( $option ); @todo
3741 do_action( 'pre_delete_site_option_' . $option );
3743 if ( !is_multisite() ) {
3744 $result = delete_option( $option );
3746 $row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
3747 if ( is_null( $row ) || !$row->meta_id )
3749 $cache_key = "{$wpdb->siteid}:$option";
3750 wp_cache_delete( $cache_key, 'site-options' );
3752 $result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
3756 do_action( "delete_site_option_{$option}", $option );
3757 do_action( "delete_site_option", $option );
3764 * Update the value of a site option that was already added.
3766 * @see update_option()
3768 * @package WordPress
3769 * @subpackage Option
3771 * @uses apply_filters() Calls 'pre_update_site_option_$option' hook to allow overwriting the
3772 * option value to be stored.
3773 * @uses do_action() Calls 'update_site_option_$option' and 'update_site_option' hooks on success.
3775 * @param string $option Name of option. Expected to not be SQL-escaped.
3776 * @param mixed $value Option value. Expected to not be SQL-escaped.
3777 * @return bool False if value was not updated and true if value was updated.
3779 function update_site_option( $option, $value ) {
3782 $oldvalue = get_site_option( $option );
3783 $value = apply_filters( 'pre_update_site_option_' . $option, $value, $oldvalue );
3785 if ( $value === $oldvalue )
3788 if ( !is_multisite() ) {
3789 $result = update_option( $option, $value );
3791 $cache_key = "{$wpdb->siteid}:$option";
3793 if ( $value && !$wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
3794 return add_site_option( $option, $value );
3795 $value = sanitize_option( $option, $value );
3796 wp_cache_set( $cache_key, $value, 'site-options' );
3799 $value = maybe_serialize( $value );
3800 $result = $wpdb->update( $wpdb->sitemeta, array( 'meta_value' => $value ), array( 'site_id' => $wpdb->siteid, 'meta_key' => $option ) );
3805 do_action( "update_site_option_{$option}", $option, $value );
3806 do_action( "update_site_option", $option, $value );
3813 * Delete a site transient
3816 * @package WordPress
3817 * @subpackage Transient
3819 * @uses do_action() Calls 'delete_site_transient_$transient' hook before transient is deleted.
3820 * @uses do_action() Calls 'deleted_site_transient' hook on success.
3822 * @param string $transient Transient name. Expected to not be SQL-escaped.
3823 * @return bool True if successful, false otherwise
3825 function delete_site_transient( $transient ) {
3826 global $_wp_using_ext_object_cache;
3828 do_action( 'delete_site_transient_' . $transient, $transient );
3829 if ( $_wp_using_ext_object_cache ) {
3830 $result = wp_cache_delete( $transient, 'site-transient' );
3832 $option_timeout = '_site_transient_timeout_' . $transient;
3833 $option = '_site_transient_' . $transient;
3834 $result = delete_site_option( $option );
3836 delete_site_option( $option_timeout );
3839 do_action( 'deleted_site_transient', $transient );
3844 * Get the value of a site transient
3846 * If the transient does not exist or does not have a value, then the return value
3849 * @see get_transient()
3851 * @package WordPress
3852 * @subpackage Transient
3854 * @uses apply_filters() Calls 'pre_site_transient_$transient' hook before checking the transient.
3855 * Any value other than false will "short-circuit" the retrieval of the transient
3856 * and return the returned value.
3857 * @uses apply_filters() Calls 'site_transient_$option' hook, after checking the transient, with
3858 * the transient value.
3860 * @param string $transient Transient name. Expected to not be SQL-escaped.
3861 * @return mixed Value of transient
3863 function get_site_transient( $transient ) {
3864 global $_wp_using_ext_object_cache;
3866 $pre = apply_filters( 'pre_site_transient_' . $transient, false );
3867 if ( false !== $pre )
3870 if ( $_wp_using_ext_object_cache ) {
3871 $value = wp_cache_get( $transient, 'site-transient' );
3873 // Core transients that do not have a timeout. Listed here so querying timeouts can be avoided.
3874 $no_timeout = array('update_core', 'update_plugins', 'update_themes');
3875 $transient_option = '_site_transient_' . $transient;
3876 if ( ! in_array( $transient, $no_timeout ) ) {
3877 $transient_timeout = '_site_transient_timeout_' . $transient;
3878 $timeout = get_site_option( $transient_timeout );
3879 if ( false !== $timeout && $timeout < time() ) {
3880 delete_site_option( $transient_option );
3881 delete_site_option( $transient_timeout );
3886 $value = get_site_option( $transient_option );
3889 return apply_filters( 'site_transient_' . $transient, $value );
3893 * Set/update the value of a site transient
3895 * You do not need to serialize values, if the value needs to be serialize, then
3896 * it will be serialized before it is set.
3898 * @see set_transient()
3900 * @package WordPress
3901 * @subpackage Transient
3903 * @uses apply_filters() Calls 'pre_set_site_transient_$transient' hook to allow overwriting the
3904 * transient value to be stored.
3905 * @uses do_action() Calls 'set_site_transient_$transient' and 'setted_site_transient' hooks on success.
3907 * @param string $transient Transient name. Expected to not be SQL-escaped.
3908 * @param mixed $value Transient value. Expected to not be SQL-escaped.
3909 * @param int $expiration Time until expiration in seconds, default 0
3910 * @return bool False if value was not set and true if value was set.
3912 function set_site_transient( $transient, $value, $expiration = 0 ) {
3913 global $_wp_using_ext_object_cache;
3915 $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
3917 if ( $_wp_using_ext_object_cache ) {
3918 $result = wp_cache_set( $transient, $value, 'site-transient', $expiration );
3920 $transient_timeout = '_site_transient_timeout_' . $transient;
3921 $transient = '_site_transient_' . $transient;
3922 if ( false === get_site_option( $transient ) ) {
3924 add_site_option( $transient_timeout, time() + $expiration );
3925 $result = add_site_option( $transient, $value );
3928 update_site_option( $transient_timeout, time() + $expiration );
3929 $result = update_site_option( $transient, $value );
3933 do_action( 'set_site_transient_' . $transient );
3934 do_action( 'setted_site_transient', $transient );
3944 * @package WordPress
3946 * @param int $blog_id optional blog id to test (default current blog)
3947 * @return bool True if not multisite or $blog_id is main site
3949 function is_main_site( $blog_id = '' ) {
3950 global $current_site, $current_blog;
3952 if ( !is_multisite() )
3956 $blog_id = $current_blog->blog_id;
3958 return $blog_id == $current_site->blog_id;
3962 * Whether global terms are enabled.
3966 * @package WordPress
3968 * @return bool True if multisite and global terms enabled
3970 function global_terms_enabled() {
3971 if ( ! is_multisite() )
3974 static $global_terms = null;
3975 if ( is_null( $global_terms ) ) {
3976 $filter = apply_filters( 'global_terms_enabled', null );
3977 if ( ! is_null( $filter ) )
3978 $global_terms = (bool) $filter;
3980 $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
3982 return $global_terms;
3986 * gmt_offset modification for smart timezone handling
3988 * Overrides the gmt_offset option if we have a timezone_string available
3992 * @return float|bool
3994 function wp_timezone_override_offset() {
3995 if ( !wp_timezone_supported() ) {
3998 if ( !$timezone_string = get_option( 'timezone_string' ) ) {
4002 $timezone_object = timezone_open( $timezone_string );
4003 $datetime_object = date_create();
4004 if ( false === $timezone_object || false === $datetime_object ) {
4007 return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
4011 * Check for PHP timezone support
4017 function wp_timezone_supported() {
4020 function_exists( 'date_create' ) &&
4021 function_exists( 'date_default_timezone_set' ) &&
4022 function_exists( 'timezone_identifiers_list' ) &&
4023 function_exists( 'timezone_open' ) &&
4024 function_exists( 'timezone_offset_get' )
4028 return apply_filters( 'timezone_support', $support );
4032 * {@internal Missing Short Description}}
4036 * @param unknown_type $a
4037 * @param unknown_type $b
4040 function _wp_timezone_choice_usort_callback( $a, $b ) {
4041 // Don't use translated versions of Etc
4042 if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
4043 // Make the order of these more like the old dropdown
4044 if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
4045 return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
4047 if ( 'UTC' === $a['city'] ) {
4048 if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
4053 if ( 'UTC' === $b['city'] ) {
4054 if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
4059 return strnatcasecmp( $a['city'], $b['city'] );
4061 if ( $a['t_continent'] == $b['t_continent'] ) {
4062 if ( $a['t_city'] == $b['t_city'] ) {
4063 return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
4065 return strnatcasecmp( $a['t_city'], $b['t_city'] );
4067 // Force Etc to the bottom of the list
4068 if ( 'Etc' === $a['continent'] ) {
4071 if ( 'Etc' === $b['continent'] ) {
4074 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
4079 * Gives a nicely formatted list of timezone strings // temporary! Not in final
4083 * @param string $selected_zone Selected Zone
4086 function wp_timezone_choice( $selected_zone ) {
4087 static $mo_loaded = false;
4089 $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
4091 // Load translations for continents and cities
4092 if ( !$mo_loaded ) {
4093 $locale = get_locale();
4094 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
4095 load_textdomain( 'continents-cities', $mofile );
4100 foreach ( timezone_identifiers_list() as $zone ) {
4101 $zone = explode( '/', $zone );
4102 if ( !in_array( $zone[0], $continents ) ) {
4106 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
4108 0 => ( isset( $zone[0] ) && $zone[0] ),
4109 1 => ( isset( $zone[1] ) && $zone[1] ),
4110 2 => ( isset( $zone[2] ) && $zone[2] ),
4112 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
4113 $exists[4] = ( $exists[1] && $exists[3] );
4114 $exists[5] = ( $exists[2] && $exists[3] );
4117 'continent' => ( $exists[0] ? $zone[0] : '' ),
4118 'city' => ( $exists[1] ? $zone[1] : '' ),
4119 'subcity' => ( $exists[2] ? $zone[2] : '' ),
4120 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
4121 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
4122 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
4125 usort( $zonen, '_wp_timezone_choice_usort_callback' );
4127 $structure = array();
4129 if ( empty( $selected_zone ) ) {
4130 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
4133 foreach ( $zonen as $key => $zone ) {
4134 // Build value in an array to join later
4135 $value = array( $zone['continent'] );
4137 if ( empty( $zone['city'] ) ) {
4138 // It's at the continent level (generally won't happen)
4139 $display = $zone['t_continent'];
4141 // It's inside a continent group
4143 // Continent optgroup
4144 if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
4145 $label = $zone['t_continent'];
4146 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
4149 // Add the city to the value
4150 $value[] = $zone['city'];
4152 $display = $zone['t_city'];
4153 if ( !empty( $zone['subcity'] ) ) {
4154 // Add the subcity to the value
4155 $value[] = $zone['subcity'];
4156 $display .= ' - ' . $zone['t_subcity'];
4161 $value = join( '/', $value );
4163 if ( $value === $selected_zone ) {
4164 $selected = 'selected="selected" ';
4166 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
4168 // Close continent optgroup
4169 if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
4170 $structure[] = '</optgroup>';
4175 $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
4177 if ( 'UTC' === $selected_zone )
4178 $selected = 'selected="selected" ';
4179 $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
4180 $structure[] = '</optgroup>';
4182 // Do manual UTC offsets
4183 $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
4184 $offset_range = array (-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
4185 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14);
4186 foreach ( $offset_range as $offset ) {
4188 $offset_name = '+' . $offset;
4190 $offset_name = (string) $offset;
4192 $offset_value = $offset_name;
4193 $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
4194 $offset_name = 'UTC' . $offset_name;
4195 $offset_value = 'UTC' . $offset_value;
4197 if ( $offset_value === $selected_zone )
4198 $selected = 'selected="selected" ';
4199 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
4202 $structure[] = '</optgroup>';
4204 return join( "\n", $structure );
4208 * Strip close comment and close php tags from file headers used by WP
4209 * See http://core.trac.wordpress.org/ticket/8497
4213 * @param string $str
4216 function _cleanup_header_comment($str) {
4217 return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
4221 * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
4225 function wp_scheduled_delete() {
4228 $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
4230 $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);
4232 foreach ( (array) $posts_to_delete as $post ) {
4233 $post_id = (int) $post['post_id'];
4237 $del_post = get_post($post_id);
4239 if ( !$del_post || 'trash' != $del_post->post_status ) {
4240 delete_post_meta($post_id, '_wp_trash_meta_status');
4241 delete_post_meta($post_id, '_wp_trash_meta_time');
4243 wp_delete_post($post_id);
4247 $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);
4249 foreach ( (array) $comments_to_delete as $comment ) {
4250 $comment_id = (int) $comment['comment_id'];
4254 $del_comment = get_comment($comment_id);
4256 if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
4257 delete_comment_meta($comment_id, '_wp_trash_meta_time');
4258 delete_comment_meta($comment_id, '_wp_trash_meta_status');
4260 wp_delete_comment($comment_id);
4266 * Retrieve metadata from a file.
4268 * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
4269 * Each piece of metadata must be on its own line. Fields can not span multple
4270 * lines, the value will get cut at the end of the first line.
4272 * If the file data is not within that first 8kiB, then the author should correct
4273 * their plugin file and move the data headers to the top.
4275 * @see http://codex.wordpress.org/File_Header
4278 * @param string $file Path to the file
4279 * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
4280 * @param string $context If specified adds filter hook "extra_{$context}_headers"
4282 function get_file_data( $file, $default_headers, $context = '' ) {
4283 // We don't need to write to the file, so just open for reading.
4284 $fp = fopen( $file, 'r' );
4286 // Pull only the first 8kiB of the file in.
4287 $file_data = fread( $fp, 8192 );
4289 // PHP will close file handle, but we are good citizens.
4292 if ( $context != '' ) {
4293 $extra_headers = apply_filters( "extra_{$context}_headers", array() );
4295 $extra_headers = array_flip( $extra_headers );
4296 foreach( $extra_headers as $key=>$value ) {
4297 $extra_headers[$key] = $key;
4299 $all_headers = array_merge( $extra_headers, (array) $default_headers );
4301 $all_headers = $default_headers;
4304 foreach ( $all_headers as $field => $regex ) {
4305 preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
4306 if ( !empty( ${$field} ) )
4307 ${$field} = _cleanup_header_comment( ${$field}[1] );
4312 $file_data = compact( array_keys( $all_headers ) );
4318 * Used internally to tidy up the search terms
4326 function _search_terms_tidy($t) {
4327 return trim($t, "\"'\n\r ");
4333 * Useful for returning true to filters easily
4336 * @see __return_false()
4339 function __return_true() {
4346 * Useful for returning false to filters easily
4349 * @see __return_true()
4350 * @return bool false
4352 function __return_false() {
4359 * Useful for returning 0 to filters easily
4362 * @see __return_zero()
4365 function __return_zero() {
4370 * Returns an empty array
4372 * Useful for returning an empty array to filters easily
4375 * @see __return_zero()
4376 * @return array Empty array
4378 function __return_empty_array() {
4383 * Send a HTTP header to disable content type sniffing in browsers which support it.
4385 * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
4386 * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
4391 function send_nosniff_header() {
4392 @header( 'X-Content-Type-Options: nosniff' );
4396 * Returns a MySQL expression for selecting the week number based on the start_of_week option.
4400 * @param string $column
4403 function _wp_mysql_week( $column ) {
4404 switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
4407 return "WEEK( $column, 0 )";
4409 return "WEEK( $column, 1 )";
4415 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
4420 * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
4425 * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
4426 * @param int $start The ID to start the loop check at
4427 * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
4428 * @param array $callback_args optional additional arguments to send to $callback
4429 * @return array IDs of all members of loop
4431 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
4432 $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
4434 if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
4437 return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
4441 * Uses the "The Tortoise and the Hare" algorithm to detect loops.
4443 * For every step of the algorithm, the hare takes two steps and the tortoise one.
4444 * If the hare ever laps the tortoise, there must be a loop.
4449 * @param callback $callback function that accupts ( ID, callback_arg, ... ) and outputs parent_ID
4450 * @param int $start The ID to start the loop check at
4451 * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
4452 * @param array $callback_args optional additional arguments to send to $callback
4453 * @param bool $_return_loop Return loop members or just detect presence of loop?
4454 * Only set to true if you already know the given $start is part of a loop
4455 * (otherwise the returned array might include branches)
4456 * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
4458 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
4459 $tortoise = $hare = $evanescent_hare = $start;
4462 // Set evanescent_hare to one past hare
4463 // Increment hare two steps
4467 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
4469 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
4471 if ( $_return_loop )
4472 $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
4474 // tortoise got lapped - must be a loop
4475 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
4476 return $_return_loop ? $return : $tortoise;
4478 // Increment tortoise by one step
4479 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );