]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions.php
Wordpress 3.1.3-scripts
[autoinstalls/wordpress.git] / wp-includes / functions.php
1 <?php
2 /**
3  * Main WordPress API
4  *
5  * @package WordPress
6  */
7
8 /**
9  * Converts MySQL DATETIME field to user specified date format.
10  *
11  * If $dateformatstring has 'G' value, then gmmktime() function will be used to
12  * make the time. If $dateformatstring is set to 'U', then mktime() function
13  * will be used to make the time.
14  *
15  * The $translate will only be used, if it is set to true and it is by default
16  * and if the $wp_locale object has the month and weekday set.
17  *
18  * @since 0.71
19  *
20  * @param string $dateformatstring Either 'G', 'U', or php date format.
21  * @param string $mysqlstring Time from mysql DATETIME field.
22  * @param bool $translate Optional. Default is true. Will switch format to locale.
23  * @return string Date formated by $dateformatstring or locale (if available).
24  */
25 function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
26         $m = $mysqlstring;
27         if ( empty( $m ) )
28                 return false;
29
30         if ( 'G' == $dateformatstring )
31                 return strtotime( $m . ' +0000' );
32
33         $i = strtotime( $m );
34
35         if ( 'U' == $dateformatstring )
36                 return $i;
37
38         if ( $translate )
39                 return date_i18n( $dateformatstring, $i );
40         else
41                 return date( $dateformatstring, $i );
42 }
43
44 /**
45  * Retrieve the current time based on specified type.
46  *
47  * The 'mysql' type will return the time in the format for MySQL DATETIME field.
48  * The 'timestamp' type will return the current timestamp.
49  *
50  * If $gmt is set to either '1' or 'true', then both types will use GMT time.
51  * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
52  *
53  * @since 1.0.0
54  *
55  * @param string $type Either 'mysql' or 'timestamp'.
56  * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
57  * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
58  */
59 function current_time( $type, $gmt = 0 ) {
60         switch ( $type ) {
61                 case 'mysql':
62                         return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
63                         break;
64                 case 'timestamp':
65                         return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
66                         break;
67         }
68 }
69
70 /**
71  * Retrieve the date in localized format, based on timestamp.
72  *
73  * If the locale specifies the locale month and weekday, then the locale will
74  * take over the format for the date. If it isn't, then the date format string
75  * will be used instead.
76  *
77  * @since 0.71
78  *
79  * @param string $dateformatstring Format to display the date.
80  * @param int $unixtimestamp Optional. Unix timestamp.
81  * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
82  * @return string The date, translated if locale specifies it.
83  */
84 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
85         global $wp_locale;
86         $i = $unixtimestamp;
87         // Sanity check for PHP 5.1.0-
88         if ( false === $i || intval($i) < 0 ) {
89                 if ( ! $gmt )
90                         $i = current_time( 'timestamp' );
91                 else
92                         $i = time();
93                 // we should not let date() interfere with our
94                 // specially computed timestamp
95                 $gmt = true;
96         }
97
98         // store original value for language with untypical grammars
99         // see http://core.trac.wordpress.org/ticket/9396
100         $req_format = $dateformatstring;
101
102         $datefunc = $gmt? 'gmdate' : 'date';
103
104         if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
105                 $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
106                 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
107                 $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
108                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
109                 $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
110                 $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
111                 $dateformatstring = ' '.$dateformatstring;
112                 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
113                 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
114                 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
115                 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
116                 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
117                 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
118
119                 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
120         }
121         $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
122         $timezone_formats_re = implode( '|', $timezone_formats );
123         if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) && 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 );
134                                 }
135                         }
136                 }
137         }
138         $j = @$datefunc( $dateformatstring, $i );
139         // allow plugins to redo this entirely for languages with untypical grammars
140         $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
141         return $j;
142 }
143
144 /**
145  * Convert integer number to format based on the locale.
146  *
147  * @since 2.3.0
148  *
149  * @param int $number The number to convert based on locale.
150  * @param int $decimals Precision of the number of decimal places.
151  * @return string Converted number in string format.
152  */
153 function number_format_i18n( $number, $decimals = 0 ) {
154         global $wp_locale;
155         $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
156         return apply_filters( 'number_format_i18n', $formatted );
157 }
158
159 /**
160  * Convert number of bytes largest unit bytes will fit into.
161  *
162  * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
163  * number of bytes to human readable number by taking the number of that unit
164  * that the bytes will go into it. Supports TB value.
165  *
166  * Please note that integers in PHP are limited to 32 bits, unless they are on
167  * 64 bit architecture, then they have 64 bit size. If you need to place the
168  * larger size then what PHP integer type will hold, then use a string. It will
169  * be converted to a double, which should always have 64 bit length.
170  *
171  * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
172  * @link http://en.wikipedia.org/wiki/Byte
173  *
174  * @since 2.3.0
175  *
176  * @param int|string $bytes Number of bytes. Note max integer size for integers.
177  * @param int $decimals Precision of number of decimal places. Deprecated.
178  * @return bool|string False on failure. Number string on success.
179  */
180 function size_format( $bytes, $decimals = 0 ) {
181         $quant = array(
182                 // ========================= Origin ====
183                 'TB' => 1099511627776,  // pow( 1024, 4)
184                 'GB' => 1073741824,     // pow( 1024, 3)
185                 'MB' => 1048576,        // pow( 1024, 2)
186                 'kB' => 1024,           // pow( 1024, 1)
187                 'B ' => 1,              // pow( 1024, 0)
188         );
189         foreach ( $quant as $unit => $mag )
190                 if ( doubleval($bytes) >= $mag )
191                         return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
192
193         return false;
194 }
195
196 /**
197  * Get the week start and end from the datetime or date string from mysql.
198  *
199  * @since 0.71
200  *
201  * @param string $mysqlstring Date or datetime field type from mysql.
202  * @param int $start_of_week Optional. Start of the week as an integer.
203  * @return array Keys are 'start' and 'end'.
204  */
205 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
206         $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
207         $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
208         $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
209         $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
210         $weekday = date( 'w', $day ); // The day of the week from the timestamp
211         if ( !is_numeric($start_of_week) )
212                 $start_of_week = get_option( 'start_of_week' );
213
214         if ( $weekday < $start_of_week )
215                 $weekday += 7;
216
217         $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
218         $end = $start + 604799; // $start + 7 days - 1 second
219         return compact( 'start', 'end' );
220 }
221
222 /**
223  * Unserialize value only if it was serialized.
224  *
225  * @since 2.0.0
226  *
227  * @param string $original Maybe unserialized original, if is needed.
228  * @return mixed Unserialized data can be any type.
229  */
230 function maybe_unserialize( $original ) {
231         if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
232                 return @unserialize( $original );
233         return $original;
234 }
235
236 /**
237  * Check value to find if it was serialized.
238  *
239  * If $data is not an string, then returned value will always be false.
240  * Serialized data is always a string.
241  *
242  * @since 2.0.5
243  *
244  * @param mixed $data Value to check to see if was serialized.
245  * @return bool False if not serialized and true if it was.
246  */
247 function is_serialized( $data ) {
248         // if it isn't a string, it isn't serialized
249         if ( ! is_string( $data ) )
250                 return false;
251         $data = trim( $data );
252         if ( 'N;' == $data )
253                 return true;
254         $length = strlen( $data );
255         if ( $length < 4 )
256                 return false;
257         if ( ':' !== $data[1] )
258                 return false;
259         $lastc = $data[$length-1];
260         if ( ';' !== $lastc && '}' !== $lastc )
261                 return false;
262         $token = $data[0];
263         switch ( $token ) {
264                 case 's' :
265                         if ( '"' !== $data[$length-2] )
266                                 return false;
267                 case 'a' :
268                 case 'O' :
269                         return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
270                 case 'b' :
271                 case 'i' :
272                 case 'd' :
273                         return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
274         }
275         return false;
276 }
277
278 /**
279  * Check whether serialized data is of string type.
280  *
281  * @since 2.0.5
282  *
283  * @param mixed $data Serialized data
284  * @return bool False if not a serialized string, true if it is.
285  */
286 function is_serialized_string( $data ) {
287         // if it isn't a string, it isn't a serialized string
288         if ( !is_string( $data ) )
289                 return false;
290         $data = trim( $data );
291         if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
292                 return true;
293         return false;
294 }
295
296 /**
297  * Retrieve option value based on name of option.
298  *
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.
303  *
304  * If the option was serialized then it will be unserialized when it is returned.
305  *
306  * @since 1.5.0
307  * @package WordPress
308  * @subpackage Option
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
314  *      the option value.
315  *
316  * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
317  * @return mixed Value set for the option.
318  */
319 function get_option( $option, $default = false ) {
320         global $wpdb;
321
322         // Allow plugins to short-circuit options.
323         $pre = apply_filters( 'pre_option_' . $option, false );
324         if ( false !== $pre )
325                 return $pre;
326
327         $option = trim($option);
328         if ( empty($option) )
329                 return false;
330
331         if ( defined( 'WP_SETUP_CONFIG' ) )
332                 return false;
333
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] ) )
338                         return $default;
339
340                 $alloptions = wp_load_alloptions();
341
342                 if ( isset( $alloptions[$option] ) ) {
343                         $value = $alloptions[$option];
344                 } else {
345                         $value = wp_cache_get( $option, 'options' );
346
347                         if ( false === $value ) {
348                                 $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
349
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' );
357                                         return $default;
358                                 }
359                         }
360                 }
361         } else {
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;
367                 else
368                         return $default;
369         }
370
371         // If home is not set use siteurl.
372         if ( 'home' == $option && '' == $value )
373                 return get_option( 'siteurl' );
374
375         if ( in_array( $option, array('siteurl', 'home', 'category_base', 'tag_base') ) )
376                 $value = untrailingslashit( $value );
377
378         return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
379 }
380
381 /**
382  * Protect WordPress special option from being modified.
383  *
384  * Will die if $option is in protected list. Protected options are 'alloptions'
385  * and 'notoptions' options.
386  *
387  * @since 2.2.0
388  * @package WordPress
389  * @subpackage Option
390  *
391  * @param string $option Option name.
392  */
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 ) ) );
397 }
398
399 /**
400  * Print option value after sanitizing for forms.
401  *
402  * @uses attr Sanitizes value.
403  * @since 1.5.0
404  * @package WordPress
405  * @subpackage Option
406  *
407  * @param string $option Option name.
408  */
409 function form_option( $option ) {
410         echo esc_attr( get_option( $option ) );
411 }
412
413 /**
414  * Loads and caches all autoloaded options, if available or all options.
415  *
416  * @since 2.2.0
417  * @package WordPress
418  * @subpackage Option
419  *
420  * @return array List of all options.
421  */
422 function wp_load_alloptions() {
423         global $wpdb;
424
425         if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
426                 $alloptions = wp_cache_get( 'alloptions', 'options' );
427         else
428                 $alloptions = false;
429
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;
438                 }
439                 if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
440                         wp_cache_add( 'alloptions', $alloptions, 'options' );
441         }
442
443         return $alloptions;
444 }
445
446 /**
447  * Loads and caches certain often requested site options if is_multisite() and a peristent cache is not being used.
448  *
449  * @since 3.0.0
450  * @package WordPress
451  * @subpackage Option
452  *
453  * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
454  */
455 function wp_load_core_site_options( $site_id = null ) {
456         global $wpdb, $_wp_using_ext_object_cache;
457
458         if ( !is_multisite() || $_wp_using_ext_object_cache || defined( 'WP_INSTALLING' ) )
459                 return;
460
461         if ( empty($site_id) )
462                 $site_id = $wpdb->siteid;
463
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' );
465
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) );
468
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 );
473
474                 wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
475         }
476 }
477
478 /**
479  * Update the value of an option that was already added.
480  *
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.
484  *
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().
488  *
489  * @since 1.0.0
490  * @package WordPress
491  * @subpackage Option
492  *
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.
497  *
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.
501  */
502 function update_option( $option, $newvalue ) {
503         global $wpdb;
504
505         $option = trim($option);
506         if ( empty($option) )
507                 return false;
508
509         wp_protect_special_option( $option );
510
511         if ( is_object($newvalue) )
512                 $newvalue = wp_clone($newvalue);
513
514         $newvalue = sanitize_option( $option, $newvalue );
515         $oldvalue = get_option( $option );
516         $newvalue = apply_filters( 'pre_update_option_' . $option, $newvalue, $oldvalue );
517
518         // If the new and old values are the same, no need to update.
519         if ( $newvalue === $oldvalue )
520                 return false;
521
522         if ( false === $oldvalue )
523                 return add_option( $option, $newvalue );
524
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' );
529         }
530
531         $_newvalue = $newvalue;
532         $newvalue = maybe_serialize( $newvalue );
533
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' );
540                 } else {
541                         wp_cache_set( $option, $_newvalue, 'options' );
542                 }
543         }
544
545         $result = $wpdb->update( $wpdb->options, array( 'option_value' => $newvalue ), array( 'option_name' => $option ) );
546
547         if ( $result ) {
548                 do_action( "update_option_{$option}", $oldvalue, $_newvalue );
549                 do_action( 'updated_option', $option, $oldvalue, $_newvalue );
550                 return true;
551         }
552         return false;
553 }
554
555 /**
556  * Add a new option.
557  *
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.
561  *
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.
567  *
568  * @package WordPress
569  * @subpackage Option
570  * @since 1.0.0
571  *
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.
574  *
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.
580  */
581 function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
582         global $wpdb;
583
584         if ( !empty( $deprecated ) )
585                 _deprecated_argument( __FUNCTION__, '2.3' );
586
587         $option = trim($option);
588         if ( empty($option) )
589                 return false;
590
591         wp_protect_special_option( $option );
592
593         if ( is_object($value) )
594                 $value = wp_clone($value);
595
596         $value = sanitize_option( $option, $value );
597
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 ) )
602                         return;
603
604         $_value = $value;
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' );
613                 } else {
614                         wp_cache_set( $option, $value, 'options' );
615                 }
616         }
617
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' );
623         }
624
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 ) );
626
627         if ( $result ) {
628                 do_action( "add_option_{$option}", $option, $_value );
629                 do_action( 'added_option', $option, $_value );
630                 return true;
631         }
632         return false;
633 }
634
635 /**
636  * Removes option by name. Prevents removal of protected WordPress options.
637  *
638  * @package WordPress
639  * @subpackage Option
640  * @since 1.2.0
641  *
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.
644  *
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.
647  */
648 function delete_option( $option ) {
649         global $wpdb;
650
651         wp_protect_special_option( $option );
652
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 ) )
656                 return false;
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' );
665                         }
666                 } else {
667                         wp_cache_delete( $option, 'options' );
668                 }
669         }
670         if ( $result ) {
671                 do_action( "delete_option_$option", $option );
672                 do_action( 'deleted_option', $option );
673                 return true;
674         }
675         return false;
676 }
677
678 /**
679  * Delete a transient
680  *
681  * @since 2.8.0
682  * @package WordPress
683  * @subpackage Transient
684  *
685  * @uses do_action() Calls 'delete_transient_$transient' hook before transient is deleted.
686  * @uses do_action() Calls 'deleted_transient' hook on success.
687  *
688  * @param string $transient Transient name. Expected to not be SQL-escaped.
689  * @return bool true if successful, false otherwise
690  */
691 function delete_transient( $transient ) {
692         global $_wp_using_ext_object_cache;
693
694         do_action( 'delete_transient_' . $transient, $transient );
695
696         if ( $_wp_using_ext_object_cache ) {
697                 $result = wp_cache_delete( $transient, 'transient' );
698         } else {
699                 $option_timeout = '_transient_timeout_' . $transient;
700                 $option = '_transient_' . $transient;
701                 $result = delete_option( $option );
702                 if ( $result )
703                         delete_option( $option_timeout );
704         }
705
706         if ( $result )
707                 do_action( 'deleted_transient', $transient );
708         return $result;
709 }
710
711 /**
712  * Get the value of a transient
713  *
714  * If the transient does not exist or does not have a value, then the return value
715  * will be false.
716  *
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.
722  *
723  * @since 2.8.0
724  * @package WordPress
725  * @subpackage Transient
726  *
727  * @param string $transient Transient name. Expected to not be SQL-escaped
728  * @return mixed Value of transient
729  */
730 function get_transient( $transient ) {
731         global $_wp_using_ext_object_cache;
732
733         $pre = apply_filters( 'pre_transient_' . $transient, false );
734         if ( false !== $pre )
735                 return $pre;
736
737         if ( $_wp_using_ext_object_cache ) {
738                 $value = wp_cache_get( $transient, 'transient' );
739         } else {
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 );
749                                         return false;
750                                 }
751                         }
752                 }
753
754                 $value = get_option( $transient_option );
755         }
756
757         return apply_filters( 'transient_' . $transient, $value );
758 }
759
760 /**
761  * Set/update the value of a transient
762  *
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.
765  *
766  * @since 2.8.0
767  * @package WordPress
768  * @subpackage Transient
769  *
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.
773  *
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.
778  */
779 function set_transient( $transient, $value, $expiration = 0 ) {
780         global $_wp_using_ext_object_cache;
781
782         $value = apply_filters( 'pre_set_transient_' . $transient, $value );
783
784         if ( $_wp_using_ext_object_cache ) {
785                 $result = wp_cache_set( $transient, $value, 'transient', $expiration );
786         } else {
787                 $transient_timeout = '_transient_timeout_' . $transient;
788                 $transient = '_transient_' . $transient;
789                 if ( false === get_option( $transient ) ) {
790                         $autoload = 'yes';
791                         if ( $expiration ) {
792                                 $autoload = 'no';
793                                 add_option( $transient_timeout, time() + $expiration, '', 'no' );
794                         }
795                         $result = add_option( $transient, $value, '', $autoload );
796                 } else {
797                         if ( $expiration )
798                                 update_option( $transient_timeout, time() + $expiration );
799                         $result = update_option( $transient, $value );
800                 }
801         }
802         if ( $result ) {
803                 do_action( 'set_transient_' . $transient );
804                 do_action( 'setted_transient', $transient );
805         }
806         return $result;
807 }
808
809 /**
810  * Saves and restores user interface settings stored in a cookie.
811  *
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
814  * the settings.
815  *
816  * @package WordPress
817  * @subpackage Option
818  * @since 2.7.0
819  */
820 function wp_user_settings() {
821
822         if ( ! is_admin() )
823                 return;
824
825         if ( defined('DOING_AJAX') )
826                 return;
827
828         if ( ! $user = wp_get_current_user() )
829                 return;
830
831         $settings = get_user_option( 'user-settings', $user->ID );
832
833         if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
834                 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
835
836                 if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
837                         if ( $cookie == $settings )
838                                 return;
839
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;
842
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 );
846                                 return;
847                         }
848                 }
849         }
850
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;
854 }
855
856 /**
857  * Retrieve user interface setting value based on setting name.
858  *
859  * @package WordPress
860  * @subpackage Option
861  * @since 2.7.0
862  *
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.
866  */
867 function get_user_setting( $name, $default = false ) {
868
869         $all = get_all_user_settings();
870
871         return isset($all[$name]) ? $all[$name] : $default;
872 }
873
874 /**
875  * Add or update user interface setting.
876  *
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().
879  *
880  * @package WordPress
881  * @subpackage Option
882  * @since 2.8.0
883  *
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.
887  */
888 function set_user_setting( $name, $value ) {
889
890         if ( headers_sent() )
891                 return false;
892
893         $all = get_all_user_settings();
894         $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
895
896         if ( empty($name) )
897                 return false;
898
899         $all[$name] = $value;
900
901         return wp_set_all_user_settings($all);
902 }
903
904 /**
905  * Delete user interface settings.
906  *
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().
909  *
910  * @package WordPress
911  * @subpackage Option
912  * @since 2.7.0
913  *
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.
916  */
917 function delete_user_setting( $names ) {
918
919         if ( headers_sent() )
920                 return false;
921
922         $all = get_all_user_settings();
923         $names = (array) $names;
924
925         foreach ( $names as $name ) {
926                 if ( isset($all[$name]) ) {
927                         unset($all[$name]);
928                         $deleted = true;
929                 }
930         }
931
932         if ( isset($deleted) )
933                 return wp_set_all_user_settings($all);
934
935         return false;
936 }
937
938 /**
939  * Retrieve all user interface settings.
940  *
941  * @package WordPress
942  * @subpackage Option
943  * @since 2.7.0
944  *
945  * @return array the last saved user settings or empty array.
946  */
947 function get_all_user_settings() {
948         global $_updated_user_settings;
949
950         if ( ! $user = wp_get_current_user() )
951                 return array();
952
953         if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
954                 return $_updated_user_settings;
955
956         $all = array();
957         if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
958                 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
959
960                 if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
961                         parse_str($cookie, $all);
962
963         } else {
964                 $option = get_user_option('user-settings', $user->ID);
965                 if ( $option && is_string($option) )
966                         parse_str( $option, $all );
967         }
968
969         return $all;
970 }
971
972 /**
973  * Private. Set all user interface settings.
974  *
975  * @package WordPress
976  * @subpackage Option
977  * @since 2.8.0
978  *
979  * @param unknown $all
980  * @return bool
981  */
982 function wp_set_all_user_settings($all) {
983         global $_updated_user_settings;
984
985         if ( ! $user = wp_get_current_user() )
986                 return false;
987
988         $_updated_user_settings = $all;
989         $settings = '';
990         foreach ( $all as $k => $v ) {
991                 $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
992                 $settings .= $k . '=' . $v . '&';
993         }
994
995         $settings = rtrim($settings, '&');
996
997         update_user_option( $user->ID, 'user-settings', $settings, false );
998         update_user_option( $user->ID, 'user-settings-time', time(), false );
999
1000         return true;
1001 }
1002
1003 /**
1004  * Delete the user settings of the current user.
1005  *
1006  * @package WordPress
1007  * @subpackage Option
1008  * @since 2.7.0
1009  */
1010 function delete_all_user_settings() {
1011         if ( ! $user = wp_get_current_user() )
1012                 return;
1013
1014         update_user_option( $user->ID, 'user-settings', '', false );
1015         setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
1016 }
1017
1018 /**
1019  * Serialize data, if needed.
1020  *
1021  * @since 2.0.5
1022  *
1023  * @param mixed $data Data that might be serialized.
1024  * @return mixed A scalar data
1025  */
1026 function maybe_serialize( $data ) {
1027         if ( is_array( $data ) || is_object( $data ) )
1028                 return serialize( $data );
1029
1030         if ( is_serialized( $data ) )
1031                 return serialize( $data );
1032
1033         return $data;
1034 }
1035
1036 /**
1037  * Retrieve post title from XMLRPC XML.
1038  *
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.
1041  *
1042  * @package WordPress
1043  * @subpackage XMLRPC
1044  * @since 0.71
1045  *
1046  * @global string $post_default_title Default XMLRPC post title.
1047  *
1048  * @param string $content XMLRPC XML Request content
1049  * @return string Post title
1050  */
1051 function xmlrpc_getposttitle( $content ) {
1052         global $post_default_title;
1053         if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
1054                 $post_title = $matchtitle[1];
1055         } else {
1056                 $post_title = $post_default_title;
1057         }
1058         return $post_title;
1059 }
1060
1061 /**
1062  * Retrieve the post category or categories from XMLRPC XML.
1063  *
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.
1067  *
1068  * @package WordPress
1069  * @subpackage XMLRPC
1070  * @since 0.71
1071  *
1072  * @global string $post_default_category Default XMLRPC post category.
1073  *
1074  * @param string $content XMLRPC XML Request content
1075  * @return string|array List of categories or category name.
1076  */
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 );
1082         } else {
1083                 $post_category = $post_default_category;
1084         }
1085         return $post_category;
1086 }
1087
1088 /**
1089  * XMLRPC XML content without title and category elements.
1090  *
1091  * @package WordPress
1092  * @subpackage XMLRPC
1093  * @since 0.71
1094  *
1095  * @param string $content XMLRPC XML Request content
1096  * @return string XMLRPC XML Request content without title and category elements.
1097  */
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 );
1102         return $content;
1103 }
1104
1105 /**
1106  * Open the file handle for debugging.
1107  *
1108  * This function is used for XMLRPC feature, but it is general purpose enough
1109  * to be used in anywhere.
1110  *
1111  * @see fopen() for mode options.
1112  * @package WordPress
1113  * @subpackage Debug
1114  * @since 0.71
1115  * @uses $debug Used for whether debugging is enabled.
1116  *
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.
1120  */
1121 function debug_fopen( $filename, $mode ) {
1122         global $debug;
1123         if ( 1 == $debug ) {
1124                 $fp = fopen( $filename, $mode );
1125                 return $fp;
1126         } else {
1127                 return false;
1128         }
1129 }
1130
1131 /**
1132  * Write contents to the file used for debugging.
1133  *
1134  * Technically, this can be used to write to any file handle when the global
1135  * $debug is set to 1 or true.
1136  *
1137  * @package WordPress
1138  * @subpackage Debug
1139  * @since 0.71
1140  * @uses $debug Used for whether debugging is enabled.
1141  *
1142  * @param resource $fp File handle for debugging file.
1143  * @param string $string Content to write to debug file.
1144  */
1145 function debug_fwrite( $fp, $string ) {
1146         global $debug;
1147         if ( 1 == $debug )
1148                 fwrite( $fp, $string );
1149 }
1150
1151 /**
1152  * Close the debugging file handle.
1153  *
1154  * Technically, this can be used to close any file handle when the global $debug
1155  * is set to 1 or true.
1156  *
1157  * @package WordPress
1158  * @subpackage Debug
1159  * @since 0.71
1160  * @uses $debug Used for whether debugging is enabled.
1161  *
1162  * @param resource $fp Debug File handle.
1163  */
1164 function debug_fclose( $fp ) {
1165         global $debug;
1166         if ( 1 == $debug )
1167                 fclose( $fp );
1168 }
1169
1170 /**
1171  * Check content for video and audio links to add as enclosures.
1172  *
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.
1176  *
1177  * @package WordPress
1178  * @since 1.5.0
1179  *
1180  * @uses $wpdb
1181  *
1182  * @param string $content Post Content
1183  * @param int $post_ID Post ID
1184  */
1185 function do_enclose( $content, $post_ID ) {
1186         global $wpdb;
1187
1188         //TODO: Tidy this ghetto code up and make the debug code optional
1189         include_once( ABSPATH . WPINC . '/class-IXR.php' );
1190
1191         $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
1192         $post_links = array();
1193         debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
1194
1195         $pung = get_enclosed( $post_ID );
1196
1197         $ltrs = '\w';
1198         $gunk = '/#~:.?+=&%@!\-';
1199         $punc = '.:?\-';
1200         $any = $ltrs . $gunk . $punc;
1201
1202         preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
1203
1204         debug_fwrite( $log, 'Post contents:' );
1205         debug_fwrite( $log, $content . "\n" );
1206
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 );
1213                 }
1214         }
1215
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 )
1220                                 continue;
1221                         if ( isset( $test['query'] ) )
1222                                 $post_links[] = $link_test;
1223                         elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
1224                                 $post_links[] = $link_test;
1225                 }
1226         }
1227
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 ) . '%' ) ) ) {
1230
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' );
1235
1236                                 // Check to see if we can figure out the mime type from
1237                                 // the extension
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 ) ) {
1244                                                                 $type = $mime;
1245                                                                 break;
1246                                                         }
1247                                                 }
1248                                         }
1249                                 }
1250
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 );
1255                                 }
1256                         }
1257                 }
1258         }
1259 }
1260
1261 /**
1262  * Perform a HTTP HEAD or GET request.
1263  *
1264  * If $file_path is a writable filename, this will do a GET request and write
1265  * the file to that path.
1266  *
1267  * @since 2.5.0
1268  *
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.
1273  */
1274 function wp_get_http( $url, $file_path = false, $red = 1 ) {
1275         @set_time_limit( 60 );
1276
1277         if ( $red > 5 )
1278                 return false;
1279
1280         $options = array();
1281         $options['redirection'] = 5;
1282
1283         if ( false == $file_path )
1284                 $options['method'] = 'HEAD';
1285         else
1286                 $options['method'] = 'GET';
1287
1288         $response = wp_remote_request($url, $options);
1289
1290         if ( is_wp_error( $response ) )
1291                 return false;
1292
1293         $headers = wp_remote_retrieve_headers( $response );
1294         $headers['response'] = $response['response']['code'];
1295
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 );
1299         }
1300
1301         if ( false == $file_path )
1302                 return $headers;
1303
1304         // GET request - write it to the supplied filename
1305         $out_fp = fopen($file_path, 'w');
1306         if ( !$out_fp )
1307                 return $headers;
1308
1309         fwrite( $out_fp,  $response['body']);
1310         fclose($out_fp);
1311         clearstatcache();
1312
1313         return $headers;
1314 }
1315
1316 /**
1317  * Retrieve HTTP Headers from URL.
1318  *
1319  * @since 1.5.1
1320  *
1321  * @param string $url
1322  * @param bool $deprecated Not Used.
1323  * @return bool|string False on failure, headers on success.
1324  */
1325 function wp_get_http_headers( $url, $deprecated = false ) {
1326         if ( !empty( $deprecated ) )
1327                 _deprecated_argument( __FUNCTION__, '2.7' );
1328
1329         $response = wp_remote_head( $url );
1330
1331         if ( is_wp_error( $response ) )
1332                 return false;
1333
1334         return wp_remote_retrieve_headers( $response );
1335 }
1336
1337 /**
1338  * Whether today is a new day.
1339  *
1340  * @since 0.71
1341  * @uses $day Today
1342  * @uses $previousday Previous day
1343  *
1344  * @return int 1 when new day, 0 if not a new day.
1345  */
1346 function is_new_day() {
1347         global $currentday, $previousday;
1348         if ( $currentday != $previousday )
1349                 return 1;
1350         else
1351                 return 0;
1352 }
1353
1354 /**
1355  * Build URL query based on an associative and, or indexed array.
1356  *
1357  * This is a convenient function for easily building url queries. It sets the
1358  * separator to '&' and uses _http_build_query() function.
1359  *
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.
1363  *
1364  * @since 2.3.0
1365  *
1366  * @param array $data URL-encode key/value pairs.
1367  * @return string URL encoded string
1368  */
1369 function build_query( $data ) {
1370         return _http_build_query( $data, null, '&', '', false );
1371 }
1372
1373 /**
1374  * Retrieve a modified URL query string.
1375  *
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.
1378  *
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
1381  * value.
1382  *
1383  * @since 1.5.0
1384  *
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.
1389  */
1390 function add_query_arg() {
1391         $ret = '';
1392         if ( is_array( func_get_arg(0) ) ) {
1393                 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
1394                         $uri = $_SERVER['REQUEST_URI'];
1395                 else
1396                         $uri = @func_get_arg( 1 );
1397         } else {
1398                 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
1399                         $uri = $_SERVER['REQUEST_URI'];
1400                 else
1401                         $uri = @func_get_arg( 2 );
1402         }
1403
1404         if ( $frag = strstr( $uri, '#' ) )
1405                 $uri = substr( $uri, 0, -strlen( $frag ) );
1406         else
1407                 $frag = '';
1408
1409         if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
1410                 $protocol = $matches[0];
1411                 $uri = substr( $uri, strlen( $protocol ) );
1412         } else {
1413                 $protocol = '';
1414         }
1415
1416         if ( strpos( $uri, '?' ) !== false ) {
1417                 $parts = explode( '?', $uri, 2 );
1418                 if ( 1 == count( $parts ) ) {
1419                         $base = '?';
1420                         $query = $parts[0];
1421                 } else {
1422                         $base = $parts[0] . '?';
1423                         $query = $parts[1];
1424                 }
1425         } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
1426                 $base = $uri . '?';
1427                 $query = '';
1428         } else {
1429                 $base = '';
1430                 $query = $uri;
1431         }
1432
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 );
1438         } else {
1439                 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1440         }
1441
1442         foreach ( (array) $qs as $k => $v ) {
1443                 if ( $v === false )
1444                         unset( $qs[$k] );
1445         }
1446
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, '?' );
1452         return $ret;
1453 }
1454
1455 /**
1456  * Removes an item or list from the query string.
1457  *
1458  * @since 1.5.0
1459  *
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.
1463  */
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 );
1468                 return $query;
1469         }
1470         return add_query_arg( $key, false, $query );
1471 }
1472
1473 /**
1474  * Walks the array while sanitizing the contents.
1475  *
1476  * @since 0.71
1477  *
1478  * @param array $array Array to used to walk while sanitizing contents.
1479  * @return array Sanitized $array.
1480  */
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 );
1485                 } else {
1486                         $array[$k] = addslashes( $v );
1487                 }
1488         }
1489         return $array;
1490 }
1491
1492 /**
1493  * HTTP request for URI to retrieve content.
1494  *
1495  * @since 1.5.1
1496  * @uses wp_remote_get()
1497  *
1498  * @param string $uri URI/URL of web page to retrieve.
1499  * @return bool|string HTTP content. False on failure.
1500  */
1501 function wp_remote_fopen( $uri ) {
1502         $parsed_url = @parse_url( $uri );
1503
1504         if ( !$parsed_url || !is_array( $parsed_url ) )
1505                 return false;
1506
1507         $options = array();
1508         $options['timeout'] = 10;
1509
1510         $response = wp_remote_get( $uri, $options );
1511
1512         if ( is_wp_error( $response ) )
1513                 return false;
1514
1515         return $response['body'];
1516 }
1517
1518 /**
1519  * Set up the WordPress query.
1520  *
1521  * @since 2.0.0
1522  *
1523  * @param string $query_vars Default WP_Query arguments.
1524  */
1525 function wp( $query_vars = '' ) {
1526         global $wp, $wp_query, $wp_the_query;
1527         $wp->main( $query_vars );
1528
1529         if ( !isset($wp_the_query) )
1530                 $wp_the_query = $wp_query;
1531 }
1532
1533 /**
1534  * Retrieve the description for the HTTP status.
1535  *
1536  * @since 2.3.0
1537  *
1538  * @param int $code HTTP status code.
1539  * @return string Empty string if not found, or description if found.
1540  */
1541 function get_status_header_desc( $code ) {
1542         global $wp_header_to_desc;
1543
1544         $code = absint( $code );
1545
1546         if ( !isset( $wp_header_to_desc ) ) {
1547                 $wp_header_to_desc = array(
1548                         100 => 'Continue',
1549                         101 => 'Switching Protocols',
1550                         102 => 'Processing',
1551
1552                         200 => 'OK',
1553                         201 => 'Created',
1554                         202 => 'Accepted',
1555                         203 => 'Non-Authoritative Information',
1556                         204 => 'No Content',
1557                         205 => 'Reset Content',
1558                         206 => 'Partial Content',
1559                         207 => 'Multi-Status',
1560                         226 => 'IM Used',
1561
1562                         300 => 'Multiple Choices',
1563                         301 => 'Moved Permanently',
1564                         302 => 'Found',
1565                         303 => 'See Other',
1566                         304 => 'Not Modified',
1567                         305 => 'Use Proxy',
1568                         306 => 'Reserved',
1569                         307 => 'Temporary Redirect',
1570
1571                         400 => 'Bad Request',
1572                         401 => 'Unauthorized',
1573                         402 => 'Payment Required',
1574                         403 => 'Forbidden',
1575                         404 => 'Not Found',
1576                         405 => 'Method Not Allowed',
1577                         406 => 'Not Acceptable',
1578                         407 => 'Proxy Authentication Required',
1579                         408 => 'Request Timeout',
1580                         409 => 'Conflict',
1581                         410 => 'Gone',
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',
1590                         423 => 'Locked',
1591                         424 => 'Failed Dependency',
1592                         426 => 'Upgrade Required',
1593
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'
1603                 );
1604         }
1605
1606         if ( isset( $wp_header_to_desc[$code] ) )
1607                 return $wp_header_to_desc[$code];
1608         else
1609                 return '';
1610 }
1611
1612 /**
1613  * Set HTTP status header.
1614  *
1615  * @since 2.0.0
1616  * @uses apply_filters() Calls 'status_header' on status header string, HTTP
1617  *              HTTP code, HTTP code description, and protocol string as separate
1618  *              parameters.
1619  *
1620  * @param int $header HTTP status code
1621  * @return unknown
1622  */
1623 function status_header( $header ) {
1624         $text = get_status_header_desc( $header );
1625
1626         if ( empty( $text ) )
1627                 return false;
1628
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 );
1635
1636         return @header( $status_header, true, $header );
1637 }
1638
1639 /**
1640  * Gets the header information to prevent caching.
1641  *
1642  * The several different headers cover the different ways cache prevention is handled
1643  * by different browsers
1644  *
1645  * @since 2.8.0
1646  *
1647  * @uses apply_filters()
1648  * @return array The associative array of header names and field values.
1649  */
1650 function wp_get_nocache_headers() {
1651         $headers = array(
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',
1656         );
1657
1658         if ( function_exists('apply_filters') ) {
1659                 $headers = (array) apply_filters('nocache_headers', $headers);
1660         }
1661         return $headers;
1662 }
1663
1664 /**
1665  * Sets the headers to prevent caching for the different browsers.
1666  *
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.
1669  *
1670  * @since 2.0.0
1671  * @uses wp_get_nocache_headers()
1672  */
1673 function nocache_headers() {
1674         $headers = wp_get_nocache_headers();
1675         foreach( $headers as $name => $field_value )
1676                 @header("{$name}: {$field_value}");
1677 }
1678
1679 /**
1680  * Set the headers for caching for 10 days with JavaScript content type.
1681  *
1682  * @since 2.1.0
1683  */
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" );
1689 }
1690
1691 /**
1692  * Retrieve the number of database queries during the WordPress execution.
1693  *
1694  * @since 2.0.0
1695  *
1696  * @return int Number of database queries
1697  */
1698 function get_num_queries() {
1699         global $wpdb;
1700         return $wpdb->num_queries;
1701 }
1702
1703 /**
1704  * Whether input is yes or no. Must be 'y' to be true.
1705  *
1706  * @since 1.0.0
1707  *
1708  * @param string $yn Character string containing either 'y' or 'n'
1709  * @return bool True if yes, false on anything else
1710  */
1711 function bool_from_yn( $yn ) {
1712         return ( strtolower( $yn ) == 'y' );
1713 }
1714
1715 /**
1716  * Loads the feed template from the use of an action hook.
1717  *
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.
1720  *
1721  * It is better to only have one hook for each feed.
1722  *
1723  * @since 2.1.0
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.
1726  */
1727 function do_feed() {
1728         global $wp_query;
1729
1730         $feed = get_query_var( 'feed' );
1731
1732         // Remove the pad, if present.
1733         $feed = preg_replace( '/^_+/', '', $feed );
1734
1735         if ( $feed == '' || $feed == 'feed' )
1736                 $feed = get_default_feed();
1737
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 ) );
1742         }
1743
1744         do_action( $hook, $wp_query->is_comment_feed );
1745 }
1746
1747 /**
1748  * Load the RDF RSS 0.91 Feed template.
1749  *
1750  * @since 2.1.0
1751  */
1752 function do_feed_rdf() {
1753         load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1754 }
1755
1756 /**
1757  * Load the RSS 1.0 Feed Template
1758  *
1759  * @since 2.1.0
1760  */
1761 function do_feed_rss() {
1762         load_template( ABSPATH . WPINC . '/feed-rss.php' );
1763 }
1764
1765 /**
1766  * Load either the RSS2 comment feed or the RSS2 posts feed.
1767  *
1768  * @since 2.1.0
1769  *
1770  * @param bool $for_comments True for the comment feed, false for normal feed.
1771  */
1772 function do_feed_rss2( $for_comments ) {
1773         if ( $for_comments )
1774                 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1775         else
1776                 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1777 }
1778
1779 /**
1780  * Load either Atom comment feed or Atom posts feed.
1781  *
1782  * @since 2.1.0
1783  *
1784  * @param bool $for_comments True for the comment feed, false for normal feed.
1785  */
1786 function do_feed_atom( $for_comments ) {
1787         if ($for_comments)
1788                 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1789         else
1790                 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1791 }
1792
1793 /**
1794  * Display the robot.txt file content.
1795  *
1796  * The echo content should be with usage of the permalinks or for creating the
1797  * robot.txt file.
1798  *
1799  * @since 2.1.0
1800  * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
1801  */
1802 function do_robots() {
1803         header( 'Content-Type: text/plain; charset=utf-8' );
1804
1805         do_action( 'do_robotstxt' );
1806
1807         $output = '';
1808         $public = get_option( 'blog_public' );
1809         if ( '0' ==  $public ) {
1810                 $output .= "User-agent: *\n";
1811                 $output .= "Disallow: /\n";
1812         } else {
1813                 $output .= "User-agent: *\n";
1814                 $output .= "Disallow:\n";
1815         }
1816
1817         echo apply_filters('robots_txt', $output, $public);
1818 }
1819
1820 /**
1821  * Test whether blog is already installed.
1822  *
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.
1826  *
1827  * Checks for the option siteurl for whether WordPress is installed.
1828  *
1829  * @since 2.1.0
1830  * @uses $wpdb
1831  *
1832  * @return bool Whether blog is already installed.
1833  */
1834 function is_blog_installed() {
1835         global $wpdb;
1836
1837         // Check cache first. If options table goes away and we have true cached, oh well.
1838         if ( wp_cache_get( 'is_blog_installed' ) )
1839                 return true;
1840
1841         $suppress = $wpdb->suppress_errors();
1842         if ( ! defined( 'WP_INSTALLING' ) ) {
1843                 $alloptions = wp_load_alloptions();
1844         }
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'" );
1848         else
1849                 $installed = $alloptions['siteurl'];
1850         $wpdb->suppress_errors( $suppress );
1851
1852         $installed = !empty( $installed );
1853         wp_cache_set( 'is_blog_installed', $installed );
1854
1855         if ( $installed )
1856                 return true;
1857
1858         $suppress = $wpdb->suppress_errors();
1859         $tables = $wpdb->get_col('SHOW TABLES');
1860         $wpdb->suppress_errors( $suppress );
1861
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 )
1871                                 continue;
1872                         if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1873                                 continue;
1874
1875                         // If visiting repair.php, return true and let it take over.
1876                         if ( defined('WP_REPAIRING') )
1877                                 return true;
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' );
1880                         dead_db();
1881                 }
1882         }
1883
1884         wp_cache_set( 'is_blog_installed', false );
1885
1886         return false;
1887 }
1888
1889 /**
1890  * Retrieve URL with nonce added to URL query.
1891  *
1892  * @package WordPress
1893  * @subpackage Security
1894  * @since 2.0.4
1895  *
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.
1899  */
1900 function wp_nonce_url( $actionurl, $action = -1 ) {
1901         $actionurl = str_replace( '&amp;', '&', $actionurl );
1902         return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1903 }
1904
1905 /**
1906  * Retrieve or display nonce hidden field for forms.
1907  *
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.
1912  *
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
1916  * referer field.
1917  *
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
1923  * damage.
1924  *
1925  * The input name will be whatever $name value you gave. The input value will be
1926  * the nonce creation value.
1927  *
1928  * @package WordPress
1929  * @subpackage Security
1930  * @since 2.0.4
1931  *
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.
1937  */
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 ) . '" />';
1941         if ( $echo )
1942                 echo $nonce_field;
1943
1944         if ( $referer )
1945                 wp_referer_field( $echo );
1946
1947         return $nonce_field;
1948 }
1949
1950 /**
1951  * Retrieve or display referer hidden field for forms.
1952  *
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.
1955  *
1956  * @package WordPress
1957  * @subpackage Security
1958  * @since 2.0.4
1959  *
1960  * @param bool $echo Whether to echo or return the referer field.
1961  * @return string Referer field.
1962  */
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 . '" />';
1966
1967         if ( $echo )
1968                 echo $referer_field;
1969         return $referer_field;
1970 }
1971
1972 /**
1973  * Retrieve or display original referer hidden field for forms.
1974  *
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.
1978  *
1979  * @package WordPress
1980  * @subpackage Security
1981  * @since 2.0.4
1982  *
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.
1986  */
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 ) ) . '" />';
1991         if ( $echo )
1992                 echo $orig_referer_field;
1993         return $orig_referer_field;
1994 }
1995
1996 /**
1997  * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
1998  *
1999  * @package WordPress
2000  * @subpackage Security
2001  * @since 2.0.4
2002  *
2003  * @return string|bool False on failure. Referer URL on success.
2004  */
2005 function wp_get_referer() {
2006         $ref = '';
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'];
2011
2012         if ( $ref !== $_SERVER['REQUEST_URI'] )
2013                 return $ref;
2014         return false;
2015 }
2016
2017 /**
2018  * Retrieve original referer that was posted, if it exists.
2019  *
2020  * @package WordPress
2021  * @subpackage Security
2022  * @since 2.0.4
2023  *
2024  * @return string|bool False if no original referer or original referer if set.
2025  */
2026 function wp_get_original_referer() {
2027         if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
2028                 return $_REQUEST['_wp_original_http_referer'];
2029         return false;
2030 }
2031
2032 /**
2033  * Recursive directory creation based on full path.
2034  *
2035  * Will attempt to set permissions on folders.
2036  *
2037  * @since 2.0.1
2038  *
2039  * @param string $target Full path to attempt to create.
2040  * @return bool Whether the path was created. True if path already exists.
2041  */
2042 function wp_mkdir_p( $target ) {
2043         // from php.net/mkdir user contributed notes
2044         $target = str_replace( '//', '/', $target );
2045
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) )
2049                 $target = '/';
2050
2051         if ( file_exists( $target ) )
2052                 return @is_dir( $target );
2053
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 );
2059                 return true;
2060         } elseif ( is_dir( dirname( $target ) ) ) {
2061                         return false;
2062         }
2063
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 );
2067
2068         return false;
2069 }
2070
2071 /**
2072  * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
2073  *
2074  * @since 2.5.0
2075  *
2076  * @param string $path File path
2077  * @return bool True if path is absolute, false is not absolute.
2078  */
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 )
2082                 return true;
2083
2084         if ( strlen($path) == 0 || $path[0] == '.' )
2085                 return false;
2086
2087         // windows allows absolute paths like this
2088         if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
2089                 return true;
2090
2091         // a path starting with / or \ is absolute; anything else is relative
2092         return (bool) preg_match('#^[/\\\\]#', $path);
2093 }
2094
2095 /**
2096  * Join two filesystem paths together (e.g. 'give me $path relative to $base').
2097  *
2098  * If the $path is absolute, then it the full path is returned.
2099  *
2100  * @since 2.5.0
2101  *
2102  * @param string $base
2103  * @param string $path
2104  * @return string The path with the base or absolute path.
2105  */
2106 function path_join( $base, $path ) {
2107         if ( path_is_absolute($path) )
2108                 return $path;
2109
2110         return rtrim($base, '/') . '/' . ltrim($path, '/');
2111 }
2112
2113 /**
2114  * Get an array containing the current upload directory's path and url.
2115  *
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.
2120  *
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.
2123  *
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.
2127  *
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.
2131  *
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.
2139  *
2140  * @since 2.0.0
2141  * @uses apply_filters() Calls 'upload_dir' on returned array.
2142  *
2143  * @param string $time Optional. Time formatted in 'yyyy/mm'.
2144  * @return array See above for description.
2145  */
2146 function wp_upload_dir( $time = null ) {
2147         global $switched;
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';
2154         } else {
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 );
2161                 }
2162         }
2163
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';
2167                 else
2168                         $url = trailingslashit( $siteurl ) . $upload_path;
2169         }
2170
2171         if ( defined('UPLOADS') && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
2172                 $dir = ABSPATH . UPLOADS;
2173                 $url = trailingslashit( $siteurl ) . UPLOADS;
2174         }
2175
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 );
2180         }
2181
2182         $bdir = $dir;
2183         $burl = $url;
2184
2185         $subdir = '';
2186         if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
2187                 // Generate the yearly and monthly dirs
2188                 if ( !$time )
2189                         $time = current_time( 'mysql' );
2190                 $y = substr( $time, 0, 4 );
2191                 $m = substr( $time, 5, 2 );
2192                 $subdir = "/$y/$m";
2193         }
2194
2195         $dir .= $subdir;
2196         $url .= $subdir;
2197
2198         $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
2199
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 );
2204         }
2205
2206         return $uploads;
2207 }
2208
2209 /**
2210  * Get a filename that is sanitized and unique for the given directory.
2211  *
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
2214  * unique.
2215  *
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.
2218  *
2219  * @since 2.5.0
2220  *
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.
2225  */
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);
2229
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);
2234
2235         // edge case: if file is named '.ext', treat as an empty name
2236         if ( $name === $ext )
2237                 $name = '';
2238
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 );
2242         } else {
2243                 $number = '';
2244
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 );
2249
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;
2256                         }
2257                         return $filename2;
2258                 }
2259
2260                 while ( file_exists( $dir . "/$filename" ) ) {
2261                         if ( '' == "$number$ext" )
2262                                 $filename = $filename . ++$number . $ext;
2263                         else
2264                                 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
2265                 }
2266         }
2267
2268         return $filename;
2269 }
2270
2271 /**
2272  * Create a file in the upload folder with given content.
2273  *
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.
2277  *
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
2282  * folder.
2283  *
2284  * The permissions will be set on the new file automatically by this function.
2285  *
2286  * @since 2.0.0
2287  *
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'.
2292  * @return array
2293  */
2294 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
2295         if ( !empty( $deprecated ) )
2296                 _deprecated_argument( __FUNCTION__, '2.0' );
2297
2298         if ( empty( $name ) )
2299                 return array( 'error' => __( 'Empty filename' ) );
2300
2301         $wp_filetype = wp_check_filetype( $name );
2302         if ( !$wp_filetype['ext'] )
2303                 return array( 'error' => __( 'Invalid file type' ) );
2304
2305         $upload = wp_upload_dir( $time );
2306
2307         if ( $upload['error'] !== false )
2308                 return $upload;
2309
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;
2313                 return $upload;
2314         }
2315
2316         $filename = wp_unique_filename( $upload['path'], $name );
2317
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 );
2322         }
2323
2324         $ifp = @ fopen( $new_file, 'wb' );
2325         if ( ! $ifp )
2326                 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
2327
2328         @fwrite( $ifp, $bits );
2329         fclose( $ifp );
2330         clearstatcache();
2331
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 );
2337         clearstatcache();
2338
2339         // Compute the URL
2340         $url = $upload['url'] . "/$filename";
2341
2342         return array( 'file' => $new_file, 'url' => $url, 'error' => false );
2343 }
2344
2345 /**
2346  * Retrieve the file type based on the extension name.
2347  *
2348  * @package WordPress
2349  * @since 2.5.0
2350  * @uses apply_filters() Calls 'ext2type' hook on default supported types.
2351  *
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.
2354  */
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' ),
2365         ));
2366         foreach ( $ext2type as $type => $exts )
2367                 if ( in_array( $ext, $exts ) )
2368                         return $type;
2369 }
2370
2371 /**
2372  * Retrieve the file type from the file name.
2373  *
2374  * You can optionally define the mime array, if needed.
2375  *
2376  * @since 2.0.4
2377  *
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.
2381  */
2382 function wp_check_filetype( $filename, $mimes = null ) {
2383         if ( empty($mimes) )
2384                 $mimes = get_allowed_mime_types();
2385         $type = false;
2386         $ext = false;
2387
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];
2393                         break;
2394                 }
2395         }
2396
2397         return compact( 'ext', 'type' );
2398 }
2399
2400 /**
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.
2403  *
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.
2406  *
2407  * Currently this function only supports validating images known to getimagesize().
2408  *
2409  * @since 3.0.0
2410  *
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
2415  */
2416 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
2417
2418         $proper_filename = false;
2419
2420         // Do basic extension validation and MIME mapping
2421         $wp_filetype = wp_check_filetype( $filename, $mimes );
2422         extract( $wp_filetype );
2423
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' );
2427
2428         // We're able to validate images using GD
2429         if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
2430
2431                 // Attempt to figure out what type of image it actually is
2432                 $imgstats = @getimagesize( $file );
2433
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',
2444                         ) );
2445
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 );
2452
2453                                 if ( $new_filename != $filename )
2454                                         $proper_filename = $new_filename; // Mark that it changed
2455
2456                                 // Redefine the extension / MIME
2457                                 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
2458                                 extract( $wp_filetype );
2459                         }
2460                 }
2461         }
2462
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 );
2466 }
2467
2468 /**
2469  * Retrieve list of allowed mime types and file extensions.
2470  *
2471  * @since 2.8.6
2472  *
2473  * @return array Array of mime types keyed by the file extension regex corresponding to those types.
2474  */
2475 function get_allowed_mime_types() {
2476         static $mimes = false;
2477
2478         if ( !$mimes ) {
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',
2539                 ) );
2540         }
2541
2542         return $mimes;
2543 }
2544
2545 /**
2546  * Retrieve nonce action "Are you sure" message.
2547  *
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.
2552  *
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).
2560  *
2561  * @package WordPress
2562  * @subpackage Security
2563  * @since 2.0.4
2564  *
2565  * @param string $action Nonce action.
2566  * @return string Are you sure message.
2567  */
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];
2572
2573                 $trans = array();
2574                 $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
2575
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: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
2578                 $trans['update']['category']   = array( __( 'Your attempt to edit this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
2579
2580                 $trans['delete']['comment']    = array( __( 'Your attempt to delete this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
2581                 $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
2582                 $trans['approve']['comment']   = array( __( 'Your attempt to approve this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
2583                 $trans['update']['comment']    = array( __( 'Your attempt to edit this comment: &#8220;%s&#8221; 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 );
2586
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: &#8220;%s&#8221; has failed.' ), 'use_id' );
2589                 $trans['update']['bookmark']   = array( __( 'Your attempt to edit this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
2590                 $trans['bulk']['bookmarks']    = array( __( 'Your attempt to bulk modify links has failed.' ), false );
2591
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: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
2594                 $trans['update']['page']       = array( __( 'Your attempt to edit this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
2595
2596                 $trans['edit']['plugin']       = array( __( 'Your attempt to edit this plugin file: &#8220;%s&#8221; has failed.' ), 'use_id' );
2597                 $trans['activate']['plugin']   = array( __( 'Your attempt to activate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
2598                 $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
2599                 $trans['upgrade']['plugin']    = array( __( 'Your attempt to update this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
2600
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: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
2603                 $trans['update']['post']       = array( __( 'Your attempt to edit this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
2604
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: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
2609                 $trans['update']['profile']    = array( __( 'Your attempt to modify the profile for: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
2610
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: &#8220;%s&#8221; has failed.' ), 'use_id' );
2614                 $trans['edit']['theme']        = array( __( 'Your attempt to edit this theme file: &#8220;%s&#8221; has failed.' ), 'use_id' );
2615                 $trans['switch']['theme']      = array( __( 'Your attempt to switch to this theme: &#8220;%s&#8221; has failed.' ), 'use_id' );
2616
2617                 $trans['log']['out']           = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
2618
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 );
2628                                         else
2629                                                 $object = call_user_func( $lookup, $object );
2630                                 }
2631                                 return sprintf( $trans[$verb][$noun][0], esc_html($object) );
2632                         } else {
2633                                 return $trans[$verb][$noun][0];
2634                         }
2635                 }
2636
2637                 return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), isset($matches[4]) ? $matches[4] : '' );
2638         } else {
2639                 return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
2640         }
2641 }
2642
2643 /**
2644  * Display "Are You Sure" message to confirm the action being taken.
2645  *
2646  * If the action has the nonce explain message, then it will be displayed along
2647  * with the "Are you sure?" message.
2648  *
2649  * @package WordPress
2650  * @subpackage Security
2651  * @since 2.0.4
2652  *
2653  * @param string $action The nonce action.
2654  */
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>";
2662
2663         wp_die( $html, $title, array('response' => 403) );
2664 }
2665
2666
2667 /**
2668  * Kill WordPress execution and display HTML message with error message.
2669  *
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.
2675  *
2676  * @since 2.0.4
2677  *
2678  * @param string $message Error message.
2679  * @param string $title Error title.
2680  * @param string|array $args Optional arguements to control behaviour.
2681  */
2682 function wp_die( $message, $title = '', $args = array() ) {
2683         if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2684                 die('-1');
2685
2686         if ( function_exists( 'apply_filters' ) ) {
2687                 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
2688         } else {
2689                 $function = '_default_wp_die_handler';
2690         }
2691
2692         call_user_func( $function, $message, $title, $args );
2693 }
2694
2695 /**
2696  * Kill WordPress execution and display HTML message with error message.
2697  *
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
2700  *
2701  * @since 3.0.0
2702  * @access private
2703  *
2704  * @param string $message Error message.
2705  * @param string $title Error title.
2706  * @param string|array $args Optional arguements to control behaviour.
2707  */
2708 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
2709         $defaults = array( 'response' => 500 );
2710         $r = wp_parse_args($args, $defaults);
2711
2712         $have_gettext = function_exists('__');
2713
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'];
2719                 }
2720                 $errors = $message->get_error_messages();
2721                 switch ( count( $errors ) ) :
2722                 case 0 :
2723                         $message = '';
2724                         break;
2725                 case 1 :
2726                         $message = "<p>{$errors[0]}</p>";
2727                         break;
2728                 default :
2729                         $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
2730                         break;
2731                 endswitch;
2732         } elseif ( is_string( $message ) ) {
2733                 $message = "<p>$message</p>";
2734         }
2735
2736         if ( isset( $r['back_link'] ) && $r['back_link'] ) {
2737                 $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
2738                 $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>";
2739         }
2740
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 )
2746                 $admin_dir = '';
2747         else
2748                 $admin_dir = 'wp-admin/';
2749
2750         if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
2751         if ( !headers_sent() ) {
2752                 status_header( $r['response'] );
2753                 nocache_headers();
2754                 header( 'Content-Type: text/html; charset=utf-8' );
2755         }
2756
2757         if ( empty($title) )
2758                 $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
2759
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';
2765 ?>
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'"; ?>>
2769 <head>
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" />
2773 <?php
2774 if ( 'rtl' == $text_direction ) : ?>
2775         <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
2776 <?php endif; ?>
2777 </head>
2778 <body id="error-page">
2779 <?php endif; ?>
2780         <?php echo $message; ?>
2781 </body>
2782 </html>
2783 <?php
2784         die();
2785 }
2786
2787 /**
2788  * Retrieve the WordPress home page URL.
2789  *
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.
2793  *
2794  * @access private
2795  * @package WordPress
2796  * @since 2.2.0
2797  *
2798  * @param string $url URL for the home location
2799  * @return string Homepage location.
2800  */
2801 function _config_wp_home( $url = '' ) {
2802         if ( defined( 'WP_HOME' ) )
2803                 return WP_HOME;
2804         return $url;
2805 }
2806
2807 /**
2808  * Retrieve the WordPress site URL.
2809  *
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.
2813  *
2814  * @access private
2815  * @package WordPress
2816  * @since 2.2.0
2817  *
2818  * @param string $url URL to set the WordPress site location.
2819  * @return string The WordPress Site URL
2820  */
2821 function _config_wp_siteurl( $url = '' ) {
2822         if ( defined( 'WP_SITEURL' ) )
2823                 return WP_SITEURL;
2824         return $url;
2825 }
2826
2827 /**
2828  * Set the localized direction for MCE plugin.
2829  *
2830  * Will only set the direction to 'rtl', if the WordPress locale has the text
2831  * direction set to 'rtl'.
2832  *
2833  * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
2834  * keys. These keys are then returned in the $input array.
2835  *
2836  * @access private
2837  * @package WordPress
2838  * @subpackage MCE
2839  * @since 2.1.0
2840  *
2841  * @param array $input MCE plugin array.
2842  * @return array Direction set for 'rtl', if needed by locale.
2843  */
2844 function _mce_set_direction( $input ) {
2845         if ( is_rtl() ) {
2846                 $input['directionality'] = 'rtl';
2847                 $input['plugins'] .= ',directionality';
2848                 $input['theme_advanced_buttons1'] .= ',ltr';
2849         }
2850
2851         return $input;
2852 }
2853
2854
2855 /**
2856  * Convert smiley code to the icon graphic file equivalent.
2857  *
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.
2860  *
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
2863  * image file.
2864  *
2865  * The $wp_smiliessearch global is for the regular expression and is set each
2866  * time the function is called.
2867  *
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
2870  * available.
2871  *
2872  * @global array $wpsmiliestrans
2873  * @global array $wp_smiliessearch
2874  * @since 2.2.0
2875  */
2876 function smilies_init() {
2877         global $wpsmiliestrans, $wp_smiliessearch;
2878
2879         // don't bother setting up smilies if they are disabled
2880         if ( !get_option( 'use_smilies' ) )
2881                 return;
2882
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',
2929                 );
2930         }
2931
2932         if (count($wpsmiliestrans) == 0) {
2933                 return;
2934         }
2935
2936         /*
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
2940          */
2941         krsort($wpsmiliestrans);
2942
2943         $wp_smiliessearch = '/(?:\s|^)';
2944
2945         $subchar = '';
2946         foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
2947                 $firstchar = substr($smiley, 0, 1);
2948                 $rest = substr($smiley, 1);
2949
2950                 // new subpattern?
2951                 if ($firstchar != $subchar) {
2952                         if ($subchar != '') {
2953                                 $wp_smiliessearch .= ')|(?:\s|^)';
2954                         }
2955                         $subchar = $firstchar;
2956                         $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
2957                 } else {
2958                         $wp_smiliessearch .= '|';
2959                 }
2960                 $wp_smiliessearch .= preg_quote($rest, '/');
2961         }
2962
2963         $wp_smiliessearch .= ')(?:\s|$)/m';
2964 }
2965
2966 /**
2967  * Merge user defined arguments into defaults array.
2968  *
2969  * This function is used throughout WordPress to allow for both string or array
2970  * to be merged into another array.
2971  *
2972  * @since 2.2.0
2973  *
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.
2977  */
2978 function wp_parse_args( $args, $defaults = '' ) {
2979         if ( is_object( $args ) )
2980                 $r = get_object_vars( $args );
2981         elseif ( is_array( $args ) )
2982                 $r =& $args;
2983         else
2984                 wp_parse_str( $args, $r );
2985
2986         if ( is_array( $defaults ) )
2987                 return array_merge( $defaults, $r );
2988         return $r;
2989 }
2990
2991 /**
2992  * Clean up an array, comma- or space-separated list of IDs
2993  *
2994  * @since 3.0.0
2995  *
2996  * @param array|string $list
2997  * @return array Sanitized array of IDs
2998  */
2999 function wp_parse_id_list( $list ) {
3000         if ( !is_array($list) )
3001                 $list = preg_split('/[\s,]+/', $list);
3002
3003         return array_unique(array_map('absint', $list));
3004 }
3005
3006 /**
3007  * Extract a slice of an array, given a list of keys
3008  *
3009  * @since 3.1.0
3010  *
3011  * @param array $array The original array
3012  * @param array $keys The list of keys
3013  * @return array The array slice
3014  */
3015 function wp_array_slice_assoc( $array, $keys ) {
3016         $slice = array();
3017         foreach ( $keys as $key )
3018                 if ( isset( $array[ $key ] ) )
3019                         $slice[ $key ] = $array[ $key ];
3020
3021         return $slice;
3022 }
3023
3024 /**
3025  * Filters a list of objects, based on a set of key => value arguments
3026  *
3027  * @since 3.0.0
3028  *
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
3035  */
3036 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
3037         if ( ! is_array( $list ) )
3038                 return array();
3039
3040         $list = wp_list_filter( $list, $args, $operator );
3041
3042         if ( $field )
3043                 $list = wp_list_pluck( $list, $field );
3044
3045         return $list;
3046 }
3047
3048 /**
3049  * Filters a list of objects, based on a set of key => value arguments
3050  *
3051  * @since 3.1.0
3052  *
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'.
3060  * @return array
3061  */
3062 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
3063         if ( ! is_array( $list ) )
3064                 return array();
3065
3066         if ( empty( $args ) )
3067                 return $list;
3068
3069         $operator = strtoupper( $operator );
3070         $count = count( $args );
3071         $filtered = array();
3072
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;
3079                 }
3080         }
3081
3082         return $filtered;
3083 }
3084
3085 /**
3086  * Pluck a certain field out of each object in a list
3087  *
3088  * @since 3.1.0
3089  *
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
3092  * @return array
3093  */
3094 function wp_list_pluck( $list, $field ) {
3095         foreach ( $list as $key => $value ) {
3096                 $value = (array) $value;
3097                 $list[ $key ] = $value[ $field ];
3098         }
3099
3100         return $list;
3101 }
3102
3103 /**
3104  * Determines if default embed handlers should be loaded.
3105  *
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.
3108  *
3109  * @since 2.9.0
3110  */
3111 function wp_maybe_load_embeds() {
3112         if ( ! apply_filters('load_default_embeds', true) )
3113                 return;
3114         require_once( ABSPATH . WPINC . '/default-embeds.php' );
3115 }
3116
3117 /**
3118  * Determines if Widgets library should be loaded.
3119  *
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.
3122  *
3123  * @since 2.2.0
3124  * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
3125  */
3126 function wp_maybe_load_widgets() {
3127         if ( ! apply_filters('load_default_widgets', true) )
3128                 return;
3129         require_once( ABSPATH . WPINC . '/default-widgets.php' );
3130         add_action( '_admin_menu', 'wp_widgets_add_menu' );
3131 }
3132
3133 /**
3134  * Append the Widgets menu to the themes main menu.
3135  *
3136  * @since 2.2.0
3137  * @uses $submenu The administration submenu list.
3138  */
3139 function wp_widgets_add_menu() {
3140         global $submenu;
3141         $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
3142         ksort( $submenu['themes.php'], SORT_NUMERIC );
3143 }
3144
3145 /**
3146  * Flush all output buffers for PHP 5.2.
3147  *
3148  * Make sure all output buffers are flushed before our singletons our destroyed.
3149  *
3150  * @since 2.2.0
3151  */
3152 function wp_ob_end_flush_all() {
3153         $levels = ob_get_level();
3154         for ($i=0; $i<$levels; $i++)
3155                 ob_end_flush();
3156 }
3157
3158 /**
3159  * Load custom DB error or display WordPress DB error.
3160  *
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.
3164  *
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
3167  * same.
3168  *
3169  * This function was backported to the the WordPress 2.3.2, but originally was
3170  * added in WordPress 2.5.0.
3171  *
3172  * @since 2.3.2
3173  * @uses $wpdb
3174  */
3175 function dead_db() {
3176         global $wpdb;
3177
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' );
3181                 die();
3182         }
3183
3184         // If installing or in the admin, provide the verbose message.
3185         if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
3186                 wp_die($wpdb->error);
3187
3188         // Otherwise, be terse.
3189         status_header( 500 );
3190         nocache_headers();
3191         header( 'Content-Type: text/html; charset=utf-8' );
3192 ?>
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(); ?>>
3195 <head>
3196 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3197         <title>Database Error</title>
3198
3199 </head>
3200 <body>
3201         <h1>Error establishing a database connection</h1>
3202 </body>
3203 </html>
3204 <?php
3205         die();
3206 }
3207
3208 /**
3209  * Converts value to nonnegative integer.
3210  *
3211  * @since 2.5.0
3212  *
3213  * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
3214  * @return int An nonnegative integer
3215  */
3216 function absint( $maybeint ) {
3217         return abs( intval( $maybeint ) );
3218 }
3219
3220 /**
3221  * Determines if the blog can be accessed over SSL.
3222  *
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.
3225  *
3226  * @since 2.5.0
3227  *
3228  * @param string $url
3229  * @return bool Whether SSL access is available
3230  */
3231 function url_is_accessable_via_ssl($url)
3232 {
3233         if (in_array('curl', get_loaded_extensions())) {
3234                 $ssl = preg_replace( '/^http:\/\//', 'https://',  $url );
3235
3236                 $ch = curl_init();
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);
3242
3243                 curl_exec($ch);
3244
3245                 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
3246                 curl_close ($ch);
3247
3248                 if ($status == 200 || $status == 401) {
3249                         return true;
3250                 }
3251         }
3252         return false;
3253 }
3254
3255 /**
3256  * Secure URL, if available or the given URL.
3257  *
3258  * @since 2.5.0
3259  *
3260  * @param string $url Complete URL path with transport.
3261  * @return string Secure or regular URL path.
3262  */
3263 function atom_service_url_filter($url)
3264 {
3265         if ( url_is_accessable_via_ssl($url) )
3266                 return preg_replace( '/^http:\/\//', 'https://',  $url );
3267         else
3268                 return $url;
3269 }
3270
3271 /**
3272  * Marks a function as deprecated and informs when it has been used.
3273  *
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
3276  * function.
3277  *
3278  * The current behavior is to trigger a user error if WP_DEBUG is true.
3279  *
3280  * This function is to be used in every function that is deprecated.
3281  *
3282  * @package WordPress
3283  * @subpackage Debug
3284  * @since 2.5.0
3285  * @access private
3286  *
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.
3291  *
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
3295  */
3296 function _deprecated_function( $function, $version, $replacement=null ) {
3297
3298         do_action( 'deprecated_function_run', $function, $replacement, $version );
3299
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 ) );
3304                 else
3305                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
3306         }
3307 }
3308
3309 /**
3310  * Marks a file as deprecated and informs when it has been used.
3311  *
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
3314  * file.
3315  *
3316  * The current behavior is to trigger a user error if WP_DEBUG is true.
3317  *
3318  * This function is to be used in every file that is deprecated.
3319  *
3320  * @package WordPress
3321  * @subpackage Debug
3322  * @since 2.5.0
3323  * @access private
3324  *
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.
3329  *
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
3334  */
3335 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
3336
3337         do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
3338
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 );
3344                 else
3345                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
3346         }
3347 }
3348 /**
3349  * Marks a function argument as deprecated and informs when it has been used.
3350  *
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.
3354  * For example:
3355  * <code>
3356  * if ( !empty($deprecated) )
3357  *      _deprecated_argument( __FUNCTION__, '3.0' );
3358  * </code>
3359  *
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
3362  * argument.
3363  *
3364  * The current behavior is to trigger a user error if WP_DEBUG is true.
3365  *
3366  * @package WordPress
3367  * @subpackage Debug
3368  * @since 3.0.0
3369  * @access private
3370  *
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.
3375  *
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.
3379  */
3380 function _deprecated_argument( $function, $version, $message = null ) {
3381
3382         do_action( 'deprecated_argument_run', $function, $message, $version );
3383
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 ) );
3388                 else
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 ) );
3390         }
3391 }
3392
3393 /**
3394  * Marks something as being incorrectly called.
3395  *
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
3398  * function.
3399  *
3400  * The current behavior is to trigger a user error if WP_DEBUG is true.
3401  *
3402  * @package WordPress
3403  * @subpackage Debug
3404  * @since 3.1.0
3405  * @access private
3406  *
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.
3410  *
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.
3414  */
3415 function _doing_it_wrong( $function, $message, $version ) {
3416
3417         do_action( 'doing_it_wrong_run', $function, $message, $version );
3418
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 ) );
3423         }
3424 }
3425
3426 /**
3427  * Is the server running earlier than 1.5.0 version of lighttpd
3428  *
3429  * @since 2.5.0
3430  *
3431  * @return bool Whether the server is running lighttpd < 1.5.0
3432  */
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' );
3437 }
3438
3439 /**
3440  * Does the specified module exist in the apache config?
3441  *
3442  * @since 2.5.0
3443  *
3444  * @param string $mod e.g. mod_rewrite
3445  * @param bool $default The default return value if the module is not found
3446  * @return bool
3447  */
3448 function apache_mod_loaded($mod, $default = false) {
3449         global $is_apache;
3450
3451         if ( !$is_apache )
3452                 return false;
3453
3454         if ( function_exists('apache_get_modules') ) {
3455                 $mods = apache_get_modules();
3456                 if ( in_array($mod, $mods) )
3457                         return true;
3458         } elseif ( function_exists('phpinfo') ) {
3459                         ob_start();
3460                         phpinfo(8);
3461                         $phpinfo = ob_get_clean();
3462                         if ( false !== strpos($phpinfo, $mod) )
3463                                 return true;
3464         }
3465         return $default;
3466 }
3467
3468 /**
3469  * Check if IIS 7 supports pretty permalinks
3470  *
3471  * @since 2.8.0
3472  *
3473  * @return bool
3474  */
3475 function iis7_supports_permalinks() {
3476         global $is_iis7;
3477
3478         $supports_permalinks = false;
3479         if ( $is_iis7 ) {
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.
3489                  */
3490                 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
3491         }
3492
3493         return apply_filters('iis7_supports_permalinks', $supports_permalinks);
3494 }
3495
3496 /**
3497  * File validates against allowed set of defined rules.
3498  *
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
3502  * files list.
3503  *
3504  * @since 1.2.0
3505  *
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.
3509  */
3510 function validate_file( $file, $allowed_files = '' ) {
3511         if ( false !== strpos( $file, '..' ))
3512                 return 1;
3513
3514         if ( false !== strpos( $file, './' ))
3515                 return 1;
3516
3517         if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
3518                 return 3;
3519
3520         if (':' == substr( $file, 1, 1 ))
3521                 return 2;
3522
3523         return 0;
3524 }
3525
3526 /**
3527  * Determine if SSL is used.
3528  *
3529  * @since 2.6.0
3530  *
3531  * @return bool True if SSL, false if not used.
3532  */
3533 function is_ssl() {
3534         if ( isset($_SERVER['HTTPS']) ) {
3535                 if ( 'on' == strtolower($_SERVER['HTTPS']) )
3536                         return true;
3537                 if ( '1' == $_SERVER['HTTPS'] )
3538                         return true;
3539         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
3540                 return true;
3541         }
3542         return false;
3543 }
3544
3545 /**
3546  * Whether SSL login should be forced.
3547  *
3548  * @since 2.6.0
3549  *
3550  * @param string|bool $force Optional.
3551  * @return bool True if forced, false if not forced.
3552  */
3553 function force_ssl_login( $force = null ) {
3554         static $forced = false;
3555
3556         if ( !is_null( $force ) ) {
3557                 $old_forced = $forced;
3558                 $forced = $force;
3559                 return $old_forced;
3560         }
3561
3562         return $forced;
3563 }
3564
3565 /**
3566  * Whether to force SSL used for the Administration Panels.
3567  *
3568  * @since 2.6.0
3569  *
3570  * @param string|bool $force
3571  * @return bool True if forced, false if not forced.
3572  */
3573 function force_ssl_admin( $force = null ) {
3574         static $forced = false;
3575
3576         if ( !is_null( $force ) ) {
3577                 $old_forced = $forced;
3578                 $forced = $force;
3579                 return $old_forced;
3580         }
3581
3582         return $forced;
3583 }
3584
3585 /**
3586  * Guess the URL for the site.
3587  *
3588  * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
3589  * directory.
3590  *
3591  * @since 2.6.0
3592  *
3593  * @return string
3594  */
3595 function wp_guess_url() {
3596         if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
3597                 $url = WP_SITEURL;
3598         } else {
3599                 $schema = is_ssl() ? 'https://' : 'http://';
3600                 $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
3601         }
3602         return rtrim($url, '/');
3603 }
3604
3605 /**
3606  * Suspend cache invalidation.
3607  *
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.
3611  *
3612  * @since 2.7.0
3613  *
3614  * @param bool $suspend Whether to suspend or enable cache invalidation
3615  * @return bool The current suspend setting
3616  */
3617 function wp_suspend_cache_invalidation($suspend = true) {
3618         global $_wp_suspend_cache_invalidation;
3619
3620         $current_suspend = $_wp_suspend_cache_invalidation;
3621         $_wp_suspend_cache_invalidation = $suspend;
3622         return $current_suspend;
3623 }
3624
3625 /**
3626  * Retrieve site option value based on name of option.
3627  *
3628  * @see get_option()
3629  * @package WordPress
3630  * @subpackage Option
3631  * @since 2.8.0
3632  *
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
3637  *      the option value.
3638  *
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.
3643  */
3644 function get_site_option( $option, $default = false, $use_cache = true ) {
3645         global $wpdb;
3646
3647         // Allow plugins to short-circuit site options.
3648         $pre = apply_filters( 'pre_site_option_' . $option, false );
3649         if ( false !== $pre )
3650                 return $pre;
3651
3652         if ( !is_multisite() ) {
3653                 $value = get_option($option, $default);
3654         } else {
3655                 $cache_key = "{$wpdb->siteid}:$option";
3656                 if ( $use_cache )
3657                         $value = wp_cache_get($cache_key, 'site-options');
3658
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 ) );
3661
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;
3665                         else
3666                                 $value = $default;
3667
3668                         $value = maybe_unserialize( $value );
3669
3670                         wp_cache_set( $cache_key, $value, 'site-options' );
3671                 }
3672         }
3673
3674         return apply_filters( 'site_option_' . $option, $value );
3675 }
3676
3677 /**
3678  * Add a new site option.
3679  *
3680  * @see add_option()
3681  * @package WordPress
3682  * @subpackage Option
3683  * @since 2.8.0
3684  *
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.
3688  *
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.
3692  */
3693 function add_site_option( $option, $value ) {
3694         global $wpdb;
3695
3696         $value = apply_filters( 'pre_add_site_option_' . $option, $value );
3697
3698         if ( !is_multisite() ) {
3699                 $result = add_option( $option, $value );
3700         } else {
3701                 $cache_key = "{$wpdb->siteid}:$option";
3702
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 );
3705
3706                 $value = sanitize_option( $option, $value );
3707                 wp_cache_set( $cache_key, $value, 'site-options' );
3708
3709                 $_value = $value;
3710                 $value = maybe_serialize($value);
3711                 $result = $wpdb->insert( $wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $value ) );
3712                 $value = $_value;
3713         }
3714
3715         do_action( "add_site_option_{$option}", $option, $value );
3716         do_action( "add_site_option", $option, $value );
3717
3718         return $result;
3719 }
3720
3721 /**
3722  * Removes site option by name.
3723  *
3724  * @see delete_option()
3725  * @package WordPress
3726  * @subpackage Option
3727  * @since 2.8.0
3728  *
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'
3731  *      hooks on success.
3732  *
3733  * @param string $option Name of option to remove. Expected to not be SQL-escaped.
3734  * @return bool True, if succeed. False, if failure.
3735  */
3736 function delete_site_option( $option ) {
3737         global $wpdb;
3738
3739         // ms_protect_special_option( $option ); @todo
3740
3741         do_action( 'pre_delete_site_option_' . $option );
3742
3743         if ( !is_multisite() ) {
3744                 $result = delete_option( $option );
3745         } else {
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 )
3748                         return false;
3749                 $cache_key = "{$wpdb->siteid}:$option";
3750                 wp_cache_delete( $cache_key, 'site-options' );
3751
3752                 $result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
3753         }
3754
3755         if ( $result ) {
3756                 do_action( "delete_site_option_{$option}", $option );
3757                 do_action( "delete_site_option", $option );
3758                 return true;
3759         }
3760         return false;
3761 }
3762
3763 /**
3764  * Update the value of a site option that was already added.
3765  *
3766  * @see update_option()
3767  * @since 2.8.0
3768  * @package WordPress
3769  * @subpackage Option
3770  *
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.
3774  *
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.
3778  */
3779 function update_site_option( $option, $value ) {
3780         global $wpdb;
3781
3782         $oldvalue = get_site_option( $option );
3783         $value = apply_filters( 'pre_update_site_option_' . $option, $value, $oldvalue );
3784
3785         if ( $value === $oldvalue )
3786                 return false;
3787
3788         if ( !is_multisite() ) {
3789                 $result = update_option( $option, $value );
3790         } else {
3791                 $cache_key = "{$wpdb->siteid}:$option";
3792
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' );
3797
3798                 $_value = $value;
3799                 $value = maybe_serialize( $value );
3800                 $result = $wpdb->update( $wpdb->sitemeta, array( 'meta_value' => $value ), array( 'site_id' => $wpdb->siteid, 'meta_key' => $option ) );
3801                 $value = $_value;
3802         }
3803
3804         if ( $result ) {
3805                 do_action( "update_site_option_{$option}", $option, $value );
3806                 do_action( "update_site_option", $option, $value );
3807                 return true;
3808         }
3809         return false;
3810 }
3811
3812 /**
3813  * Delete a site transient
3814  *
3815  * @since 2.9.0
3816  * @package WordPress
3817  * @subpackage Transient
3818  *
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.
3821  *
3822  * @param string $transient Transient name. Expected to not be SQL-escaped.
3823  * @return bool True if successful, false otherwise
3824  */
3825 function delete_site_transient( $transient ) {
3826         global $_wp_using_ext_object_cache;
3827
3828         do_action( 'delete_site_transient_' . $transient, $transient );
3829         if ( $_wp_using_ext_object_cache ) {
3830                 $result = wp_cache_delete( $transient, 'site-transient' );
3831         } else {
3832                 $option_timeout = '_site_transient_timeout_' . $transient;
3833                 $option = '_site_transient_' . $transient;
3834                 $result = delete_site_option( $option );
3835                 if ( $result )
3836                         delete_site_option( $option_timeout );
3837         }
3838         if ( $result )
3839                 do_action( 'deleted_site_transient', $transient );
3840         return $result;
3841 }
3842
3843 /**
3844  * Get the value of a site transient
3845  *
3846  * If the transient does not exist or does not have a value, then the return value
3847  * will be false.
3848  *
3849  * @see get_transient()
3850  * @since 2.9.0
3851  * @package WordPress
3852  * @subpackage Transient
3853  *
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.
3859  *
3860  * @param string $transient Transient name. Expected to not be SQL-escaped.
3861  * @return mixed Value of transient
3862  */
3863 function get_site_transient( $transient ) {
3864         global $_wp_using_ext_object_cache;
3865
3866         $pre = apply_filters( 'pre_site_transient_' . $transient, false );
3867         if ( false !== $pre )
3868                 return $pre;
3869
3870         if ( $_wp_using_ext_object_cache ) {
3871                 $value = wp_cache_get( $transient, 'site-transient' );
3872         } else {
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 );
3882                                 return false;
3883                         }
3884                 }
3885
3886                 $value = get_site_option( $transient_option );
3887         }
3888
3889         return apply_filters( 'site_transient_' . $transient, $value );
3890 }
3891
3892 /**
3893  * Set/update the value of a site transient
3894  *
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.
3897  *
3898  * @see set_transient()
3899  * @since 2.9.0
3900  * @package WordPress
3901  * @subpackage Transient
3902  *
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.
3906  *
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.
3911  */
3912 function set_site_transient( $transient, $value, $expiration = 0 ) {
3913         global $_wp_using_ext_object_cache;
3914
3915         $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
3916
3917         if ( $_wp_using_ext_object_cache ) {
3918                 $result = wp_cache_set( $transient, $value, 'site-transient', $expiration );
3919         } else {
3920                 $transient_timeout = '_site_transient_timeout_' . $transient;
3921                 $transient = '_site_transient_' . $transient;
3922                 if ( false === get_site_option( $transient ) ) {
3923                         if ( $expiration )
3924                                 add_site_option( $transient_timeout, time() + $expiration );
3925                         $result = add_site_option( $transient, $value );
3926                 } else {
3927                         if ( $expiration )
3928                                 update_site_option( $transient_timeout, time() + $expiration );
3929                         $result = update_site_option( $transient, $value );
3930                 }
3931         }
3932         if ( $result ) {
3933                 do_action( 'set_site_transient_' . $transient );
3934                 do_action( 'setted_site_transient', $transient );
3935         }
3936         return $result;
3937 }
3938
3939 /**
3940  * is main site
3941  *
3942  *
3943  * @since 3.0.0
3944  * @package WordPress
3945  *
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
3948  */
3949 function is_main_site( $blog_id = '' ) {
3950         global $current_site, $current_blog;
3951
3952         if ( !is_multisite() )
3953                 return true;
3954
3955         if ( !$blog_id )
3956                 $blog_id = $current_blog->blog_id;
3957
3958         return $blog_id == $current_site->blog_id;
3959 }
3960
3961 /**
3962  * Whether global terms are enabled.
3963  *
3964  *
3965  * @since 3.0.0
3966  * @package WordPress
3967  *
3968  * @return bool True if multisite and global terms enabled
3969  */
3970 function global_terms_enabled() {
3971         if ( ! is_multisite() )
3972                 return false;
3973
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;
3979                 else
3980                         $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
3981         }
3982         return $global_terms;
3983 }
3984
3985 /**
3986  * gmt_offset modification for smart timezone handling
3987  *
3988  * Overrides the gmt_offset option if we have a timezone_string available
3989  *
3990  * @since 2.8.0
3991  *
3992  * @return float|bool
3993  */
3994 function wp_timezone_override_offset() {
3995         if ( !wp_timezone_supported() ) {
3996                 return false;
3997         }
3998         if ( !$timezone_string = get_option( 'timezone_string' ) ) {
3999                 return false;
4000         }
4001
4002         $timezone_object = timezone_open( $timezone_string );
4003         $datetime_object = date_create();
4004         if ( false === $timezone_object || false === $datetime_object ) {
4005                 return false;
4006         }
4007         return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
4008 }
4009
4010 /**
4011  * Check for PHP timezone support
4012  *
4013  * @since 2.9.0
4014  *
4015  * @return bool
4016  */
4017 function wp_timezone_supported() {
4018         $support = false;
4019         if (
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' )
4025         ) {
4026                 $support = true;
4027         }
4028         return apply_filters( 'timezone_support', $support );
4029 }
4030
4031 /**
4032  * {@internal Missing Short Description}}
4033  *
4034  * @since 2.9.0
4035  *
4036  * @param unknown_type $a
4037  * @param unknown_type $b
4038  * @return int
4039  */
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'] ) );
4046                 }
4047                 if ( 'UTC' === $a['city'] ) {
4048                         if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
4049                                 return 1;
4050                         }
4051                         return -1;
4052                 }
4053                 if ( 'UTC' === $b['city'] ) {
4054                         if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
4055                                 return -1;
4056                         }
4057                         return 1;
4058                 }
4059                 return strnatcasecmp( $a['city'], $b['city'] );
4060         }
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'] );
4064                 }
4065                 return strnatcasecmp( $a['t_city'], $b['t_city'] );
4066         } else {
4067                 // Force Etc to the bottom of the list
4068                 if ( 'Etc' === $a['continent'] ) {
4069                         return 1;
4070                 }
4071                 if ( 'Etc' === $b['continent'] ) {
4072                         return -1;
4073                 }
4074                 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
4075         }
4076 }
4077
4078 /**
4079  * Gives a nicely formatted list of timezone strings // temporary! Not in final
4080  *
4081  * @since 2.9.0
4082  *
4083  * @param string $selected_zone Selected Zone
4084  * @return string
4085  */
4086 function wp_timezone_choice( $selected_zone ) {
4087         static $mo_loaded = false;
4088
4089         $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
4090
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 );
4096                 $mo_loaded = true;
4097         }
4098
4099         $zonen = array();
4100         foreach ( timezone_identifiers_list() as $zone ) {
4101                 $zone = explode( '/', $zone );
4102                 if ( !in_array( $zone[0], $continents ) ) {
4103                         continue;
4104                 }
4105
4106                 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
4107                 $exists = array(
4108                         0 => ( isset( $zone[0] ) && $zone[0] ),
4109                         1 => ( isset( $zone[1] ) && $zone[1] ),
4110                         2 => ( isset( $zone[2] ) && $zone[2] ),
4111                 );
4112                 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
4113                 $exists[4] = ( $exists[1] && $exists[3] );
4114                 $exists[5] = ( $exists[2] && $exists[3] );
4115
4116                 $zonen[] = array(
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' ) : '' )
4123                 );
4124         }
4125         usort( $zonen, '_wp_timezone_choice_usort_callback' );
4126
4127         $structure = array();
4128
4129         if ( empty( $selected_zone ) ) {
4130                 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
4131         }
4132
4133         foreach ( $zonen as $key => $zone ) {
4134                 // Build value in an array to join later
4135                 $value = array( $zone['continent'] );
4136
4137                 if ( empty( $zone['city'] ) ) {
4138                         // It's at the continent level (generally won't happen)
4139                         $display = $zone['t_continent'];
4140                 } else {
4141                         // It's inside a continent group
4142
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 ) .'">';
4147                         }
4148
4149                         // Add the city to the value
4150                         $value[] = $zone['city'];
4151
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'];
4157                         }
4158                 }
4159
4160                 // Build the value
4161                 $value = join( '/', $value );
4162                 $selected = '';
4163                 if ( $value === $selected_zone ) {
4164                         $selected = 'selected="selected" ';
4165                 }
4166                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
4167
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>';
4171                 }
4172         }
4173
4174         // Do UTC
4175         $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
4176         $selected = '';
4177         if ( 'UTC' === $selected_zone )
4178                 $selected = 'selected="selected" ';
4179         $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
4180         $structure[] = '</optgroup>';
4181
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 ) {
4187                 if ( 0 <= $offset )
4188                         $offset_name = '+' . $offset;
4189                 else
4190                         $offset_name = (string) $offset;
4191
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;
4196                 $selected = '';
4197                 if ( $offset_value === $selected_zone )
4198                         $selected = 'selected="selected" ';
4199                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
4200
4201         }
4202         $structure[] = '</optgroup>';
4203
4204         return join( "\n", $structure );
4205 }
4206
4207 /**
4208  * Strip close comment and close php tags from file headers used by WP
4209  * See http://core.trac.wordpress.org/ticket/8497
4210  *
4211  * @since 2.8.0
4212  *
4213  * @param string $str
4214  * @return string
4215  */
4216 function _cleanup_header_comment($str) {
4217         return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
4218 }
4219
4220 /**
4221  * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
4222  *
4223  * @since 2.9.0
4224  */
4225 function wp_scheduled_delete() {
4226         global $wpdb;
4227
4228         $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
4229
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);
4231
4232         foreach ( (array) $posts_to_delete as $post ) {
4233                 $post_id = (int) $post['post_id'];
4234                 if ( !$post_id )
4235                         continue;
4236
4237                 $del_post = get_post($post_id);
4238
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');
4242                 } else {
4243                         wp_delete_post($post_id);
4244                 }
4245         }
4246
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);
4248
4249         foreach ( (array) $comments_to_delete as $comment ) {
4250                 $comment_id = (int) $comment['comment_id'];
4251                 if ( !$comment_id )
4252                         continue;
4253
4254                 $del_comment = get_comment($comment_id);
4255
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');
4259                 } else {
4260                         wp_delete_comment($comment_id);
4261                 }
4262         }
4263 }
4264
4265 /**
4266  * Retrieve metadata from a file.
4267  *
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.
4271  *
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.
4274  *
4275  * @see http://codex.wordpress.org/File_Header
4276  *
4277  * @since 2.9.0
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"
4281  */
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' );
4285
4286         // Pull only the first 8kiB of the file in.
4287         $file_data = fread( $fp, 8192 );
4288
4289         // PHP will close file handle, but we are good citizens.
4290         fclose( $fp );
4291
4292         if ( $context != '' ) {
4293                 $extra_headers = apply_filters( "extra_{$context}_headers", array() );
4294
4295                 $extra_headers = array_flip( $extra_headers );
4296                 foreach( $extra_headers as $key=>$value ) {
4297                         $extra_headers[$key] = $key;
4298                 }
4299                 $all_headers = array_merge( $extra_headers, (array) $default_headers );
4300         } else {
4301                 $all_headers = $default_headers;
4302         }
4303
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] );
4308                 else
4309                         ${$field} = '';
4310         }
4311
4312         $file_data = compact( array_keys( $all_headers ) );
4313
4314         return $file_data;
4315 }
4316
4317 /**
4318  * Used internally to tidy up the search terms
4319  *
4320  * @access private
4321  * @since 2.9.0
4322  *
4323  * @param string $t
4324  * @return string
4325  */
4326 function _search_terms_tidy($t) {
4327         return trim($t, "\"'\n\r ");
4328 }
4329
4330 /**
4331  * Returns true
4332  *
4333  * Useful for returning true to filters easily
4334  *
4335  * @since 3.0.0
4336  * @see __return_false()
4337  * @return bool true
4338  */
4339 function __return_true() {
4340         return true;
4341 }
4342
4343 /**
4344  * Returns false
4345  *
4346  * Useful for returning false to filters easily
4347  *
4348  * @since 3.0.0
4349  * @see __return_true()
4350  * @return bool false
4351  */
4352 function __return_false() {
4353         return false;
4354 }
4355
4356 /**
4357  * Returns 0
4358  *
4359  * Useful for returning 0 to filters easily
4360  *
4361  * @since 3.0.0
4362  * @see __return_zero()
4363  * @return int 0
4364  */
4365 function __return_zero() {
4366         return 0;
4367 }
4368
4369 /**
4370  * Returns an empty array
4371  *
4372  * Useful for returning an empty array to filters easily
4373  *
4374  * @since 3.0.0
4375  * @see __return_zero()
4376  * @return array Empty array
4377  */
4378 function __return_empty_array() {
4379         return array();
4380 }
4381
4382 /**
4383  * Send a HTTP header to disable content type sniffing in browsers which support it.
4384  *
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
4387  *
4388  * @since 3.0.0
4389  * @return none
4390  */
4391 function send_nosniff_header() {
4392         @header( 'X-Content-Type-Options: nosniff' );
4393 }
4394
4395 /**
4396  * Returns a MySQL expression for selecting the week number based on the start_of_week option.
4397  *
4398  * @internal
4399  * @since 3.0.0
4400  * @param string $column
4401  * @return string
4402  */
4403 function _wp_mysql_week( $column ) {
4404         switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
4405         default :
4406         case 0 :
4407                 return "WEEK( $column, 0 )";
4408         case 1 :
4409                 return "WEEK( $column, 1 )";
4410         case 2 :
4411         case 3 :
4412         case 4 :
4413         case 5 :
4414         case 6 :
4415                 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
4416         }
4417 }
4418
4419 /**
4420  * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
4421  *
4422  * @since 3.1.0
4423  * @access private
4424  *
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
4430  */
4431 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
4432         $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
4433
4434         if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
4435                 return array();
4436
4437         return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
4438 }
4439
4440 /**
4441  * Uses the "The Tortoise and the Hare" algorithm to detect loops.
4442  *
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.
4445  *
4446  * @since 3.1.0
4447  * @access private
4448  *
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
4457  */
4458 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
4459         $tortoise = $hare = $evanescent_hare = $start;
4460         $return = array();
4461
4462         // Set evanescent_hare to one past hare
4463         // Increment hare two steps
4464         while (
4465                 $tortoise
4466         &&
4467                 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
4468         &&
4469                 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
4470         ) {
4471                 if ( $_return_loop )
4472                         $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
4473
4474                 // tortoise got lapped - must be a loop
4475                 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
4476                         return $_return_loop ? $return : $tortoise;
4477
4478                 // Increment tortoise by one step
4479                 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
4480         }
4481
4482         return false;
4483 }
4484
4485 /**
4486  * Send a HTTP header to limit rendering of pages to same origin iframes.
4487  *
4488  * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
4489  *
4490  * @since 3.1.3
4491  * @return none
4492  */
4493 function send_frame_options_header() {
4494         @header( 'X-Frame-Options: SAMEORIGIN' );
4495 }
4496
4497 ?>