]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions.php
Wordpress 2.6.2-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         global $wp_locale;
27         $m = $mysqlstring;
28         if ( empty( $m ) )
29                 return false;
30
31         if( 'G' == $dateformatstring ) {
32                 return gmmktime(
33                         (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
34                         (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
35                 );
36         }
37
38         $i = mktime(
39                 (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
40                 (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
41         );
42
43         if( 'U' == $dateformatstring )
44                 return $i;
45
46         if ( -1 == $i || false == $i )
47                 $i = 0;
48
49         if ( !empty( $wp_locale->month ) && !empty( $wp_locale->weekday ) && $translate ) {
50                 $datemonth = $wp_locale->get_month( date( 'm', $i ) );
51                 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
52                 $dateweekday = $wp_locale->get_weekday( date( 'w', $i ) );
53                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
54                 $datemeridiem = $wp_locale->get_meridiem( date( 'a', $i ) );
55                 $datemeridiem_capital = $wp_locale->get_meridiem( date( 'A', $i ) );
56                 $dateformatstring = ' ' . $dateformatstring;
57                 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
58                 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
59                 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
60                 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
61                 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
62                 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
63
64                 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
65         }
66         $j = @date( $dateformatstring, $i );
67
68         /*
69         if ( !$j ) // for debug purposes
70                 echo $i." ".$mysqlstring;
71         */
72
73         return $j;
74 }
75
76 /**
77  * Retrieve the current time based on specified type.
78  *
79  * The 'mysql' type will return the time in the format for MySQL DATETIME field.
80  * The 'timestamp' type will return the current timestamp.
81  *
82  * If the $gmt is set to either '1' or 'true', then both types will use the
83  * GMT offset in the WordPress option to add the GMT offset to the time.
84  *
85  * @since 1.0.0
86  *
87  * @param string $type Either 'mysql' or 'timestamp'.
88  * @param int|bool $gmt Optional. Whether to use $gmt offset. Default is false.
89  * @return unknown
90  */
91 function current_time( $type, $gmt = 0 ) {
92         switch ( $type ) {
93                 case 'mysql':
94                         return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
95                         break;
96                 case 'timestamp':
97                         return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
98                         break;
99         }
100 }
101
102 /**
103  * Retrieve the date in localized format, based on timestamp.
104  *
105  * If the locale specifies the locale month and weekday, then the locale will
106  * take over the format for the date. If it isn't, then the date format string
107  * will be used instead.
108  *
109  * @since 0.71
110  *
111  * @param string $dateformatstring Format to display the date
112  * @param int $unixtimestamp Unix timestamp
113  * @return string The date, translated if locale specifies it.
114  */
115 function date_i18n( $dateformatstring, $unixtimestamp ) {
116         global $wp_locale;
117         $i = $unixtimestamp;
118         // Sanity check for PHP 5.1.0-
119         if ( -1 == $i )
120                 $i = false;
121         
122         if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
123                 $datemonth = $wp_locale->get_month( date( 'm', $i ) );
124                 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
125                 $dateweekday = $wp_locale->get_weekday( date( 'w', $i ) );
126                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
127                 $datemeridiem = $wp_locale->get_meridiem( date( 'a', $i ) );
128                 $datemeridiem_capital = $wp_locale->get_meridiem( date( 'A', $i ) );
129                 $dateformatstring = ' '.$dateformatstring;
130                 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
131                 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
132                 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
133                 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
134                 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
135                 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
136
137                 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
138         }
139         $j = @date( $dateformatstring, $i );
140         return $j;
141 }
142
143 /**
144  * Convert number to format based on the locale.
145  *
146  * @since 2.3.0
147  *
148  * @param mixed $number The number to convert based on locale.
149  * @param int $decimals Precision of the number of decimal places.
150  * @return string Converted number in string format.
151  */
152 function number_format_i18n( $number, $decimals = null ) {
153         global $wp_locale;
154         // let the user override the precision only
155         $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals );
156
157         return number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
158 }
159
160 /**
161  * Convert number of bytes largest unit bytes will fit into.
162  *
163  * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
164  * number of bytes to human readable number by taking the number of that unit
165  * that the bytes will go into it. Supports TB value.
166  *
167  * Please note that integers in PHP are limited to 32 bits, unless they are on
168  * 64 bit architecture, then they have 64 bit size. If you need to place the
169  * larger size then what PHP integer type will hold, then use a string. It will
170  * be converted to a double, which should always have 64 bit length.
171  *
172  * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
173  * @link http://en.wikipedia.org/wiki/Byte
174  *
175  * @since 2.3.0
176  *
177  * @param int|string $bytes Number of bytes. Note max integer size for integers.
178  * @param int $decimals Precision of number of decimal places.
179  * @return unknown
180  */
181 function size_format( $bytes, $decimals = null ) {
182         $quant = array(
183                 // ========================= Origin ====
184                 'TB' => 1099511627776,  // pow( 1024, 4)
185                 'GB' => 1073741824,     // pow( 1024, 3)
186                 'MB' => 1048576,        // pow( 1024, 2)
187                 'kB' => 1024,           // pow( 1024, 1)
188                 'B ' => 1,              // pow( 1024, 0)
189         );
190
191         foreach ( $quant as $unit => $mag )
192                 if ( doubleval($bytes) >= $mag )
193                         return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
194
195         return false;
196 }
197
198
199 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
200         $my = substr( $mysqlstring, 0, 4 );
201         $mm = substr( $mysqlstring, 8, 2 );
202         $md = substr( $mysqlstring, 5, 2 );
203         $day = mktime( 0, 0, 0, $md, $mm, $my );
204         $weekday = date( 'w', $day );
205         $i = 86400;
206         if( !is_numeric($start_of_week) )
207                 $start_of_week = get_option( 'start_of_week' );
208
209         if ( $weekday < $start_of_week )
210                 $weekday = 7 - $start_of_week - $weekday;
211
212         while ( $weekday > $start_of_week ) {
213                 $weekday = date( 'w', $day );
214                 if ( $weekday < $start_of_week )
215                         $weekday = 7 - $start_of_week - $weekday;
216
217                 $day -= 86400;
218                 $i = 0;
219         }
220         $week['start'] = $day + 86400 - $i;
221         $week['end'] = $week['start'] + 604799;
222         return $week;
223 }
224
225 /**
226  * Unserialize value only if it was serialized.
227  *
228  * @since 2.0.0
229  *
230  * @param string $original Maybe unserialized original, if is needed.
231  * @return mixed Unserialized data can be any type.
232  */
233 function maybe_unserialize( $original ) {
234         if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
235                 if ( false !== $gm = @unserialize( $original ) )
236                         return $gm;
237         return $original;
238 }
239
240 /**
241  * Check value to find if it was serialized.
242  *
243  * If $data is not an string, then returned value will always be false.
244  * Serialized data is always a string.
245  *
246  * @since 2.0.5
247  *
248  * @param mixed $data Value to check to see if was serialized.
249  * @return bool False if not serialized and true if it was.
250  */
251 function is_serialized( $data ) {
252         // if it isn't a string, it isn't serialized
253         if ( !is_string( $data ) )
254                 return false;
255         $data = trim( $data );
256         if ( 'N;' == $data )
257                 return true;
258         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
259                 return false;
260         switch ( $badions[1] ) {
261                 case 'a' :
262                 case 'O' :
263                 case 's' :
264                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
265                                 return true;
266                         break;
267                 case 'b' :
268                 case 'i' :
269                 case 'd' :
270                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
271                                 return true;
272                         break;
273         }
274         return false;
275 }
276
277 /**
278  * Check whether serialized data is of string type.
279  *
280  * @since 2.0.5
281  *
282  * @param mixed $data Serialized data
283  * @return bool False if not a serialized string, true if it is.
284  */
285 function is_serialized_string( $data ) {
286         // if it isn't a string, it isn't a serialized string
287         if ( !is_string( $data ) )
288                 return false;
289         $data = trim( $data );
290         if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
291                 return true;
292         return false;
293 }
294
295 /**
296  * Retrieve option value based on setting name.
297  *
298  * If the option does not exist or does not have a value, then the return value
299  * will be false. This is useful to check whether you need to install an option
300  * and is commonly used during installation of plugin options and to test
301  * whether upgrading is required.
302  *
303  * You can "short-circuit" the retrieval of the option from the database for
304  * your plugin or core options that aren't protected. You can do so by hooking
305  * into the 'pre_option_$option' with the $option being replaced by the option
306  * name. You should not try to override special options, but you will not be
307  * prevented from doing so.
308  *
309  * There is a second filter called 'option_$option' with the $option being
310  * replaced with the option name. This gives the value as the only parameter.
311  *
312  * @since 1.5.0
313  * @package WordPress
314  * @subpackage Option
315  * @uses apply_filters() Calls 'pre_option_$optionname' false to allow
316  *              overwriting the option value in a plugin.
317  * @uses apply_filters() Calls 'option_$optionname' with the option name value.
318  *
319  * @param string $setting Name of option to retrieve. Should already be SQL-escaped
320  * @return mixed Value set for the option.
321  */
322 function get_option( $setting ) {
323         global $wpdb;
324
325         // Allow plugins to short-circuit options.
326         $pre = apply_filters( 'pre_option_' . $setting, false );
327         if ( false !== $pre )
328                 return $pre;
329
330         // prevent non-existent options from triggering multiple queries
331         $notoptions = wp_cache_get( 'notoptions', 'options' );
332         if ( isset( $notoptions[$setting] ) )
333                 return false;
334
335         $alloptions = wp_load_alloptions();
336
337         if ( isset( $alloptions[$setting] ) ) {
338                 $value = $alloptions[$setting];
339         } else {
340                 $value = wp_cache_get( $setting, 'options' );
341
342                 if ( false === $value ) {
343                         if ( defined( 'WP_INSTALLING' ) )
344                                 $suppress = $wpdb->suppress_errors();
345                         // expected_slashed ($setting)
346                         $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" );
347                         if ( defined( 'WP_INSTALLING' ) )
348                                 $wpdb->suppress_errors($suppress);
349
350                         if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
351                                 $value = $row->option_value;
352                                 wp_cache_add( $setting, $value, 'options' );
353                         } else { // option does not exist, so we must cache its non-existence
354                                 $notoptions[$setting] = true;
355                                 wp_cache_set( 'notoptions', $notoptions, 'options' );
356                                 return false;
357                         }
358                 }
359         }
360
361         // If home is not set use siteurl.
362         if ( 'home' == $setting && '' == $value )
363                 return get_option( 'siteurl' );
364
365         if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) )
366                 $value = untrailingslashit( $value );
367
368         return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) );
369 }
370
371 /**
372  * Protect WordPress special option from being modified.
373  *
374  * Will die if $option is in protected list.
375  *
376  * @since 2.2.0
377  * @package WordPress
378  * @subpackage Option
379  *
380  * @param string $option Option name.
381  */
382 function wp_protect_special_option( $option ) {
383         $protected = array( 'alloptions', 'notoptions' );
384         if ( in_array( $option, $protected ) )
385                 die( sprintf( __( '%s is a protected WP option and may not be modified' ), wp_specialchars( $option ) ) );
386 }
387
388 /**
389  * Print option value after sanitizing for forms.
390  *
391  * @uses attribute_escape Sanitizes value.
392  * @since 1.5.0
393  * @package WordPress
394  * @subpackage Option
395  *
396  * @param string $option Option name.
397  */
398 function form_option( $option ) {
399         echo attribute_escape (get_option( $option ) );
400 }
401
402 /**
403  * Retrieve all autoload options or all options, if no autoloaded ones exist.
404  *
405  * This is different from wp_load_alloptions(), in this that function does not
406  * cache all options and will retrieve all options from the database every time
407  * it is called.
408  *
409  * @since 1.0.0
410  * @package WordPress
411  * @subpackage Option
412  * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter.
413  * @uses apply_filters() Calls 'all_options' on options list.
414  *
415  * @return array List of all options.
416  */
417 function get_alloptions() {
418         global $wpdb, $wp_queries;
419         $show = $wpdb->hide_errors();
420         if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
421                 $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
422         $wpdb->show_errors($show);
423
424         foreach ( $options as $option ) {
425                 // "When trying to design a foolproof system,
426                 //  never underestimate the ingenuity of the fools :)" -- Dougal
427                 if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) )
428                         $option->option_value = untrailingslashit( $option->option_value );
429                 $value = maybe_unserialize( $option->option_value );
430                 $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value );
431         }
432         return apply_filters( 'all_options', $all_options );
433 }
434
435 /**
436  * Loads and caches all autoloaded options, if available or all options.
437  *
438  * This is different from get_alloptions(), in that this function will cache the
439  * options and will return the cached options when called again.
440  *
441  * @since 2.2.0
442  * @package WordPress
443  * @subpackage Option
444  *
445  * @return array List all options.
446  */
447 function wp_load_alloptions() {
448         global $wpdb;
449
450         $alloptions = wp_cache_get( 'alloptions', 'options' );
451
452         if ( !$alloptions ) {
453                 $suppress = $wpdb->suppress_errors();
454                 if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
455                         $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
456                 $wpdb->suppress_errors($suppress);
457                 $alloptions = array();
458                 foreach ( (array) $alloptions_db as $o )
459                         $alloptions[$o->option_name] = $o->option_value;
460                 wp_cache_add( 'alloptions', $alloptions, 'options' );
461         }
462         return $alloptions;
463 }
464
465 /**
466  * Update the value of an option that was already added.
467  *
468  * If the option does not exist, then the option will be added with the option
469  * value, but you will not be able to set whether it is autoloaded. If you want
470  * to set whether an option autoloaded, then you need to use the add_option().
471  *
472  * When the option is updated, then the filter named
473  * 'update_option_$option_name', with the $option_name as the $option_name
474  * parameter value, will be called. The hook should accept two parameters, the
475  * first is the old parameter and the second is the new parameter.
476  *
477  * @since 1.0.0
478  * @package WordPress
479  * @subpackage Option
480  *
481  * @param string $option_name Option name. Expected to not be SQL-escaped
482  * @param mixed $newvalue Option value.
483  * @return bool False if value was not updated and true if value was updated.
484  */
485 function update_option( $option_name, $newvalue ) {
486         global $wpdb;
487
488         wp_protect_special_option( $option_name );
489
490         $safe_option_name = $wpdb->escape( $option_name );
491         $newvalue = sanitize_option( $option_name, $newvalue );
492
493         $oldvalue = get_option( $safe_option_name );
494
495         $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue );
496
497         // If the new and old values are the same, no need to update.
498         if ( $newvalue === $oldvalue )
499                 return false;
500
501         if ( false === $oldvalue ) {
502                 add_option( $option_name, $newvalue );
503                 return true;
504         }
505
506         $notoptions = wp_cache_get( 'notoptions', 'options' );
507         if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) {
508                 unset( $notoptions[$option_name] );
509                 wp_cache_set( 'notoptions', $notoptions, 'options' );
510         }
511
512         $_newvalue = $newvalue;
513         $newvalue = maybe_serialize( $newvalue );
514
515         $alloptions = wp_load_alloptions();
516         if ( isset( $alloptions[$option_name] ) ) {
517                 $alloptions[$option_name] = $newvalue;
518                 wp_cache_set( 'alloptions', $alloptions, 'options' );
519         } else {
520                 wp_cache_set( $option_name, $newvalue, 'options' );
521         }
522
523         $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", $newvalue, $option_name ) );
524         if ( $wpdb->rows_affected == 1 ) {
525                 do_action( "update_option_{$option_name}", $oldvalue, $_newvalue );
526                 return true;
527         }
528         return false;
529 }
530
531 /**
532  * Add a new option.
533  *
534  * You can create options without values and then add values later. Does not
535  * check whether the option has already been added, but does check that you
536  * aren't adding a protected WordPress option. Care should be taken to not name
537  * options, the same as the ones which are protected and to not add options
538  * that were already added.
539  *
540  * The filter named 'add_option_$optionname', with the $optionname being
541  * replaced with the option's name, will be called. The hook should accept two
542  * parameters, the first is the option name, and the second is the value.
543  *
544  * @package WordPress
545  * @subpackage Option
546  * @since 1.0.0
547  * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
548  *
549  * @param string $name Option name to add. Expects to NOT be SQL escaped.
550  * @param mixed $value Optional. Option value, can be anything.
551  * @param mixed $deprecated Optional. Description. Not used anymore.
552  * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
553  * @return null returns when finished.
554  */
555 function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) {
556         global $wpdb;
557
558         wp_protect_special_option( $name );
559         $safe_name = $wpdb->escape( $name );
560         $value = sanitize_option( $name, $value );
561
562         // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
563         $notoptions = wp_cache_get( 'notoptions', 'options' );
564         if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) )
565                 if ( false !== get_option( $safe_name ) )
566                         return;
567
568         $value = maybe_serialize( $value );
569         $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
570
571         if ( 'yes' == $autoload ) {
572                 $alloptions = wp_load_alloptions();
573                 $alloptions[$name] = $value;
574                 wp_cache_set( 'alloptions', $alloptions, 'options' );
575         } else {
576                 wp_cache_set( $name, $value, 'options' );
577         }
578
579         // This option exists now
580         $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
581         if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) {
582                 unset( $notoptions[$name] );
583                 wp_cache_set( 'notoptions', $notoptions, 'options' );
584         }
585
586         $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %s, %s)", $name, $value, $autoload ) );
587
588         do_action( "add_option_{$name}", $name, $value );
589         return;
590 }
591
592 /**
593  * Removes option by name and prevents removal of protected WordPress options.
594  *
595  * @package WordPress
596  * @subpackage Option
597  * @since unknown
598  *
599  * @param string $name Option name to remove.
600  * @return bool True, if succeed. False, if failure.
601  */
602 function delete_option( $name ) {
603         global $wpdb;
604
605         wp_protect_special_option( $name );
606
607         // Get the ID, if no ID then return
608         // expected_slashed ($name)
609         $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" );
610         if ( is_null($option) || !$option->option_id )
611                 return false;
612         // expected_slashed ($name)
613         $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
614         if ( 'yes' == $option->autoload ) {
615                 $alloptions = wp_load_alloptions();
616                 if ( isset( $alloptions[$name] ) ) {
617                         unset( $alloptions[$name] );
618                         wp_cache_set( 'alloptions', $alloptions, 'options' );
619                 }
620         } else {
621                 wp_cache_delete( $name, 'options' );
622         }
623         return true;
624 }
625
626 /**
627  * Serialize data, if needed.
628  *
629  * @param mixed $data Data that might be serialized.
630  * @return mixed A scalar data
631  */
632 function maybe_serialize( $data ) {
633         if ( is_array( $data ) || is_object( $data ) )
634                 return serialize( $data );
635
636         if ( is_serialized( $data ) )
637                 return serialize( $data );
638
639         return $data;
640 }
641
642
643 function make_url_footnote( $content ) {
644         preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
645         $j = 0;
646         for ( $i=0; $i<count($matches[0]); $i++ ) {
647                 $links_summary = ( !$j ) ? "\n" : $links_summary;
648                 $j++;
649                 $link_match = $matches[0][$i];
650                 $link_number = '['.($i+1).']';
651                 $link_url = $matches[2][$i];
652                 $link_text = $matches[4][$i];
653                 $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content );
654                 $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url;
655                 $links_summary .= "\n" . $link_number . ' ' . $link_url;
656         }
657         $content  = strip_tags( $content );
658         $content .= $links_summary;
659         return $content;
660 }
661
662
663 function xmlrpc_getposttitle( $content ) {
664         global $post_default_title;
665         if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
666                 $post_title = $matchtitle[0];
667                 $post_title = preg_replace( '/<title>/si', '', $post_title );
668                 $post_title = preg_replace( '/<\/title>/si', '', $post_title );
669         } else {
670                 $post_title = $post_default_title;
671         }
672         return $post_title;
673 }
674
675
676 function xmlrpc_getpostcategory( $content ) {
677         global $post_default_category;
678         if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
679                 $post_category = trim( $matchcat[1], ',' );
680                 $post_category = explode( ',', $post_category );
681         } else {
682                 $post_category = $post_default_category;
683         }
684         return $post_category;
685 }
686
687
688 function xmlrpc_removepostdata( $content ) {
689         $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
690         $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
691         $content = trim( $content );
692         return $content;
693 }
694
695 /**
696  * Open the file handle for debugging.
697  *
698  * This function is used for XMLRPC feature, but it is general purpose enough
699  * to be used in anywhere.
700  *
701  * @see fopen() for mode options.
702  * @package WordPress
703  * @subpackage Debug
704  * @since unknown
705  * @uses $debug Used for whether debugging is enabled.
706  *
707  * @param string $filename File path to debug file.
708  * @param string $mode Same as fopen() mode parameter.
709  * @return bool|resource File handle. False on failure.
710  */
711 function debug_fopen( $filename, $mode ) {
712         global $debug;
713         if ( 1 == $debug ) {
714                 $fp = fopen( $filename, $mode );
715                 return $fp;
716         } else {
717                 return false;
718         }
719 }
720
721 /**
722  * Write contents to the file used for debugging.
723  *
724  * Technically, this can be used to write to any file handle when the global
725  * $debug is set to 1 or true.
726  *
727  * @package WordPress
728  * @subpackage Debug
729  * @since unknown
730  * @uses $debug Used for whether debugging is enabled.
731  *
732  * @param resource $fp File handle for debugging file.
733  * @param string $string Content to write to debug file.
734  */
735 function debug_fwrite( $fp, $string ) {
736         global $debug;
737         if ( 1 == $debug )
738                 fwrite( $fp, $string );
739 }
740
741 /**
742  * Close the debugging file handle.
743  *
744  * Technically, this can be used to close any file handle when the global $debug
745  * is set to 1 or true.
746  *
747  * @package WordPress
748  * @subpackage Debug
749  * @since unknown
750  * @uses $debug Used for whether debugging is enabled.
751  *
752  * @param resource $fp Debug File handle.
753  */
754 function debug_fclose( $fp ) {
755         global $debug;
756         if ( 1 == $debug )
757                 fclose( $fp );
758 }
759
760 function do_enclose( $content, $post_ID ) {
761         global $wpdb;
762         include_once( ABSPATH . WPINC . '/class-IXR.php' );
763
764         $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
765         $post_links = array();
766         debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
767
768         $pung = get_enclosed( $post_ID );
769
770         $ltrs = '\w';
771         $gunk = '/#~:.?+=&%@!\-';
772         $punc = '.:?\-';
773         $any = $ltrs . $gunk . $punc;
774
775         preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
776
777         debug_fwrite( $log, 'Post contents:' );
778         debug_fwrite( $log, $content . "\n" );
779
780         foreach ( $post_links_temp[0] as $link_test ) {
781                 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
782                         $test = parse_url( $link_test );
783                         if ( isset( $test['query'] ) )
784                                 $post_links[] = $link_test;
785                         elseif ( $test['path'] != '/' && $test['path'] != '' )
786                                 $post_links[] = $link_test;
787                 }
788         }
789
790         foreach ( $post_links as $url ) {
791                 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, $url . '%' ) ) ) {
792                         if ( $headers = wp_get_http_headers( $url) ) {
793                                 $len = (int) $headers['content-length'];
794                                 $type = $wpdb->escape( $headers['content-type'] );
795                                 $allowed_types = array( 'video', 'audio' );
796                                 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
797                                         $meta_value = "$url\n$len\n$type\n";
798                                         $wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
799                                         VALUES ( %d, 'enclosure' , %s)", $post_ID, $meta_value ) );
800                                 }
801                         }
802                 }
803         }
804 }
805
806 /**
807  * Perform a HTTP HEAD or GET request.
808  *
809  * If $file_path is a writable filename, this will do a GET request and write
810  * the file to that path.
811  *
812  * @since unknown
813  *
814  * @param string $url
815  * @param string|bool $file_path Optional. File path to write request to.
816  * @param int $red Optional. Number of Redirects. Stops at 5 redirects.
817  * @return bool|string False on failure and string of headers if HEAD request.
818  */
819 function wp_get_http( $url, $file_path = false, $red = 1 ) {
820         global $wp_version;
821         @set_time_limit( 60 );
822
823         if ( $red > 5 )
824                  return false;
825
826         $parts = parse_url( $url );
827         $file = $parts['path'] . ( ( $parts['query'] ) ? '?' . $parts['query'] : '' );
828         $host = $parts['host'];
829         if ( !isset( $parts['port'] ) )
830                 $parts['port'] = 80;
831
832         if ( $file_path )
833                 $request_type = 'GET';
834         else
835                 $request_type = 'HEAD';
836
837         $head = "$request_type $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
838
839         $fp = @fsockopen( $host, $parts['port'], $err_num, $err_msg, 3 );
840         if ( !$fp )
841                 return false;
842
843         $response = '';
844         fputs( $fp, $head );
845         while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
846                 $response .= fgets( $fp, 2048 );
847         preg_match_all( '/(.*?): (.*)\r/', $response, $matches );
848         $count = count( $matches[1] );
849         for ( $i = 0; $i < $count; $i++ ) {
850                 $key = strtolower( $matches[1][$i] );
851                 $headers["$key"] = $matches[2][$i];
852         }
853
854         preg_match( '/.*([0-9]{3}).*/', $response, $return );
855         $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
856
857                 $code = $headers['response'];
858                 if ( ( '302' == $code || '301' == $code ) && isset( $headers['location'] ) ) {
859                                 fclose($fp);
860                                 return wp_get_http( $headers['location'], $file_path, ++$red );
861                 }
862
863         // make a note of the final location, so the caller can tell if we were redirected or not
864         $headers['x-final-location'] = $url;
865
866         // HEAD request only
867         if ( !$file_path ) {
868                 fclose($fp);
869                 return $headers;
870         }
871
872         // GET request - fetch and write it to the supplied filename
873         $content_length = $headers['content-length'];
874         $got_bytes = 0;
875         $out_fp = fopen($file_path, 'w');
876         while ( !feof($fp) ) {
877                 $buf = fread( $fp, 4096 );
878                 fwrite( $out_fp, $buf );
879                 $got_bytes += strlen($buf);
880                 // don't read past the content-length
881                 if ($content_length and $got_bytes >= $content_length)
882                         break;
883         }
884
885         fclose($out_fp);
886         fclose($fp);
887         return $headers;
888 }
889
890 /**
891  * Retrieve HTTP Headers from URL.
892  *
893  * @since 1.5.1
894  *
895  * @param string $url
896  * @param int $red Optional. Number of redirects.
897  * @return bool|string False on failure, headers on success.
898  */
899 function wp_get_http_headers( $url, $red = 1 ) {
900         return wp_get_http( $url, false, $red );
901 }
902
903 /**
904  * Whether today is a new day.
905  *
906  * {@internal Need to find out how this function is used.}}
907  *
908  * @since 0.71
909  * @uses $day Today
910  * @uses $previousday Previous day
911  *
912  * @return int 1 when new day, 0 if not a new day.
913  */
914 function is_new_day() {
915         global $day, $previousday;
916         if ( $day != $previousday )
917                 return 1;
918         else
919                 return 0;
920 }
921
922 /**
923  * Build URL query based on an associative and, or indexed array.
924  *
925  * This is a convenient function for easily building url queries. It sets the
926  * separator to '&' and uses _http_build_query() function.
927  *
928  * @see _http_build_query() Used to build the query
929  * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
930  *              http_build_query() does.
931  *
932  * @since unknown
933  *
934  * @param array $data URL-encode key/value pairs.
935  * @return string URL encoded string
936  */
937 function build_query( $data ) {
938         return _http_build_query( $data, NULL, '&', '', false );
939 }
940
941 /**
942  * Retrieve a modified URL query string.
943  *
944  * You can rebuild the URL and append a new query variable to the URL query by
945  * using this function. You can also retrieve the full URL with query data.
946  *
947  * Adding a single key & value or an associative array. Setting a key value to
948  * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
949  * value.
950  *
951  * @since 1.5.0
952  *
953  * @param mixed $param1 Either newkey or an associative_array
954  * @param mixed $param2 Either newvalue or oldquery or uri
955  * @param mixed $param3 Optional. Old query or uri
956  * @return unknown
957  */
958 function add_query_arg() {
959         $ret = '';
960         if ( is_array( func_get_arg(0) ) ) {
961                 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
962                         $uri = $_SERVER['REQUEST_URI'];
963                 else
964                         $uri = @func_get_arg( 1 );
965         } else {
966                 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
967                         $uri = $_SERVER['REQUEST_URI'];
968                 else
969                         $uri = @func_get_arg( 2 );
970         }
971
972         if ( $frag = strstr( $uri, '#' ) )
973                 $uri = substr( $uri, 0, -strlen( $frag ) );
974         else
975                 $frag = '';
976
977         if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
978                 $protocol = $matches[0];
979                 $uri = substr( $uri, strlen( $protocol ) );
980         } else {
981                 $protocol = '';
982         }
983
984         if ( strpos( $uri, '?' ) !== false ) {
985                 $parts = explode( '?', $uri, 2 );
986                 if ( 1 == count( $parts ) ) {
987                         $base = '?';
988                         $query = $parts[0];
989                 } else {
990                         $base = $parts[0] . '?';
991                         $query = $parts[1];
992                 }
993         } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
994                 $base = $uri . '?';
995                 $query = '';
996         } else {
997                 $base = '';
998                 $query = $uri;
999         }
1000
1001         wp_parse_str( $query, $qs );
1002         $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
1003         if ( is_array( func_get_arg( 0 ) ) ) {
1004                 $kayvees = func_get_arg( 0 );
1005                 $qs = array_merge( $qs, $kayvees );
1006         } else {
1007                 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
1008         }
1009
1010         foreach ( $qs as $k => $v ) {
1011                 if ( $v === false )
1012                         unset( $qs[$k] );
1013         }
1014
1015         $ret = build_query( $qs );
1016         $ret = trim( $ret, '?' );
1017         $ret = preg_replace( '#=(&|$)#', '$1', $ret );
1018         $ret = $protocol . $base . $ret . $frag;
1019         $ret = rtrim( $ret, '?' );
1020         return $ret;
1021 }
1022
1023 /**
1024  * Removes an item or list from the query string.
1025  *
1026  * @since 1.5.0
1027  *
1028  * @param string|array $key Query key or keys to remove.
1029  * @param bool $query When false uses the $_SERVER value.
1030  * @return unknown
1031  */
1032 function remove_query_arg( $key, $query=false ) {
1033         if ( is_array( $key ) ) { // removing multiple keys
1034                 foreach ( (array) $key as $k )
1035                         $query = add_query_arg( $k, false, $query );
1036                 return $query;
1037         }
1038         return add_query_arg( $key, false, $query );
1039 }
1040
1041 /**
1042  * Walks the array while sanitizing the contents.
1043  *
1044  * @uses $wpdb Used to sanitize values
1045  *
1046  * @param array $array Array to used to walk while sanitizing contents.
1047  * @return array Sanitized $array.
1048  */
1049 function add_magic_quotes( $array ) {
1050         global $wpdb;
1051
1052         foreach ( $array as $k => $v ) {
1053                 if ( is_array( $v ) ) {
1054                         $array[$k] = add_magic_quotes( $v );
1055                 } else {
1056                         $array[$k] = $wpdb->escape( $v );
1057                 }
1058         }
1059         return $array;
1060 }
1061
1062 /**
1063  * HTTP request for URI to retrieve content.
1064  *
1065  * Tries to retrieve the HTTP content with fopen first and then using cURL, if
1066  * fopen can't be used.
1067  *
1068  * @since unknown
1069  *
1070  * @param string $uri URI/URL of web page to retrieve.
1071  * @return string HTTP content.
1072  */
1073 function wp_remote_fopen( $uri ) {
1074         $timeout = 10;
1075         $parsed_url = @parse_url( $uri );
1076
1077         if ( !$parsed_url || !is_array( $parsed_url ) )
1078                 return false;
1079
1080         if ( !isset( $parsed_url['scheme'] ) || !in_array( $parsed_url['scheme'], array( 'http','https' ) ) )
1081                 $uri = 'http://' . $uri;
1082
1083         if ( ini_get( 'allow_url_fopen' ) ) {
1084                 $fp = @fopen( $uri, 'r' );
1085                 if ( !$fp )
1086                         return false;
1087
1088                 //stream_set_timeout($fp, $timeout); // Requires php 4.3
1089                 $linea = '';
1090                 while ( $remote_read = fread( $fp, 4096 ) )
1091                         $linea .= $remote_read;
1092                 fclose( $fp );
1093                 return $linea;
1094         } elseif ( function_exists( 'curl_init' ) ) {
1095                 $handle = curl_init();
1096                 curl_setopt( $handle, CURLOPT_URL, $uri);
1097                 curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 1 );
1098                 curl_setopt( $handle, CURLOPT_RETURNTRANSFER, 1 );
1099                 curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
1100                 $buffer = curl_exec( $handle );
1101                 curl_close( $handle );
1102                 return $buffer;
1103         } else {
1104                 return false;
1105         }
1106 }
1107
1108
1109 function wp( $query_vars = '' ) {
1110         global $wp, $wp_query, $wp_the_query;
1111         $wp->main( $query_vars );
1112
1113         if( !isset($wp_the_query) )
1114                 $wp_the_query = $wp_query;
1115 }
1116
1117 /**
1118  * Retrieve the description for the HTTP status.
1119  *
1120  * @since 2.3.0
1121  *
1122  * @param int $code HTTP status code.
1123  * @return string Empty string if not found, or description if found.
1124  */
1125 function get_status_header_desc( $code ) {
1126         global $wp_header_to_desc;
1127
1128         $code = absint( $code );
1129
1130         if ( !isset( $wp_header_to_desc ) ) {
1131                 $wp_header_to_desc = array(
1132                         100 => 'Continue',
1133                         101 => 'Switching Protocols',
1134
1135                         200 => 'OK',
1136                         201 => 'Created',
1137                         202 => 'Accepted',
1138                         203 => 'Non-Authoritative Information',
1139                         204 => 'No Content',
1140                         205 => 'Reset Content',
1141                         206 => 'Partial Content',
1142
1143                         300 => 'Multiple Choices',
1144                         301 => 'Moved Permanently',
1145                         302 => 'Found',
1146                         303 => 'See Other',
1147                         304 => 'Not Modified',
1148                         305 => 'Use Proxy',
1149                         307 => 'Temporary Redirect',
1150
1151                         400 => 'Bad Request',
1152                         401 => 'Unauthorized',
1153                         403 => 'Forbidden',
1154                         404 => 'Not Found',
1155                         405 => 'Method Not Allowed',
1156                         406 => 'Not Acceptable',
1157                         407 => 'Proxy Authentication Required',
1158                         408 => 'Request Timeout',
1159                         409 => 'Conflict',
1160                         410 => 'Gone',
1161                         411 => 'Length Required',
1162                         412 => 'Precondition Failed',
1163                         413 => 'Request Entity Too Large',
1164                         414 => 'Request-URI Too Long',
1165                         415 => 'Unsupported Media Type',
1166                         416 => 'Requested Range Not Satisfiable',
1167                         417 => 'Expectation Failed',
1168
1169                         500 => 'Internal Server Error',
1170                         501 => 'Not Implemented',
1171                         502 => 'Bad Gateway',
1172                         503 => 'Service Unavailable',
1173                         504 => 'Gateway Timeout',
1174                         505 => 'HTTP Version Not Supported'
1175                 );
1176         }
1177
1178         if ( isset( $wp_header_to_desc[$code] ) )
1179                 return $wp_header_to_desc[$code];
1180         else
1181                 return '';
1182 }
1183
1184 /**
1185  * Set HTTP status header.
1186  *
1187  * @since unknown
1188  * @uses apply_filters() Calls 'status_header' on status header string, HTTP
1189  *              HTTP code, HTTP code description, and protocol string as separate
1190  *              parameters.
1191  *
1192  * @param int $header HTTP status code
1193  * @return null Does not return anything.
1194  */
1195 function status_header( $header ) {
1196         $text = get_status_header_desc( $header );
1197
1198         if ( empty( $text ) )
1199                 return false;
1200
1201         $protocol = $_SERVER["SERVER_PROTOCOL"];
1202         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
1203                 $protocol = 'HTTP/1.0';
1204         $status_header = "$protocol $header $text";
1205         if ( function_exists( 'apply_filters' ) )
1206                 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
1207
1208         if ( version_compare( phpversion(), '4.3.0', '>=' ) )
1209                 return @header( $status_header, true, $header );
1210         else
1211                 return @header( $status_header );
1212 }
1213
1214 /**
1215  * Sets the headers to prevent caching for the different browsers.
1216  *
1217  * Different browsers support different nocache headers, so several headers must
1218  * be sent so that all of them get the point that no caching should occur.
1219  *
1220  * @since 2.0.0
1221  */
1222 function nocache_headers() {
1223         // why are these @-silenced when other header calls aren't?
1224         @header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
1225         @header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
1226         @header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
1227         @header( 'Pragma: no-cache' );
1228 }
1229
1230 /**
1231  * Set the headers for caching for 10 days with JavaScript content type.
1232  *
1233  * @since 2.1.0
1234  */
1235 function cache_javascript_headers() {
1236         $expiresOffset = 864000; // 10 days
1237         header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
1238         header( "Vary: Accept-Encoding" ); // Handle proxies
1239         header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
1240 }
1241
1242 /**
1243  * Retrieve the number of database queries during the WordPress execution.
1244  *
1245  * @since 2.0.0
1246  *
1247  * @return int Number of database queries
1248  */
1249 function get_num_queries() {
1250         global $wpdb;
1251         return $wpdb->num_queries;
1252 }
1253
1254 /**
1255  * Whether input is yes or no. Must be 'y' to be true.
1256  *
1257  * @since 1.0.0
1258  *
1259  * @param string $yn Character string containing either 'y' or 'n'
1260  * @return bool True if yes, false on anything else
1261  */
1262 function bool_from_yn( $yn ) {
1263         return ( strtolower( $yn ) == 'y' );
1264 }
1265
1266
1267 function do_feed() {
1268         global $wp_query;
1269
1270         $feed = get_query_var( 'feed' );
1271
1272         // Remove the pad, if present.
1273         $feed = preg_replace( '/^_+/', '', $feed );
1274
1275         if ( $feed == '' || $feed == 'feed' )
1276                 $feed = get_default_feed();
1277
1278         $hook = 'do_feed_' . $feed;
1279         if ( !has_action($hook) ) {
1280                 $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), wp_specialchars($feed));
1281                 wp_die($message);
1282         }
1283
1284         do_action( $hook, $wp_query->is_comment_feed );
1285 }
1286
1287 /**
1288  * Load the RDF RSS 0.91 Feed template.
1289  *
1290  * @since 2.1.0
1291  */
1292 function do_feed_rdf() {
1293         load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1294 }
1295
1296 /**
1297  * Load the RSS 1.0 Feed Template
1298  *
1299  * @since 2.1.0
1300  */
1301 function do_feed_rss() {
1302         load_template( ABSPATH . WPINC . '/feed-rss.php' );
1303 }
1304
1305 /**
1306  * Load either the RSS2 comment feed or the RSS2 posts feed.
1307  *
1308  * @since 2.1.0
1309  *
1310  * @param bool $for_comments True for the comment feed, false for normal feed.
1311  */
1312 function do_feed_rss2( $for_comments ) {
1313         if ( $for_comments )
1314                 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1315         else
1316                 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1317 }
1318
1319 /**
1320  * Load either Atom comment feed or Atom posts feed.
1321  *
1322  * @since 2.1.0
1323  *
1324  * @param bool $for_comments True for the comment feed, false for normal feed.
1325  */
1326 function do_feed_atom( $for_comments ) {
1327         if ($for_comments)
1328                 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1329         else
1330                 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1331 }
1332
1333 /**
1334  * Display the robot.txt file content.
1335  *
1336  * The echo content should be with usage of the permalinks or for creating the
1337  * robot.txt file.
1338  *
1339  * @since 2.1.0
1340  * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
1341  */
1342 function do_robots() {
1343         header( 'Content-Type: text/plain; charset=utf-8' );
1344
1345         do_action( 'do_robotstxt' );
1346
1347         if ( '0' == get_option( 'blog_public' ) ) {
1348                 echo "User-agent: *\n";
1349                 echo "Disallow: /\n";
1350         } else {
1351                 echo "User-agent: *\n";
1352                 echo "Disallow:\n";
1353         }
1354 }
1355
1356
1357 function is_blog_installed() {
1358         global $wpdb;
1359
1360         // Check cache first.  If options table goes away and we have true cached, oh well.
1361         if ( wp_cache_get('is_blog_installed') )
1362                 return true;
1363
1364         $suppress = $wpdb->suppress_errors();
1365         $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1366         $wpdb->suppress_errors($suppress);
1367
1368         $installed = !empty( $installed ) ? true : false;
1369         wp_cache_set('is_blog_installed', $installed);
1370
1371         return $installed;
1372 }
1373
1374
1375 function wp_nonce_url( $actionurl, $action = -1 ) {
1376         $actionurl = str_replace( '&amp;', '&', $actionurl );
1377         return wp_specialchars( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1378 }
1379
1380
1381 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1382         $name = attribute_escape( $name );
1383         $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1384         if ( $echo )
1385                 echo $nonce_field;
1386         
1387         if ( $referer )
1388                 wp_referer_field( $echo, 'previous' );
1389         
1390         return $nonce_field;
1391 }
1392
1393
1394 function wp_referer_field( $echo = true) {
1395         $ref = attribute_escape( $_SERVER['REQUEST_URI'] );
1396         $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
1397
1398         if ( $echo )
1399                 echo $referer_field;
1400         return $referer_field;
1401 }
1402
1403 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1404         $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
1405         $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
1406         $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . attribute_escape( stripslashes( $ref ) ) . '" />';
1407         if ( $echo )
1408                 echo $orig_referer_field;
1409         return $orig_referer_field;
1410 }
1411
1412
1413 function wp_get_referer() {
1414         if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
1415                 $ref = $_REQUEST['_wp_http_referer'];
1416         else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
1417                 $ref = $_SERVER['HTTP_REFERER'];
1418
1419         if ( $ref !== $_SERVER['REQUEST_URI'] )
1420                 return $ref;
1421         return false;
1422 }
1423
1424
1425 function wp_get_original_referer() {
1426         if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
1427                 return $_REQUEST['_wp_original_http_referer'];
1428         return false;
1429 }
1430
1431
1432 function wp_mkdir_p( $target ) {
1433         // from php.net/mkdir user contributed notes
1434         $target = str_replace( '//', '/', $target );
1435         if ( file_exists( $target ) )
1436                 return @is_dir( $target );
1437
1438         // Attempting to create the directory may clutter up our display.
1439         if ( @mkdir( $target ) ) {
1440                 $stat = @stat( dirname( $target ) );
1441                 $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
1442                 @chmod( $target, $dir_perms );
1443                 return true;
1444         } elseif ( is_dir( dirname( $target ) ) ) {
1445                         return false;
1446         }
1447
1448         // If the above failed, attempt to create the parent node, then try again.
1449         if ( wp_mkdir_p( dirname( $target ) ) )
1450                 return wp_mkdir_p( $target );
1451
1452         return false;
1453 }
1454
1455 // Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows')
1456 function path_is_absolute( $path ) {
1457         // this is definitive if true but fails if $path does not exist or contains a symbolic link
1458         if ( realpath($path) == $path )
1459                 return true;
1460
1461         if ( strlen($path) == 0 || $path{0} == '.' )
1462                 return false;
1463
1464         // windows allows absolute paths like this
1465         if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1466                 return true;
1467
1468         // a path starting with / or \ is absolute; anything else is relative
1469         return (bool) preg_match('#^[/\\\\]#', $path);
1470 }
1471
1472 // Join two filesystem paths together (e.g. 'give me $path relative to $base')
1473 function path_join( $base, $path ) {
1474         if ( path_is_absolute($path) )
1475                 return $path;
1476
1477         return rtrim($base, '/') . '/' . ltrim($path, '/');
1478 }
1479
1480 // Returns an array containing the current upload directory's path and url, or an error message.
1481 function wp_upload_dir( $time = NULL ) {
1482         $siteurl = get_option( 'siteurl' );
1483         $upload_path = get_option( 'upload_path' );
1484         $upload_path = trim($upload_path);
1485         if ( empty($upload_path) )
1486                 $dir = WP_CONTENT_DIR . '/uploads';
1487         else 
1488                 $dir = $upload_path;
1489
1490         // $dir is absolute, $path is (maybe) relative to ABSPATH
1491         $dir = path_join( ABSPATH, $dir );
1492         
1493         if ( !$url = get_option( 'upload_url_path' ) ) {
1494                 if ( empty($upload_path) or ( $upload_path == $dir ) )
1495                         $url = WP_CONTENT_URL . '/uploads';
1496                 else
1497                         $url = trailingslashit( $siteurl ) . $upload_path;
1498         }
1499
1500         if ( defined('UPLOADS') ) {
1501                 $dir = ABSPATH . UPLOADS;
1502                 $url = trailingslashit( $siteurl ) . UPLOADS;
1503         }
1504
1505         $bdir = $dir; 
1506         $burl = $url;
1507
1508         $subdir = '';
1509         if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
1510                 // Generate the yearly and monthly dirs
1511                 if ( !$time )
1512                         $time = current_time( 'mysql' );
1513                 $y = substr( $time, 0, 4 );
1514                 $m = substr( $time, 5, 2 );
1515                 $subdir = "/$y/$m";
1516         }
1517
1518         $dir .= $subdir;
1519         $url .= $subdir;
1520
1521         // Make sure we have an uploads dir
1522         if ( ! wp_mkdir_p( $dir ) ) {
1523                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $dir );
1524                 return array( 'error' => $message );
1525         }
1526         
1527         $uploads = array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false );
1528
1529         return apply_filters( 'upload_dir', $uploads );
1530 }
1531
1532 // return a filename that is sanitized and unique for the given directory
1533 function wp_unique_filename( $dir, $filename, $unique_filename_callback = NULL ) {
1534         $filename = strtolower( $filename );
1535         // separate the filename into a name and extension
1536         $info = pathinfo($filename);
1537         $ext = $info['extension'];
1538         $name = basename($filename, ".{$ext}");
1539         
1540         // edge case: if file is named '.ext', treat as an empty name
1541         if( $name === ".$ext" )
1542                 $name = '';
1543
1544         // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
1545         if ( $unique_filename_callback && function_exists( $unique_filename_callback ) ) {
1546                 $filename = $unique_filename_callback( $dir, $name );
1547         } else {
1548                 $number = '';
1549
1550                 if ( empty( $ext ) )
1551                         $ext = '';
1552                 else
1553                         $ext = strtolower( ".$ext" );
1554
1555                 $filename = str_replace( $ext, '', $filename );
1556                 // Strip % so the server doesn't try to decode entities.
1557                 $filename = str_replace('%', '', sanitize_title_with_dashes( $filename ) ) . $ext;
1558
1559                 while ( file_exists( $dir . "/$filename" ) ) {
1560                         if ( '' == "$number$ext" )
1561                                 $filename = $filename . ++$number . $ext;
1562                         else
1563                                 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
1564                 }
1565         }
1566
1567         return $filename;
1568 }
1569
1570 function wp_upload_bits( $name, $deprecated, $bits, $time = NULL ) {
1571         if ( empty( $name ) )
1572                 return array( 'error' => __( "Empty filename" ) );
1573
1574         $wp_filetype = wp_check_filetype( $name );
1575         if ( !$wp_filetype['ext'] )
1576                 return array( 'error' => __( "Invalid file type" ) );
1577
1578         $upload = wp_upload_dir( $time );
1579
1580         if ( $upload['error'] !== false )
1581                 return $upload;
1582
1583         $filename = wp_unique_filename( $upload['path'], $name );
1584
1585         $new_file = $upload['path'] . "/$filename";
1586         if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
1587                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
1588                 return array( 'error' => $message );
1589         }
1590
1591         $ifp = @ fopen( $new_file, 'wb' );
1592         if ( ! $ifp )
1593                 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
1594
1595         @fwrite( $ifp, $bits );
1596         fclose( $ifp );
1597         // Set correct file permissions
1598         $stat = @ stat( dirname( $new_file ) );
1599         $perms = $stat['mode'] & 0007777;
1600         $perms = $perms & 0000666;
1601         @ chmod( $new_file, $perms );
1602
1603         // Compute the URL
1604         $url = $upload['url'] . "/$filename";
1605
1606         return array( 'file' => $new_file, 'url' => $url, 'error' => false );
1607 }
1608
1609 function wp_ext2type( $ext ) {
1610         $ext2type = apply_filters('ext2type', array(
1611                 'audio' => array('aac','ac3','aif','aiff','mp1','mp2','mp3','m3a','m4a','m4b','ogg','ram','wav','wma'),
1612                 'video' => array('asf','avi','divx','dv','mov','mpg','mpeg','mp4','mpv','ogm','qt','rm','vob','wmv'),
1613                 'document' => array('doc','pages','odt','rtf','pdf'),
1614                 'spreadsheet' => array('xls','numbers','ods'),
1615                 'interactive' => array('ppt','key','odp','swf'),
1616                 'text' => array('txt'),
1617                 'archive' => array('tar','bz2','gz','cab','dmg','rar','sea','sit','sqx','zip'),
1618                 'code' => array('css','html','php','js'),
1619         ));
1620         foreach ( $ext2type as $type => $exts )
1621                 if ( in_array($ext, $exts) )
1622                         return $type;
1623 }
1624
1625 function wp_check_filetype( $filename, $mimes = null ) {
1626         // Accepted MIME types are set here as PCRE unless provided.
1627         $mimes = ( is_array( $mimes ) ) ? $mimes : apply_filters( 'upload_mimes', array(
1628                 'jpg|jpeg|jpe' => 'image/jpeg',
1629                 'gif' => 'image/gif',
1630                 'png' => 'image/png',
1631                 'bmp' => 'image/bmp',
1632                 'tif|tiff' => 'image/tiff',
1633                 'ico' => 'image/x-icon',
1634                 'asf|asx|wax|wmv|wmx' => 'video/asf',
1635                 'avi' => 'video/avi',
1636                 'mov|qt' => 'video/quicktime',
1637                 'mpeg|mpg|mpe|mp4' => 'video/mpeg',
1638                 'txt|c|cc|h' => 'text/plain',
1639                 'rtx' => 'text/richtext',
1640                 'css' => 'text/css',
1641                 'htm|html' => 'text/html',
1642                 'mp3|m4a' => 'audio/mpeg',
1643                 'ra|ram' => 'audio/x-realaudio',
1644                 'wav' => 'audio/wav',
1645                 'ogg' => 'audio/ogg',
1646                 'mid|midi' => 'audio/midi',
1647                 'wma' => 'audio/wma',
1648                 'rtf' => 'application/rtf',
1649                 'js' => 'application/javascript',
1650                 'pdf' => 'application/pdf',
1651                 'doc' => 'application/msword',
1652                 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
1653                 'wri' => 'application/vnd.ms-write',
1654                 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
1655                 'mdb' => 'application/vnd.ms-access',
1656                 'mpp' => 'application/vnd.ms-project',
1657                 'swf' => 'application/x-shockwave-flash',
1658                 'class' => 'application/java',
1659                 'tar' => 'application/x-tar',
1660                 'zip' => 'application/zip',
1661                 'gz|gzip' => 'application/x-gzip',
1662                 'exe' => 'application/x-msdownload',
1663                 // openoffice formats
1664                 'odt' => 'application/vnd.oasis.opendocument.text',
1665                 'odp' => 'application/vnd.oasis.opendocument.presentation',
1666                 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1667                 'odg' => 'application/vnd.oasis.opendocument.graphics',
1668                 'odc' => 'application/vnd.oasis.opendocument.chart',
1669                 'odb' => 'application/vnd.oasis.opendocument.database',
1670                 'odf' => 'application/vnd.oasis.opendocument.formula',
1671                 )
1672         );
1673
1674         $type = false;
1675         $ext = false;
1676
1677         foreach ( $mimes as $ext_preg => $mime_match ) {
1678                 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1679                 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
1680                         $type = $mime_match;
1681                         $ext = $ext_matches[1];
1682                         break;
1683                 }
1684         }
1685
1686         return compact( 'ext', 'type' );
1687 }
1688
1689 function wp_explain_nonce( $action ) {
1690         if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
1691                 $verb = $matches[1];
1692                 $noun = $matches[2];
1693
1694                 $trans = array();
1695                 $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: &quot;%s&quot; has failed.' ), 'get_the_title' );
1696
1697                 $trans['add']['category']      = array( __( 'Your attempt to add this category has failed.' ), false );
1698                 $trans['delete']['category']   = array( __( 'Your attempt to delete this category: &quot;%s&quot; has failed.' ), 'get_catname' );
1699                 $trans['update']['category']   = array( __( 'Your attempt to edit this category: &quot;%s&quot; has failed.' ), 'get_catname' );
1700
1701                 $trans['delete']['comment']    = array( __( 'Your attempt to delete this comment: &quot;%s&quot; has failed.' ), 'use_id' );
1702                 $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: &quot;%s&quot; has failed.' ), 'use_id' );
1703                 $trans['approve']['comment']   = array( __( 'Your attempt to approve this comment: &quot;%s&quot; has failed.' ), 'use_id' );
1704                 $trans['update']['comment']    = array( __( 'Your attempt to edit this comment: &quot;%s&quot; has failed.' ), 'use_id' );
1705                 $trans['bulk']['comments']     = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
1706                 $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
1707
1708                 $trans['add']['bookmark']      = array( __( 'Your attempt to add this link has failed.' ), false );
1709                 $trans['delete']['bookmark']   = array( __( 'Your attempt to delete this link: &quot;%s&quot; has failed.' ), 'use_id' );
1710                 $trans['update']['bookmark']   = array( __( 'Your attempt to edit this link: &quot;%s&quot; has failed.' ), 'use_id' );
1711                 $trans['bulk']['bookmarks']    = array( __( 'Your attempt to bulk modify links has failed.' ), false );
1712
1713                 $trans['add']['page']          = array( __( 'Your attempt to add this page has failed.' ), false );
1714                 $trans['delete']['page']       = array( __( 'Your attempt to delete this page: &quot;%s&quot; has failed.' ), 'get_the_title' );
1715                 $trans['update']['page']       = array( __( 'Your attempt to edit this page: &quot;%s&quot; has failed.' ), 'get_the_title' );
1716
1717                 $trans['edit']['plugin']       = array( __( 'Your attempt to edit this plugin file: &quot;%s&quot; has failed.' ), 'use_id' );
1718                 $trans['activate']['plugin']   = array( __( 'Your attempt to activate this plugin: &quot;%s&quot; has failed.' ), 'use_id' );
1719                 $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &quot;%s&quot; has failed.' ), 'use_id' );
1720                 $trans['upgrade']['plugin']    = array( __( 'Your attempt to upgrade this plugin: &quot;%s&quot; has failed.' ), 'use_id' );            
1721
1722                 $trans['add']['post']          = array( __( 'Your attempt to add this post has failed.' ), false );
1723                 $trans['delete']['post']       = array( __( 'Your attempt to delete this post: &quot;%s&quot; has failed.' ), 'get_the_title' );
1724                 $trans['update']['post']       = array( __( 'Your attempt to edit this post: &quot;%s&quot; has failed.' ), 'get_the_title' );
1725
1726                 $trans['add']['user']          = array( __( 'Your attempt to add this user has failed.' ), false );
1727                 $trans['delete']['users']      = array( __( 'Your attempt to delete users has failed.' ), false );
1728                 $trans['bulk']['users']        = array( __( 'Your attempt to bulk modify users has failed.' ), false );
1729                 $trans['update']['user']       = array( __( 'Your attempt to edit this user: &quot;%s&quot; has failed.' ), 'get_author_name' );
1730                 $trans['update']['profile']    = array( __( 'Your attempt to modify the profile for: &quot;%s&quot; has failed.' ), 'get_author_name' );
1731
1732                 $trans['update']['options']    = array( __( 'Your attempt to edit your settings has failed.' ), false );
1733                 $trans['update']['permalink']  = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
1734                 $trans['edit']['file']         = array( __( 'Your attempt to edit this file: &quot;%s&quot; has failed.' ), 'use_id' );
1735                 $trans['edit']['theme']        = array( __( 'Your attempt to edit this theme file: &quot;%s&quot; has failed.' ), 'use_id' );
1736                 $trans['switch']['theme']      = array( __( 'Your attempt to switch to this theme: &quot;%s&quot; has failed.' ), 'use_id' );
1737
1738                 if ( isset( $trans[$verb][$noun] ) ) {
1739                         if ( !empty( $trans[$verb][$noun][1] ) ) {
1740                                 $lookup = $trans[$verb][$noun][1];
1741                                 $object = $matches[4];
1742                                 if ( 'use_id' != $lookup )
1743                                         $object = call_user_func( $lookup, $object );
1744                                 return sprintf( $trans[$verb][$noun][0], wp_specialchars($object) );
1745                         } else {
1746                                 return $trans[$verb][$noun][0];
1747                         }
1748                 }
1749         }
1750
1751         return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), $matches[4] );
1752 }
1753
1754
1755 function wp_nonce_ays( $action ) {
1756         $title = __( 'WordPress Failure Notice' );
1757         $html = wp_specialchars( wp_explain_nonce( $action ) ) . '</p>';
1758         if ( wp_get_referer() )
1759                 $html .= "<p><a href='" . remove_query_arg( 'updated', clean_url( wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
1760         wp_die( $html, $title);
1761 }
1762
1763
1764 function wp_die( $message, $title = '' ) {
1765         global $wp_locale;
1766
1767         if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
1768                 if ( empty( $title ) ) {
1769                         $error_data = $message->get_error_data();
1770                         if ( is_array( $error_data ) && isset( $error_data['title'] ) )
1771                                 $title = $error_data['title'];
1772                 }
1773                 $errors = $message->get_error_messages();
1774                 switch ( count( $errors ) ) :
1775                 case 0 :
1776                         $message = '';
1777                         break;
1778                 case 1 :
1779                         $message = "<p>{$errors[0]}</p>";
1780                         break;
1781                 default :
1782                         $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
1783                         break;
1784                 endswitch;
1785         } elseif ( is_string( $message ) ) {
1786                 $message = "<p>$message</p>";
1787         }
1788
1789         if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
1790                 $admin_dir = WP_SITEURL . '/wp-admin/';
1791         elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
1792                 $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
1793         elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
1794                 $admin_dir = '';
1795         else
1796                 $admin_dir = 'wp-admin/';
1797
1798         if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
1799         if( !headers_sent() ){
1800                 status_header( 500 );
1801                 nocache_headers();
1802                 header( 'Content-Type: text/html; charset=utf-8' );
1803         }
1804
1805         if ( empty($title) ) {
1806                 if ( function_exists( '__' ) )
1807                         $title = __( 'WordPress &rsaquo; Error' );
1808                 else
1809                         $title = 'WordPress &rsaquo; Error';
1810         }
1811
1812 ?>
1813 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1814 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
1815 <head>
1816         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1817         <title><?php echo $title ?></title>
1818         <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
1819 <?php
1820 if ( ( $wp_locale ) && ( 'rtl' == $wp_locale->text_direction ) ) : ?>
1821         <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
1822 <?php endif; ?>
1823 </head>
1824 <body id="error-page">
1825 <?php endif; ?>
1826         <?php echo $message; ?>
1827 </body>
1828 </html>
1829 <?php
1830         die();
1831 }
1832
1833
1834 function _config_wp_home( $url = '' ) {
1835         if ( defined( 'WP_HOME' ) )
1836                 return WP_HOME;
1837         return $url;
1838 }
1839
1840
1841 function _config_wp_siteurl( $url = '' ) {
1842         if ( defined( 'WP_SITEURL' ) )
1843                 return WP_SITEURL;
1844         return $url;
1845 }
1846
1847
1848 function _mce_set_direction( $input ) {
1849         global $wp_locale;
1850
1851         if ( 'rtl' == $wp_locale->text_direction ) {
1852                 $input['directionality'] = 'rtl';
1853                 $input['plugins'] .= ',directionality';
1854                 $input['theme_advanced_buttons1'] .= ',ltr';
1855         }
1856
1857         return $input;
1858 }
1859
1860
1861 function smilies_init() {
1862         global $wpsmiliestrans, $wp_smiliessearch, $wp_smiliesreplace;
1863
1864         // don't bother setting up smilies if they are disabled
1865         if ( !get_option( 'use_smilies' ) )
1866                 return;
1867
1868         if ( !isset( $wpsmiliestrans ) ) {
1869                 $wpsmiliestrans = array(
1870                 ':mrgreen:' => 'icon_mrgreen.gif',
1871                 ':neutral:' => 'icon_neutral.gif',
1872                 ':twisted:' => 'icon_twisted.gif',
1873                   ':arrow:' => 'icon_arrow.gif',
1874                   ':shock:' => 'icon_eek.gif',
1875                   ':smile:' => 'icon_smile.gif',
1876                     ':???:' => 'icon_confused.gif',
1877                    ':cool:' => 'icon_cool.gif',
1878                    ':evil:' => 'icon_evil.gif',
1879                    ':grin:' => 'icon_biggrin.gif',
1880                    ':idea:' => 'icon_idea.gif',
1881                    ':oops:' => 'icon_redface.gif',
1882                    ':razz:' => 'icon_razz.gif',
1883                    ':roll:' => 'icon_rolleyes.gif',
1884                    ':wink:' => 'icon_wink.gif',
1885                     ':cry:' => 'icon_cry.gif',
1886                     ':eek:' => 'icon_surprised.gif',
1887                     ':lol:' => 'icon_lol.gif',
1888                     ':mad:' => 'icon_mad.gif',
1889                     ':sad:' => 'icon_sad.gif',
1890                       '8-)' => 'icon_cool.gif',
1891                       '8-O' => 'icon_eek.gif',
1892                       ':-(' => 'icon_sad.gif',
1893                       ':-)' => 'icon_smile.gif',
1894                       ':-?' => 'icon_confused.gif',
1895                       ':-D' => 'icon_biggrin.gif',
1896                       ':-P' => 'icon_razz.gif',
1897                       ':-o' => 'icon_surprised.gif',
1898                       ':-x' => 'icon_mad.gif',
1899                       ':-|' => 'icon_neutral.gif',
1900                       ';-)' => 'icon_wink.gif',
1901                        '8)' => 'icon_cool.gif',
1902                        '8O' => 'icon_eek.gif',
1903                        ':(' => 'icon_sad.gif',
1904                        ':)' => 'icon_smile.gif',
1905                        ':?' => 'icon_confused.gif',
1906                        ':D' => 'icon_biggrin.gif',
1907                        ':P' => 'icon_razz.gif',
1908                        ':o' => 'icon_surprised.gif',
1909                        ':x' => 'icon_mad.gif',
1910                        ':|' => 'icon_neutral.gif',
1911                        ';)' => 'icon_wink.gif',
1912                       ':!:' => 'icon_exclaim.gif',
1913                       ':?:' => 'icon_question.gif',
1914                 );
1915         }
1916
1917         $siteurl = get_option( 'siteurl' );
1918         foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
1919                 $wp_smiliessearch[] = '/(\s|^)' . preg_quote( $smiley, '/' ) . '(\s|$)/';
1920                 $smiley_masked = attribute_escape( trim( $smiley ) );
1921                 $wp_smiliesreplace[] = " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
1922         }
1923 }
1924
1925 /**
1926  * Merge user defined arguments into defaults array.
1927  *
1928  * This function is used throughout WordPress to allow for both string or array
1929  * to be merged into another array.
1930  *
1931  * @since 2.2.0
1932  *
1933  * @param string|array $args Value to merge with $defaults
1934  * @param array $defaults Array that serves as the defaults.
1935  * @return array Merged user defined values with defaults.
1936  */
1937 function wp_parse_args( $args, $defaults = '' ) {
1938         if ( is_object( $args ) )
1939                 $r = get_object_vars( $args );
1940         elseif ( is_array( $args ) )
1941                 $r =& $args;
1942         else
1943                 wp_parse_str( $args, $r );
1944
1945         if ( is_array( $defaults ) )
1946                 return array_merge( $defaults, $r );
1947         return $r;
1948 }
1949
1950 /**
1951  * Determines if Widgets library should be loaded.
1952  *
1953  * Checks to make sure that the widgets library hasn't already been loaded. If
1954  * it hasn't, then it will load the widgets library and run an action hook.
1955  *
1956  * @since 2.2.0
1957  * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
1958  */
1959 function wp_maybe_load_widgets() {
1960         if ( !function_exists( 'dynamic_sidebar' ) ) {
1961                 require_once( ABSPATH . WPINC . '/widgets.php' );
1962                 add_action( '_admin_menu', 'wp_widgets_add_menu' );
1963         }
1964 }
1965
1966 /**
1967  * Append the Widgets menu to the themes main menu.
1968  *
1969  * @since 2.2.0
1970  * @uses $submenu The administration submenu list.
1971  */
1972 function wp_widgets_add_menu() {
1973         global $submenu;
1974         $submenu['themes.php'][7] = array( __( 'Widgets' ), 'switch_themes', 'widgets.php' );
1975         ksort( $submenu['themes.php'], SORT_NUMERIC );
1976 }
1977
1978 /**
1979  * Flush all output buffers for PHP 5.2.
1980  *
1981  * Make sure all output buffers are flushed before our singletons our destroyed.
1982  *
1983  * @since 2.2.0
1984  */
1985 function wp_ob_end_flush_all() {
1986         while ( @ob_end_flush() );
1987 }
1988
1989 /**
1990  * Load the correct database class file.
1991  *
1992  * This function is used to load the database class file either at runtime or by
1993  * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
1994  * defined globally by the inline code in wp-db.php.
1995  *
1996  * @since 2.5
1997  * @global $wpdb WordPress Database Object
1998  */
1999 function require_wp_db() {
2000         global $wpdb;
2001         if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
2002                 require_once( WP_CONTENT_DIR . '/db.php' );
2003         else
2004                 require_once( ABSPATH . WPINC . '/wp-db.php' );
2005 }
2006
2007 /**
2008  * Load custom DB error or display WordPress DB error.
2009  *
2010  * If a file exists in the wp-content directory named db-error.php, then it will
2011  * be loaded instead of displaying the WordPress DB error. If it is not found,
2012  * then the WordPress DB error will be displayed instead.
2013  *
2014  * The WordPress DB error sets the HTTP status header to 500 to try to prevent
2015  * search engines from caching the message. Custom DB messages should do the
2016  * same.
2017  *
2018  * @since 2.5
2019  * @uses $wpdb
2020  */
2021 function dead_db() {
2022         global $wpdb;
2023
2024         // Load custom DB error template, if present.
2025         if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
2026                 require_once( WP_CONTENT_DIR . '/db-error.php' );
2027                 die();
2028         }
2029
2030         // If installing or in the admin, provide the verbose message.
2031         if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
2032                 wp_die($wpdb->error);
2033
2034         // Otherwise, be terse.
2035         status_header( 500 );
2036         nocache_headers();
2037         header( 'Content-Type: text/html; charset=utf-8' );
2038 ?>
2039 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2040 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
2041 <head>
2042 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2043         <title>Database Error</title>
2044
2045 </head>
2046 <body>
2047         <h1>Error establishing a database connection</h1>
2048 </body>
2049 </html>
2050 <?php
2051         die();
2052 }
2053
2054 /**
2055  * Converts value to positive integer.
2056  *
2057  * @since 2.5
2058  * 
2059  * @param mixed $maybeint data you wish to have convered to an absolute integer
2060  * @return int an absolute integer
2061  */
2062 function absint( $maybeint ) {
2063         return abs( intval( $maybeint ) );
2064 }
2065
2066 /**
2067  * Determines if the blog can be accessed over SSL.
2068  *
2069  * Determines if blog can be accessed over SSL by using cURL to access the site
2070  * using the https in the siteurl. Requires cURL extension to work correctly.
2071  *
2072  * @since 2.5
2073  *
2074  * @return bool Whether or not SSL access is available
2075  */
2076 function url_is_accessable_via_ssl($url)
2077 {
2078         if (in_array('curl', get_loaded_extensions())) {
2079                  $ssl = preg_replace( '/^http:\/\//', 'https://',  $url );
2080
2081                  $ch = curl_init();
2082                  curl_setopt($ch, CURLOPT_URL, $ssl);
2083                  curl_setopt($ch, CURLOPT_FAILONERROR, true);
2084                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2085                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
2086
2087                  curl_exec($ch);
2088
2089                  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2090                  curl_close ($ch);
2091
2092                  if ($status == 200 || $status == 401) {
2093                          return true;
2094                  }
2095         }
2096         return false;
2097 }
2098
2099 /**
2100  * Secure URL, if available or the given URL.
2101  *
2102  * @since 2.5
2103  *
2104  * @param string $url Complete URL path with transport.
2105  * @return string Secure or regular URL path.
2106  */
2107 function atom_service_url_filter($url)
2108 {
2109         if ( url_is_accessable_via_ssl($url) )
2110                 return preg_replace( '/^http:\/\//', 'https://',  $url );
2111         else
2112                 return $url;
2113 }
2114
2115 /**
2116  * Marks a function as deprecated and informs when it has been used.
2117  *
2118  * There is a hook deprecated_function_run that will be called that can be used
2119  * to get the backtrace up to what file and function called the deprecated
2120  * function.
2121  *
2122  * The current behavior is to trigger an user error if WP_DEBUG is defined and
2123  * is true.
2124  *
2125  * This function is to be used in every function in depreceated.php
2126  *
2127  * @package WordPress
2128  * @package Debug
2129  * @since 2.5
2130  * @access private
2131  *
2132  * @uses do_action() Calls 'deprecated_function_run' and passes the function name and what to use instead.
2133  * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
2134  *
2135  * @param string $function The function that was called
2136  * @param string $version The version of WordPress that depreceated the function
2137  * @param string $replacement Optional. The function that should have been called
2138  */
2139 function _deprecated_function($function, $version, $replacement=null) {
2140
2141         do_action('deprecated_function_run', $function, $replacement);
2142
2143         // Allow plugin to filter the output error trigger
2144         if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_function_trigger_error', true )) {
2145                 if( !is_null($replacement) )
2146                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2147                 else
2148                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2149         }
2150 }
2151
2152 /**
2153  * Marks a file as deprecated and informs when it has been used.
2154  *
2155  * There is a hook deprecated_file_included that will be called that can be used
2156  * to get the backtrace up to what file and function included the deprecated
2157  * file.
2158  *
2159  * The current behavior is to trigger an user error if WP_DEBUG is defined and
2160  * is true.
2161  *
2162  * This function is to be used in every file that is depreceated
2163  *
2164  * @package WordPress
2165  * @package Debug
2166  * @since 2.5
2167  * @access private
2168  *
2169  * @uses do_action() Calls 'deprecated_file_included' and passes the file name and what to use instead.
2170  * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
2171  *
2172  * @param string $file The file that was included
2173  * @param string $version The version of WordPress that depreceated the function
2174  * @param string $replacement Optional. The function that should have been called
2175  */
2176 function _deprecated_file($file, $version, $replacement=null) {
2177
2178         do_action('deprecated_file_included', $file, $replacement);
2179
2180         // Allow plugin to filter the output error trigger
2181         if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_file_trigger_error', true )) {
2182                 if( !is_null($replacement) )
2183                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) );
2184                 else
2185                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) );
2186         }
2187 }
2188
2189 /**
2190  * Is the server running earlier than 1.5.0 version of lighttpd
2191  *
2192  * @since unknown
2193  *
2194  * @return bool Whether the server is running lighttpd < 1.5.0
2195  */
2196 function is_lighttpd_before_150() {
2197         $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
2198         $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
2199         return  'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
2200 }
2201
2202 /**
2203  * Does the specified module exist in the apache config?
2204  *
2205  * @since unknown
2206  *
2207  * @param string $mod e.g. mod_rewrite
2208  * @param bool $default The default return value if the module is not found
2209  * @return bool
2210  */
2211 function apache_mod_loaded($mod, $default = false) {
2212         global $is_apache;
2213
2214         if ( !$is_apache )
2215                 return false;
2216
2217         if ( function_exists('apache_get_modules') ) {
2218                 $mods = apache_get_modules();
2219                 if ( in_array($mod, $mods) )
2220                         return true;
2221         } elseif ( function_exists('phpinfo') ) {
2222                         ob_start();
2223                         phpinfo(8);
2224                         $phpinfo = ob_get_clean();
2225                         if ( false !== strpos($phpinfo, $mod) )
2226                                 return true;
2227         }
2228         return $default;
2229 }
2230
2231 /**
2232  * File validates against allowed set of defined rules.
2233  *
2234  * A return value of '1' means that the $file contains either '..' or './'. A
2235  * return value of '2' means that the $file contains ':' after the first
2236  * character. A return value of '3' means that the file is not in the allowed
2237  * files list.
2238  *
2239  * @since 2.6
2240  *
2241  * @param string $file File path.
2242  * @param array $allowed_files List of allowed files.
2243  * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
2244  */
2245 function validate_file( $file, $allowed_files = '' ) {
2246         if ( false !== strpos( $file, '..' ))
2247                 return 1;
2248
2249         if ( false !== strpos( $file, './' ))
2250                 return 1;
2251
2252         if (':' == substr( $file, 1, 1 ))
2253                 return 2;
2254
2255         if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
2256                 return 3;
2257
2258         return 0;
2259 }
2260
2261 /**
2262  * Determine if SSL is used.
2263  *
2264  * @since 2.6
2265  *
2266  * @return bool True if SSL, false if not used.
2267  */
2268 function is_ssl() {
2269         return ( isset($_SERVER['HTTPS']) && 'on' == strtolower($_SERVER['HTTPS']) ) ? true : false; 
2270 }
2271
2272 /**
2273  * Whether SSL login should be forced.
2274  *
2275  * @since 2.6
2276  *
2277  * @param string|bool $force Optional.
2278  * @return bool True if forced, false if not forced.
2279  */
2280 function force_ssl_login($force = '') {
2281         static $forced;
2282
2283         if ( '' != $force ) {
2284                 $old_forced = $forced;
2285                 $forced = $force;
2286                 return $old_forced;
2287         }
2288
2289         return $forced;
2290 }
2291
2292 /**
2293  * Whether to force SSL used for the Administration Panels.
2294  *
2295  * @since 2.6
2296  *
2297  * @param string|bool $force
2298  * @return bool True if forced, false if not forced.
2299  */
2300 function force_ssl_admin($force = '') {
2301         static $forced;
2302
2303         if ( '' != $force ) {
2304                 $old_forced = $forced;
2305                 $forced = $force;
2306                 return $old_forced;
2307         }
2308
2309         return $forced;
2310 }
2311
2312 /**
2313  * Guess the URL for the site.
2314  *
2315  * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
2316  * directory.
2317  *
2318  * @since 2.6
2319  *
2320  * @return string
2321  */
2322 function wp_guess_url() {
2323         if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
2324                 $url = WP_SITEURL;
2325         } else {
2326                 $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
2327                 $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
2328         }
2329         return $url;
2330 }
2331
2332 ?>