]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions.php
Wordpress 2.3.2-scripts
[autoinstalls/wordpress.git] / wp-includes / functions.php
1 <?php
2
3 function mysql2date($dateformatstring, $mysqlstring, $translate = true) {
4         global $wp_locale;
5         $m = $mysqlstring;
6         if ( empty($m) ) {
7                 return false;
8         }
9         $i = mktime(
10                 (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
11                 (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
12         );
13
14         if( 'U' == $dateformatstring )
15                 return $i;
16
17         if ( -1 == $i || false == $i )
18                 $i = 0;
19
20         if ( !empty($wp_locale->month) && !empty($wp_locale->weekday) && $translate ) {
21                 $datemonth = $wp_locale->get_month(date('m', $i));
22                 $datemonth_abbrev = $wp_locale->get_month_abbrev($datemonth);
23                 $dateweekday = $wp_locale->get_weekday(date('w', $i));
24                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev($dateweekday);
25                 $datemeridiem = $wp_locale->get_meridiem(date('a', $i));
26                 $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i));
27                 $dateformatstring = ' '.$dateformatstring;
28                 $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
29                 $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
30                 $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
31                 $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
32                 $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring);
33                 $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring);
34
35                 $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
36         }
37         $j = @date($dateformatstring, $i);
38         if ( !$j ) {
39         // for debug purposes
40         //      echo $i." ".$mysqlstring;
41         }
42         return $j;
43 }
44
45 function current_time($type, $gmt = 0) {
46         switch ($type) {
47                 case 'mysql':
48                         if ( $gmt ) $d = gmdate('Y-m-d H:i:s');
49                         else $d = gmdate('Y-m-d H:i:s', (time() + (get_option('gmt_offset') * 3600)));
50                         return $d;
51                         break;
52                 case 'timestamp':
53                         if ( $gmt ) $d = time();
54                         else $d = time() + (get_option('gmt_offset') * 3600);
55                         return $d;
56                         break;
57         }
58 }
59
60 function date_i18n($dateformatstring, $unixtimestamp) {
61         global $wp_locale;
62         $i = $unixtimestamp;
63         if ( (!empty($wp_locale->month)) && (!empty($wp_locale->weekday)) ) {
64                 $datemonth = $wp_locale->get_month(date('m', $i));
65                 $datemonth_abbrev = $wp_locale->get_month_abbrev($datemonth);
66                 $dateweekday = $wp_locale->get_weekday(date('w', $i));
67                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev($dateweekday);
68                 $datemeridiem = $wp_locale->get_meridiem(date('a', $i));
69                 $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i));
70                 $dateformatstring = ' '.$dateformatstring;
71                 $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
72                 $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
73                 $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
74                 $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
75                 $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring);
76                 $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring);
77
78                 $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
79         }
80         $j = @date($dateformatstring, $i);
81         return $j;
82 }
83
84 function number_format_i18n($number, $decimals = null) {
85         global $wp_locale;
86         // let the user override the precision only
87         $decimals = is_null($decimals)? $wp_locale->number_format['decimals'] : intval($decimals);
88
89         return number_format($number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep']);
90 }
91
92 function size_format($bytes, $decimals = null) {
93         // technically the correct unit names for powers of 1024 are KiB, MiB etc
94         // see http://en.wikipedia.org/wiki/Byte
95         $quant = array(
96                 'TB' => pow(1024, 4),
97                 'GB' => pow(1024, 3),
98                 'MB' => pow(1024, 2),
99                 'kB' => pow(1024, 1),
100                 'B'  => pow(1024, 0),
101         );
102
103         foreach ($quant as $unit => $mag)
104                 if ( intval($bytes) >= $mag )
105                         return number_format_i18n($bytes / $mag, $decimals) . ' ' . $unit;
106 }
107
108 function get_weekstartend($mysqlstring, $start_of_week) {
109         $my = substr($mysqlstring,0,4);
110         $mm = substr($mysqlstring,8,2);
111         $md = substr($mysqlstring,5,2);
112         $day = mktime(0,0,0, $md, $mm, $my);
113         $weekday = date('w',$day);
114         $i = 86400;
115
116         if ( $weekday < get_option('start_of_week') )
117                 $weekday = 7 - (get_option('start_of_week') - $weekday);
118
119         while ($weekday > get_option('start_of_week')) {
120                 $weekday = date('w',$day);
121                 if ( $weekday < get_option('start_of_week') )
122                         $weekday = 7 - (get_option('start_of_week') - $weekday);
123
124                 $day = $day - 86400;
125                 $i = 0;
126         }
127         $week['start'] = $day + 86400 - $i;
128         // $week['end'] = $day - $i + 691199;
129         $week['end'] = $week['start'] + 604799;
130         return $week;
131 }
132
133 function maybe_unserialize($original) {
134         if ( is_serialized($original) ) // don't attempt to unserialize data that wasn't serialized going in
135                 if ( false !== $gm = @ unserialize($original) )
136                         return $gm;
137         return $original;
138 }
139
140 function is_serialized($data) {
141         // if it isn't a string, it isn't serialized
142         if ( !is_string($data) )
143                 return false;
144         $data = trim($data);
145         if ( 'N;' == $data )
146                 return true;
147         if ( !preg_match('/^([adObis]):/', $data, $badions) )
148                 return false;
149         switch ( $badions[1] ) :
150         case 'a' :
151         case 'O' :
152         case 's' :
153                 if ( preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data) )
154                         return true;
155                 break;
156         case 'b' :
157         case 'i' :
158         case 'd' :
159                 if ( preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data) )
160                         return true;
161                 break;
162         endswitch;
163         return false;
164 }
165
166 function is_serialized_string($data) {
167         // if it isn't a string, it isn't a serialized string
168         if ( !is_string($data) )
169                 return false;
170         $data = trim($data);
171         if ( preg_match('/^s:[0-9]+:.*;$/s',$data) ) // this should fetch all serialized strings
172                 return true;
173         return false;
174 }
175
176 /* Options functions */
177
178 // expects $setting to already be SQL-escaped
179 function get_option($setting) {
180         global $wpdb;
181
182         // Allow plugins to short-circuit options.
183         $pre = apply_filters( 'pre_option_' . $setting, false );
184         if ( false !== $pre )
185                 return $pre;
186
187         // prevent non-existent options from triggering multiple queries
188         $notoptions = wp_cache_get('notoptions', 'options');
189         if ( isset($notoptions[$setting]) )
190                 return false;
191
192         $alloptions = wp_load_alloptions();
193
194         if ( isset($alloptions[$setting]) ) {
195                 $value = $alloptions[$setting];
196         } else {
197                 $value = wp_cache_get($setting, 'options');
198
199                 if ( false === $value ) {
200                         if ( defined('WP_INSTALLING') )
201                                 $show = $wpdb->hide_errors();
202                         $row = $wpdb->get_row("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1");
203                         if ( defined('WP_INSTALLING') )
204                                 $wpdb->show_errors($show);
205
206                         if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
207                                 $value = $row->option_value;
208                                 wp_cache_add($setting, $value, 'options');
209                         } else { // option does not exist, so we must cache its non-existence
210                                 $notoptions[$setting] = true;
211                                 wp_cache_set('notoptions', $notoptions, 'options');
212                                 return false;
213                         }
214                 }
215         }
216
217         // If home is not set use siteurl.
218         if ( 'home' == $setting && '' == $value )
219                 return get_option('siteurl');
220
221         if ( in_array($setting, array('siteurl', 'home', 'category_base', 'tag_base')) )
222                 $value = untrailingslashit($value);
223
224         return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
225 }
226
227 function wp_protect_special_option($option) {
228         $protected = array('alloptions', 'notoptions');
229         if ( in_array($option, $protected) )
230                 die(sprintf(__('%s is a protected WP option and may not be modified'), wp_specialchars($option)));
231 }
232
233 function form_option($option) {
234         echo attribute_escape(get_option($option));
235 }
236
237 function get_alloptions() {
238         global $wpdb, $wp_queries;
239         $show = $wpdb->hide_errors();
240         if ( !$options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") ) {
241                 $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
242         }
243         $wpdb->show_errors($show);
244
245         foreach ($options as $option) {
246                 // "When trying to design a foolproof system,
247                 //  never underestimate the ingenuity of the fools :)" -- Dougal
248                 if ( 'siteurl' == $option->option_name )
249                         $option->option_value = preg_replace('|/+$|', '', $option->option_value);
250                 if ( 'home' == $option->option_name )
251                         $option->option_value = preg_replace('|/+$|', '', $option->option_value);
252                 if ( 'category_base' == $option->option_name )
253                         $option->option_value = preg_replace('|/+$|', '', $option->option_value);
254                 $value = maybe_unserialize($option->option_value);
255                 $all_options->{$option->option_name} = apply_filters('pre_option_' . $option->option_name, $value);
256         }
257         return apply_filters('all_options', $all_options);
258 }
259
260 function wp_load_alloptions() {
261         global $wpdb;
262
263         $alloptions = wp_cache_get('alloptions', 'options');
264
265         if ( !$alloptions ) {
266                 $show = $wpdb->hide_errors();
267                 if ( !$alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") )
268                         $alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
269                 $wpdb->show_errors($show);
270                 $alloptions = array();
271                 foreach ( (array) $alloptions_db as $o )
272                         $alloptions[$o->option_name] = $o->option_value;
273                 wp_cache_add('alloptions', $alloptions, 'options');
274         }
275         return $alloptions;
276 }
277
278 // expects $option_name to NOT be SQL-escaped
279 function update_option($option_name, $newvalue) {
280         global $wpdb;
281
282         wp_protect_special_option($option_name);
283
284         $safe_option_name = $wpdb->escape($option_name);
285         $newvalue = sanitize_option($option_name, $newvalue);
286
287         if ( is_string($newvalue) )
288                 $newvalue = trim($newvalue);
289
290         // If the new and old values are the same, no need to update.
291         $oldvalue = get_option($safe_option_name);
292         if ( $newvalue === $oldvalue ) {
293                 return false;
294         }
295
296         if ( false === $oldvalue ) {
297                 add_option($option_name, $newvalue);
298                 return true;
299         }
300
301         $notoptions = wp_cache_get('notoptions', 'options');
302         if ( is_array($notoptions) && isset($notoptions[$option_name]) ) {
303                 unset($notoptions[$option_name]);
304                 wp_cache_set('notoptions', $notoptions, 'options');
305         }
306
307         $_newvalue = $newvalue;
308         $newvalue = maybe_serialize($newvalue);
309
310         $alloptions = wp_load_alloptions();
311         if ( isset($alloptions[$option_name]) ) {
312                 $alloptions[$option_name] = $newvalue;
313                 wp_cache_set('alloptions', $alloptions, 'options');
314         } else {
315                 wp_cache_set($option_name, $newvalue, 'options');
316         }
317
318         $newvalue = $wpdb->escape($newvalue);
319         $option_name = $wpdb->escape($option_name);
320         $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
321         if ( $wpdb->rows_affected == 1 ) {
322                 do_action("update_option_{$option_name}", $oldvalue, $_newvalue);
323                 return true;
324         }
325         return false;
326 }
327
328 // thx Alex Stapleton, http://alex.vort-x.net/blog/
329 // expects $name to NOT be SQL-escaped
330 function add_option($name, $value = '', $deprecated = '', $autoload = 'yes') {
331         global $wpdb;
332
333         wp_protect_special_option($name);
334         $safe_name = $wpdb->escape($name);
335
336         // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
337         $notoptions = wp_cache_get('notoptions', 'options');
338         if ( !is_array($notoptions) || !isset($notoptions[$name]) )
339                 if ( false !== get_option($safe_name) )
340                         return;
341
342         $value = maybe_serialize($value);
343         $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
344
345         if ( 'yes' == $autoload ) {
346                 $alloptions = wp_load_alloptions();
347                 $alloptions[$name] = $value;
348                 wp_cache_set('alloptions', $alloptions, 'options');
349         } else {
350                 wp_cache_set($name, $value, 'options');
351         }
352
353         // This option exists now
354         $notoptions = wp_cache_get('notoptions', 'options'); // yes, again... we need it to be fresh
355         if ( is_array($notoptions) && isset($notoptions[$name]) ) {
356                 unset($notoptions[$name]);
357                 wp_cache_set('notoptions', $notoptions, 'options');
358         }
359
360         $name = $wpdb->escape($name);
361         $value = $wpdb->escape($value);
362         $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES ('$name', '$value', '$autoload')");
363
364         return;
365 }
366
367 function delete_option($name) {
368         global $wpdb;
369
370         wp_protect_special_option($name);
371
372         // Get the ID, if no ID then return
373         $option = $wpdb->get_row("SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'");
374         if ( !$option->option_id ) return false;
375         $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
376         if ( 'yes' == $option->autoload ) {
377                 $alloptions = wp_load_alloptions();
378                 if ( isset($alloptions[$name]) ) {
379                         unset($alloptions[$name]);
380                         wp_cache_set('alloptions', $alloptions, 'options');
381                 }
382         } else {
383                 wp_cache_delete($name, 'options');
384         }
385         return true;
386 }
387
388 function maybe_serialize($data) {
389         if ( is_string($data) )
390                 $data = trim($data);
391         elseif ( is_array($data) || is_object($data) )
392                 return serialize($data);
393         if ( is_serialized($data) )
394                 return serialize($data);
395         return $data;
396 }
397
398 function gzip_compression() {
399         if ( !get_option( 'gzipcompression' ) ) {
400                 return false;
401         }
402
403         if ( ( ini_get( 'zlib.output_compression' ) == 'On' || ini_get( 'zlib.output_compression_level' ) > 0 ) || ini_get( 'output_handler' ) == 'ob_gzhandler' ) {
404                 return false;
405         }
406
407         if ( extension_loaded( 'zlib' ) ) {
408                 ob_start( 'ob_gzhandler' );
409         }
410 }
411
412 function make_url_footnote($content) {
413         preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
414         $j = 0;
415         for ($i=0; $i<count($matches[0]); $i++) {
416                 $links_summary = (!$j) ? "\n" : $links_summary;
417                 $j++;
418                 $link_match = $matches[0][$i];
419                 $link_number = '['.($i+1).']';
420                 $link_url = $matches[2][$i];
421                 $link_text = $matches[4][$i];
422                 $content = str_replace($link_match, $link_text.' '.$link_number, $content);
423                 $link_url = ((strtolower(substr($link_url,0,7)) != 'http://') && (strtolower(substr($link_url,0,8)) != 'https://')) ? get_option('home') . $link_url : $link_url;
424                 $links_summary .= "\n".$link_number.' '.$link_url;
425         }
426         $content = strip_tags($content);
427         $content .= $links_summary;
428         return $content;
429 }
430
431
432 function xmlrpc_getposttitle($content) {
433         global $post_default_title;
434         if ( preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle) ) {
435                 $post_title = $matchtitle[0];
436                 $post_title = preg_replace('/<title>/si', '', $post_title);
437                 $post_title = preg_replace('/<\/title>/si', '', $post_title);
438         } else {
439                 $post_title = $post_default_title;
440         }
441         return $post_title;
442 }
443
444 function xmlrpc_getpostcategory($content) {
445         global $post_default_category;
446         if ( preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat) ) {
447                 $post_category = trim($matchcat[1], ',');
448                 $post_category = explode(',', $post_category);
449         } else {
450                 $post_category = $post_default_category;
451         }
452         return $post_category;
453 }
454
455 function xmlrpc_removepostdata($content) {
456         $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
457         $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
458         $content = trim($content);
459         return $content;
460 }
461
462 function debug_fopen($filename, $mode) {
463         global $debug;
464         if ( $debug == 1 ) {
465                 $fp = fopen($filename, $mode);
466                 return $fp;
467         } else {
468                 return false;
469         }
470 }
471
472 function debug_fwrite($fp, $string) {
473         global $debug;
474         if ( $debug == 1 ) {
475                 fwrite($fp, $string);
476         }
477 }
478
479 function debug_fclose($fp) {
480         global $debug;
481         if ( $debug == 1 ) {
482                 fclose($fp);
483         }
484 }
485
486 function do_enclose( $content, $post_ID ) {
487         global $wp_version, $wpdb;
488         include_once (ABSPATH . WPINC . '/class-IXR.php');
489
490         $log = debug_fopen(ABSPATH . 'enclosures.log', 'a');
491         $post_links = array();
492         debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
493
494         $pung = get_enclosed( $post_ID );
495
496         $ltrs = '\w';
497         $gunk = '/#~:.?+=&%@!\-';
498         $punc = '.:?\-';
499         $any = $ltrs . $gunk . $punc;
500
501         preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
502
503         debug_fwrite($log, 'Post contents:');
504         debug_fwrite($log, $content."\n");
505
506         foreach($post_links_temp[0] as $link_test) :
507                 if ( !in_array($link_test, $pung) ) : // If we haven't pung it already
508                         $test = parse_url($link_test);
509                         if ( isset($test['query']) )
510                                 $post_links[] = $link_test;
511                         elseif (($test['path'] != '/') && ($test['path'] != ''))
512                                 $post_links[] = $link_test;
513                 endif;
514         endforeach;
515
516         foreach ($post_links as $url) :
517                 if ( $url != '' && !$wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE post_id = '$post_ID' AND meta_key = 'enclosure' AND meta_value LIKE ('$url%')") ) {
518                         if ( $headers = wp_get_http_headers( $url) ) {
519                                 $len = (int) $headers['content-length'];
520                                 $type = $wpdb->escape( $headers['content-type'] );
521                                 $allowed_types = array( 'video', 'audio' );
522                                 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
523                                         $meta_value = "$url\n$len\n$type\n";
524                                         $wpdb->query( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
525                                         VALUES ( '$post_ID', 'enclosure' , '$meta_value')" );
526                                 }
527                         }
528                 }
529         endforeach;
530 }
531
532 function wp_get_http_headers( $url, $red = 1 ) {
533         global $wp_version;
534         @set_time_limit( 60 );
535
536         if ( $red > 5 )
537                  return false;
538
539         $parts = parse_url( $url );
540         $file = $parts['path'] . ($parts['query'] ? '?'.$parts['query'] : '');
541         $host = $parts['host'];
542         if ( !isset( $parts['port'] ) )
543                 $parts['port'] = 80;
544
545         $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
546
547         $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
548         if ( !$fp )
549                 return false;
550
551         $response = '';
552         fputs( $fp, $head );
553         while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
554                 $response .= fgets( $fp, 2048 );
555         fclose( $fp );
556         preg_match_all('/(.*?): (.*)\r/', $response, $matches);
557         $count = count($matches[1]);
558         for ( $i = 0; $i < $count; $i++) {
559                 $key = strtolower($matches[1][$i]);
560                 $headers["$key"] = $matches[2][$i];
561         }
562
563         preg_match('/.*([0-9]{3}).*/', $response, $return);
564         $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
565
566                 $code = $headers['response'];
567                 if ( ('302' == $code || '301' == $code) && isset($headers['location']) )
568                                 return wp_get_http_headers( $headers['location'], ++$red );
569
570         return $headers;
571 }
572
573 function is_new_day() {
574         global $day, $previousday;
575         if ( $day != $previousday ) {
576                 return(1);
577         } else {
578                 return(0);
579         }
580 }
581
582 function build_query($data) {
583         return _http_build_query($data, NULL, '&', '', false);
584 }
585
586 /*
587 add_query_arg: Returns a modified querystring by adding
588 a single key & value or an associative array.
589 Setting a key value to emptystring removes the key.
590 Omitting oldquery_or_uri uses the $_SERVER value.
591
592 Parameters:
593 add_query_arg(newkey, newvalue, oldquery_or_uri) or
594 add_query_arg(associative_array, oldquery_or_uri)
595 */
596 function add_query_arg() {
597         $ret = '';
598         if ( is_array(func_get_arg(0)) ) {
599                 if ( @func_num_args() < 2 || false === @func_get_arg(1) )
600                         $uri = $_SERVER['REQUEST_URI'];
601                 else
602                         $uri = @func_get_arg(1);
603         } else {
604                 if ( @func_num_args() < 3 || false === @func_get_arg(2) )
605                         $uri = $_SERVER['REQUEST_URI'];
606                 else
607                         $uri = @func_get_arg(2);
608         }
609
610         if ( $frag = strstr($uri, '#') )
611                 $uri = substr($uri, 0, -strlen($frag));
612         else
613                 $frag = '';
614
615         if ( preg_match('|^https?://|i', $uri, $matches) ) {
616                 $protocol = $matches[0];
617                 $uri = substr($uri, strlen($protocol));
618         } else {
619                 $protocol = '';
620         }
621
622         if (strpos($uri, '?') !== false) {
623                 $parts = explode('?', $uri, 2);
624                 if ( 1 == count($parts) ) {
625                         $base = '?';
626                         $query = $parts[0];
627                 } else {
628                         $base = $parts[0] . '?';
629                         $query = $parts[1];
630                 }
631         } elseif (!empty($protocol) || strpos($uri, '=') === false ) {
632                 $base = $uri . '?';
633                 $query = '';
634         } else {
635                 $base = '';
636                 $query = $uri;
637         }
638
639         wp_parse_str($query, $qs);
640         $qs = urlencode_deep($qs); // this re-URL-encodes things that were already in the query string
641         if ( is_array(func_get_arg(0)) ) {
642                 $kayvees = func_get_arg(0);
643                 $qs = array_merge($qs, $kayvees);
644         } else {
645                 $qs[func_get_arg(0)] = func_get_arg(1);
646         }
647
648         foreach ( $qs as $k => $v ) {
649                 if ( $v === false )
650                         unset($qs[$k]);
651         }
652
653         $ret = build_query($qs);
654         $ret = trim($ret, '?');
655         $ret = preg_replace('#=(&|$)#', '$1', $ret);
656         $ret = $protocol . $base . $ret . $frag;
657         $ret = rtrim($ret, '?');
658         return $ret;
659 }
660
661 /*
662 remove_query_arg: Returns a modified querystring by removing
663 a single key or an array of keys.
664 Omitting oldquery_or_uri uses the $_SERVER value.
665
666 Parameters:
667 remove_query_arg(removekey, [oldquery_or_uri]) or
668 remove_query_arg(removekeyarray, [oldquery_or_uri])
669 */
670
671 function remove_query_arg($key, $query=FALSE) {
672         if ( is_array($key) ) { // removing multiple keys
673                 foreach ( (array) $key as $k )
674                         $query = add_query_arg($k, FALSE, $query);
675                 return $query;
676         }
677         return add_query_arg($key, FALSE, $query);
678 }
679
680 function add_magic_quotes($array) {
681         global $wpdb;
682
683         foreach ($array as $k => $v) {
684                 if ( is_array($v) ) {
685                         $array[$k] = add_magic_quotes($v);
686                 } else {
687                         $array[$k] = $wpdb->escape($v);
688                 }
689         }
690         return $array;
691 }
692
693 function wp_remote_fopen( $uri ) {
694         $timeout = 10;
695         $parsed_url = @parse_url($uri);
696
697         if ( !$parsed_url || !is_array($parsed_url) )
698                 return false;
699
700         if ( !isset($parsed_url['scheme']) || !in_array($parsed_url['scheme'], array('http','https')) )
701                 $uri = 'http://' . $uri;
702
703         if ( ini_get('allow_url_fopen') ) {
704                 $fp = @fopen( $uri, 'r' );
705                 if ( !$fp )
706                         return false;
707
708                 //stream_set_timeout($fp, $timeout); // Requires php 4.3
709                 $linea = '';
710                 while( $remote_read = fread($fp, 4096) )
711                         $linea .= $remote_read;
712                 fclose($fp);
713                 return $linea;
714         } else if ( function_exists('curl_init') ) {
715                 $handle = curl_init();
716                 curl_setopt ($handle, CURLOPT_URL, $uri);
717                 curl_setopt ($handle, CURLOPT_CONNECTTIMEOUT, 1);
718                 curl_setopt ($handle, CURLOPT_RETURNTRANSFER, 1);
719                 curl_setopt ($handle, CURLOPT_TIMEOUT, $timeout);
720                 $buffer = curl_exec($handle);
721                 curl_close($handle);
722                 return $buffer;
723         } else {
724                 return false;
725         }
726 }
727
728 function wp($query_vars = '') {
729         global $wp, $wp_query, $wp_the_query;
730
731         $wp->main($query_vars);
732
733         if( !isset($wp_the_query) )
734                 $wp_the_query = $wp_query;
735 }
736
737 function get_status_header_desc( $code ) {
738         global $wp_header_to_desc;
739
740         $code = (int) $code;
741
742         if ( !isset($wp_header_to_desc) ) {
743                 $wp_header_to_desc = array(
744                         100 => 'Continue',
745                         101 => 'Switching Protocols',
746
747                         200 => 'OK',
748                         201 => 'Created',
749                         202 => 'Accepted',
750                         203 => 'Non-Authoritative Information',
751                         204 => 'No Content',
752                         205 => 'Reset Content',
753                         206 => 'Partial Content',
754
755                         300 => 'Multiple Choices',
756                         301 => 'Moved Permanently',
757                         302 => 'Found',
758                         303 => 'See Other',
759                         304 => 'Not Modified',
760                         305 => 'Use Proxy',
761                         307 => 'Temporary Redirect',
762
763                         400 => 'Bad Request',
764                         401 => 'Unauthorized',
765                         403 => 'Forbidden',
766                         404 => 'Not Found',
767                         405 => 'Method Not Allowed',
768                         406 => 'Not Acceptable',
769                         407 => 'Proxy Authentication Required',
770                         408 => 'Request Timeout',
771                         409 => 'Conflict',
772                         410 => 'Gone',
773                         411 => 'Length Required',
774                         412 => 'Precondition Failed',
775                         413 => 'Request Entity Too Large',
776                         414 => 'Request-URI Too Long',
777                         415 => 'Unsupported Media Type',
778                         416 => 'Requested Range Not Satisfiable',
779                         417 => 'Expectation Failed',
780
781                         500 => 'Internal Server Error',
782                         501 => 'Not Implemented',
783                         502 => 'Bad Gateway',
784                         503 => 'Service Unavailable',
785                         504 => 'Gateway Timeout',
786                         505 => 'HTTP Version Not Supported'
787                 );
788         }
789
790         if ( isset( $wp_header_to_desc[$code] ) ) {
791                 return $wp_header_to_desc[$code];
792         } else {
793                 return '';
794         }
795 }
796
797 function status_header( $header ) {
798         $text = get_status_header_desc( $header );
799
800         if ( empty( $text ) )
801                 return false;
802
803         $protocol = $_SERVER["SERVER_PROTOCOL"];
804         if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
805                 $protocol = 'HTTP/1.0';
806         $status_header = "$protocol $header $text";
807         if ( function_exists('apply_filters') )
808                 $status_header = apply_filters('status_header', $status_header, $header, $text, $protocol);
809
810         if ( version_compare( phpversion(), '4.3.0', '>=' ) ) {
811                 return @header( $status_header, true, $header );
812         } else {
813                 return @header( $status_header );
814         }
815 }
816
817 function nocache_headers() {
818         @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
819         @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
820         @ header('Cache-Control: no-cache, must-revalidate, max-age=0');
821         @ header('Pragma: no-cache');
822 }
823
824 function cache_javascript_headers() {
825         $expiresOffset = 864000; // 10 days
826         header("Content-Type: text/javascript; charset=" . get_bloginfo('charset'));
827         header("Vary: Accept-Encoding"); // Handle proxies
828         header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
829 }
830
831 function get_num_queries() {
832         global $wpdb;
833         return $wpdb->num_queries;
834 }
835
836 function bool_from_yn( $yn ) {
837         return ( strtolower( $yn ) == 'y' );
838 }
839
840 function do_feed() {
841         global $wp_query;
842
843         $feed = get_query_var('feed');
844
845         // Remove the pad, if present.
846         $feed = preg_replace('/^_+/', '', $feed);
847
848         if ( $feed == '' || $feed == 'feed' )
849                 $feed = 'rss2';
850
851         $hook = 'do_feed_' . $feed;
852         do_action($hook, $wp_query->is_comment_feed);
853 }
854
855 function do_feed_rdf() {
856         load_template(ABSPATH . WPINC . '/feed-rdf.php');
857 }
858
859 function do_feed_rss() {
860         load_template(ABSPATH . WPINC . '/feed-rss.php');
861 }
862
863 function do_feed_rss2($for_comments) {
864         if ( $for_comments ) {
865                 load_template(ABSPATH . WPINC . '/feed-rss2-comments.php');
866         } else {
867                 load_template(ABSPATH . WPINC . '/feed-rss2.php');
868         }
869 }
870
871 function do_feed_atom($for_comments) {
872         if ($for_comments) {
873                 load_template(ABSPATH . WPINC . '/feed-atom-comments.php');
874         } else {
875                 load_template(ABSPATH . WPINC . '/feed-atom.php');
876         }
877 }
878
879 function do_robots() {
880         header('Content-Type: text/plain; charset=utf-8');
881
882         do_action('do_robotstxt');
883
884         if ( '0' == get_option('blog_public') ) {
885                 echo "User-agent: *\n";
886                 echo "Disallow: /\n";
887         } else {
888                 echo "User-agent: *\n";
889                 echo "Disallow:\n";
890         }
891 }
892
893 function is_blog_installed() {
894         global $wpdb;
895         $show = $wpdb->hide_errors();
896         $installed = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'");
897         $wpdb->show_errors($show);
898
899         $install_status = !empty( $installed ) ? TRUE : FALSE;
900         return $install_status;
901 }
902
903 function wp_nonce_url($actionurl, $action = -1) {
904         $actionurl = str_replace('&amp;', '&', $actionurl);
905         return wp_specialchars(add_query_arg('_wpnonce', wp_create_nonce($action), $actionurl));
906 }
907
908 function wp_nonce_field($action = -1, $name = "_wpnonce", $referer = true) {
909         $name = attribute_escape($name);
910         echo '<input type="hidden" name="' . $name . '" value="' . wp_create_nonce($action) . '" />';
911         if ( $referer )
912                 wp_referer_field();
913 }
914
915 function wp_referer_field() {
916         $ref = attribute_escape($_SERVER['REQUEST_URI']);
917         echo '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
918         if ( wp_get_original_referer() ) {
919                 $original_ref = attribute_escape(stripslashes(wp_get_original_referer()));
920                 echo '<input type="hidden" name="_wp_original_http_referer" value="'. $original_ref . '" />';
921         }
922 }
923
924 function wp_original_referer_field() {
925         echo '<input type="hidden" name="_wp_original_http_referer" value="' . attribute_escape(stripslashes($_SERVER['REQUEST_URI'])) . '" />';
926 }
927
928 function wp_get_referer() {
929         foreach ( array($_REQUEST['_wp_http_referer'], $_SERVER['HTTP_REFERER']) as $ref )
930                 if ( !empty($ref) )
931                         return $ref;
932         return false;
933 }
934
935 function wp_get_original_referer() {
936         if ( !empty($_REQUEST['_wp_original_http_referer']) )
937                 return $_REQUEST['_wp_original_http_referer'];
938         return false;
939 }
940
941 function wp_mkdir_p($target) {
942         // from php.net/mkdir user contributed notes
943         if (file_exists($target)) {
944                 if (! @ is_dir($target))
945                         return false;
946                 else
947                         return true;
948         }
949
950         // Attempting to create the directory may clutter up our display.
951         if (@ mkdir($target)) {
952                 $stat = @ stat(dirname($target));
953                 $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
954                 @ chmod($target, $dir_perms);
955                 return true;
956         } else {
957                 if ( is_dir(dirname($target)) )
958                         return false;
959         }
960
961         // If the above failed, attempt to create the parent node, then try again.
962         if (wp_mkdir_p(dirname($target)))
963                 return wp_mkdir_p($target);
964
965         return false;
966 }
967
968 // Returns an array containing the current upload directory's path and url, or an error message.
969 function wp_upload_dir() {
970         $siteurl = get_option('siteurl');
971         //prepend ABSPATH to $dir and $siteurl to $url if they're not already there
972         $path = str_replace(ABSPATH, '', trim(get_option('upload_path')));
973         $dir = ABSPATH . $path;
974         $url = trailingslashit($siteurl) . $path;
975
976         if ( $dir == ABSPATH ) { //the option was empty
977                 $dir = ABSPATH . 'wp-content/uploads';
978         }
979
980         if ( defined('UPLOADS') ) {
981                 $dir = ABSPATH . UPLOADS;
982                 $url = trailingslashit($siteurl) . UPLOADS;
983         }
984
985         if ( get_option('uploads_use_yearmonth_folders')) {
986                 // Generate the yearly and monthly dirs
987                 $time = current_time( 'mysql' );
988                 $y = substr( $time, 0, 4 );
989                 $m = substr( $time, 5, 2 );
990                 $dir = $dir . "/$y/$m";
991                 $url = $url . "/$y/$m";
992         }
993
994         // Make sure we have an uploads dir
995         if ( ! wp_mkdir_p( $dir ) ) {
996                 $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir);
997                 return array('error' => $message);
998         }
999
1000                 $uploads = array('path' => $dir, 'url' => $url, 'error' => false);
1001         return apply_filters('upload_dir', $uploads);
1002 }
1003
1004 function wp_upload_bits($name, $type, $bits) {
1005         if ( empty($name) )
1006                 return array('error' => __("Empty filename"));
1007
1008         $wp_filetype = wp_check_filetype($name);
1009         if ( !$wp_filetype['ext'] )
1010                 return array('error' => __("Invalid file type"));
1011
1012         $upload = wp_upload_dir();
1013
1014         if ( $upload['error'] !== false )
1015                 return $upload;
1016
1017         $number = '';
1018         $filename = $name;
1019         $path_parts = pathinfo($filename);
1020         $ext = $path_parts['extension'];
1021         if ( empty($ext) )
1022                 $ext = '';
1023         else
1024                 $ext = ".$ext";
1025         while ( file_exists($upload['path'] . "/$filename") ) {
1026                 if ( '' == "$number$ext" )
1027                         $filename = $filename . ++$number . $ext;
1028                 else
1029                         $filename = str_replace("$number$ext", ++$number . $ext, $filename);
1030         }
1031
1032         $new_file = $upload['path'] . "/$filename";
1033         if ( ! wp_mkdir_p( dirname($new_file) ) ) {
1034                 $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), dirname($new_file));
1035                 return array('error' => $message);
1036         }
1037
1038         $ifp = @ fopen($new_file, 'wb');
1039         if ( ! $ifp )
1040                 return array('error' => sprintf(__('Could not write file %s'), $new_file));
1041
1042         $success = @ fwrite($ifp, $bits);
1043         fclose($ifp);
1044         // Set correct file permissions
1045         $stat = @ stat(dirname($new_file));
1046         $perms = $stat['mode'] & 0007777;
1047         $perms = $perms & 0000666;
1048         @ chmod($new_file, $perms);
1049
1050         // Compute the URL
1051         $url = $upload['url'] . "/$filename";
1052
1053         return array('file' => $new_file, 'url' => $url, 'error' => false);
1054 }
1055
1056 function wp_check_filetype($filename, $mimes = null) {
1057         // Accepted MIME types are set here as PCRE unless provided.
1058         $mimes = is_array($mimes) ? $mimes : apply_filters('upload_mimes', array (
1059                 'jpg|jpeg|jpe' => 'image/jpeg',
1060                 'gif' => 'image/gif',
1061                 'png' => 'image/png',
1062                 'bmp' => 'image/bmp',
1063                 'tif|tiff' => 'image/tiff',
1064                 'ico' => 'image/x-icon',
1065                 'asf|asx|wax|wmv|wmx' => 'video/asf',
1066                 'avi' => 'video/avi',
1067                 'mov|qt' => 'video/quicktime',
1068                 'mpeg|mpg|mpe' => 'video/mpeg',
1069                 'txt|c|cc|h' => 'text/plain',
1070                 'rtx' => 'text/richtext',
1071                 'css' => 'text/css',
1072                 'htm|html' => 'text/html',
1073                 'mp3|mp4' => 'audio/mpeg',
1074                 'ra|ram' => 'audio/x-realaudio',
1075                 'wav' => 'audio/wav',
1076                 'ogg' => 'audio/ogg',
1077                 'mid|midi' => 'audio/midi',
1078                 'wma' => 'audio/wma',
1079                 'rtf' => 'application/rtf',
1080                 'js' => 'application/javascript',
1081                 'pdf' => 'application/pdf',
1082                 'doc' => 'application/msword',
1083                 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
1084                 'wri' => 'application/vnd.ms-write',
1085                 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
1086                 'mdb' => 'application/vnd.ms-access',
1087                 'mpp' => 'application/vnd.ms-project',
1088                 'swf' => 'application/x-shockwave-flash',
1089                 'class' => 'application/java',
1090                 'tar' => 'application/x-tar',
1091                 'zip' => 'application/zip',
1092                 'gz|gzip' => 'application/x-gzip',
1093                 'exe' => 'application/x-msdownload',
1094                 // openoffice formats
1095                 'odt' => 'application/vnd.oasis.opendocument.text',
1096                 'odp' => 'application/vnd.oasis.opendocument.presentation',
1097                 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1098                 'odg' => 'application/vnd.oasis.opendocument.graphics',
1099                 'odc' => 'application/vnd.oasis.opendocument.chart',
1100                 'odb' => 'application/vnd.oasis.opendocument.database',
1101                 'odf' => 'application/vnd.oasis.opendocument.formula',
1102
1103         ));
1104
1105         $type = false;
1106         $ext = false;
1107
1108         foreach ($mimes as $ext_preg => $mime_match) {
1109                 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1110                 if ( preg_match($ext_preg, $filename, $ext_matches) ) {
1111                         $type = $mime_match;
1112                         $ext = $ext_matches[1];
1113                         break;
1114                 }
1115         }
1116
1117         return compact('ext', 'type');
1118 }
1119
1120 function wp_explain_nonce($action) {
1121         if ( $action !== -1 && preg_match('/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches) ) {
1122                 $verb = $matches[1];
1123                 $noun = $matches[2];
1124
1125                 $trans = array();
1126                 $trans['update']['attachment'] = array(__('Are you sure you want to edit this attachment: &quot;%s&quot;?'), 'get_the_title');
1127
1128                 $trans['add']['category'] = array(__('Are you sure you want to add this category?'), false);
1129                 $trans['delete']['category'] = array(__('Are you sure you want to delete this category: &quot;%s&quot;?'), 'get_catname');
1130                 $trans['update']['category'] = array(__('Are you sure you want to edit this category: &quot;%s&quot;?'), 'get_catname');
1131
1132                 $trans['delete']['comment'] = array(__('Are you sure you want to delete this comment: &quot;%s&quot;?'), 'use_id');
1133                 $trans['unapprove']['comment'] = array(__('Are you sure you want to unapprove this comment: &quot;%s&quot;?'), 'use_id');
1134                 $trans['approve']['comment'] = array(__('Are you sure you want to approve this comment: &quot;%s&quot;?'), 'use_id');
1135                 $trans['update']['comment'] = array(__('Are you sure you want to edit this comment: &quot;%s&quot;?'), 'use_id');
1136                 $trans['bulk']['comments'] = array(__('Are you sure you want to bulk modify comments?'), false);
1137                 $trans['moderate']['comments'] = array(__('Are you sure you want to moderate comments?'), false);
1138
1139                 $trans['add']['bookmark'] = array(__('Are you sure you want to add this link?'), false);
1140                 $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this link: &quot;%s&quot;?'), 'use_id');
1141                 $trans['update']['bookmark'] = array(__('Are you sure you want to edit this link: &quot;%s&quot;?'), 'use_id');
1142                 $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify links?'), false);
1143
1144                 $trans['add']['page'] = array(__('Are you sure you want to add this page?'), false);
1145                 $trans['delete']['page'] = array(__('Are you sure you want to delete this page: &quot;%s&quot;?'), 'get_the_title');
1146                 $trans['update']['page'] = array(__('Are you sure you want to edit this page: &quot;%s&quot;?'), 'get_the_title');
1147
1148                 $trans['edit']['plugin'] = array(__('Are you sure you want to edit this plugin file: &quot;%s&quot;?'), 'use_id');
1149                 $trans['activate']['plugin'] = array(__('Are you sure you want to activate this plugin: &quot;%s&quot;?'), 'use_id');
1150                 $trans['deactivate']['plugin'] = array(__('Are you sure you want to deactivate this plugin: &quot;%s&quot;?'), 'use_id');
1151
1152                 $trans['add']['post'] = array(__('Are you sure you want to add this post?'), false);
1153                 $trans['delete']['post'] = array(__('Are you sure you want to delete this post: &quot;%s&quot;?'), 'get_the_title');
1154                 $trans['update']['post'] = array(__('Are you sure you want to edit this post: &quot;%s&quot;?'), 'get_the_title');
1155
1156                 $trans['add']['user'] = array(__('Are you sure you want to add this user?'), false);
1157                 $trans['delete']['users'] = array(__('Are you sure you want to delete users?'), false);
1158                 $trans['bulk']['users'] = array(__('Are you sure you want to bulk modify users?'), false);
1159                 $trans['update']['user'] = array(__('Are you sure you want to edit this user: &quot;%s&quot;?'), 'get_author_name');
1160                 $trans['update']['profile'] = array(__('Are you sure you want to modify the profile for: &quot;%s&quot;?'), 'get_author_name');
1161
1162                 $trans['update']['options'] = array(__('Are you sure you want to edit your settings?'), false);
1163                 $trans['update']['permalink'] = array(__('Are you sure you want to change your permalink structure to: %s?'), 'use_id');
1164                 $trans['edit']['file'] = array(__('Are you sure you want to edit this file: &quot;%s&quot;?'), 'use_id');
1165                 $trans['edit']['theme'] = array(__('Are you sure you want to edit this theme file: &quot;%s&quot;?'), 'use_id');
1166                 $trans['switch']['theme'] = array(__('Are you sure you want to switch to this theme: &quot;%s&quot;?'), 'use_id');
1167
1168                 if ( isset($trans[$verb][$noun]) ) {
1169                         if ( !empty($trans[$verb][$noun][1]) ) {
1170                                 $lookup = $trans[$verb][$noun][1];
1171                                 $object = $matches[4];
1172                                 if ( 'use_id' != $lookup )
1173                                         $object = call_user_func($lookup, $object);
1174                                 return sprintf($trans[$verb][$noun][0], $object);
1175                         } else {
1176                                 return $trans[$verb][$noun][0];
1177                         }
1178                 }
1179         }
1180
1181         return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __('Are you sure you want to do this?'), $matches[4] );
1182 }
1183
1184 function wp_nonce_ays($action) {
1185         global $pagenow, $menu, $submenu, $parent_file, $submenu_file;
1186
1187         $adminurl = get_option('siteurl') . '/wp-admin';
1188         if ( wp_get_referer() )
1189                 $adminurl = clean_url(wp_get_referer());
1190
1191         $title = __('WordPress Confirmation');
1192         // Remove extra layer of slashes.
1193         $_POST   = stripslashes_deep($_POST  );
1194         if ( $_POST ) {
1195                 $q = http_build_query($_POST);
1196                 $q = explode( ini_get('arg_separator.output'), $q);
1197                 $html .= "\t<form method='post' action='" . attribute_escape($pagenow) . "'>\n";
1198                 foreach ( (array) $q as $a ) {
1199                         $v = substr(strstr($a, '='), 1);
1200                         $k = substr($a, 0, -(strlen($v)+1));
1201                         $html .= "\t\t<input type='hidden' name='" . attribute_escape(urldecode($k)) . "' value='" . attribute_escape(urldecode($v)) . "' />\n";
1202                 }
1203                 $html .= "\t\t<input type='hidden' name='_wpnonce' value='" . wp_create_nonce($action) . "' />\n";
1204                 $html .= "\t\t<div id='message' class='confirm fade'>\n\t\t<p>" . wp_specialchars(wp_explain_nonce($action)) . "</p>\n\t\t<p><a href='$adminurl'>" . __('No') . "</a> <input type='submit' value='" . __('Yes') . "' /></p>\n\t\t</div>\n\t</form>\n";
1205         } else {
1206                 $html .= "\t<div id='message' class='confirm fade'>\n\t<p>" . wp_specialchars(wp_explain_nonce($action)) . "</p>\n\t<p><a href='$adminurl'>" . __('No') . "</a> <a href='" . clean_url(add_query_arg( '_wpnonce', wp_create_nonce($action), $_SERVER['REQUEST_URI'] )) . "'>" . __('Yes') . "</a></p>\n\t</div>\n";
1207         }
1208         $html .= "</body>\n</html>";
1209         wp_die($html, $title);
1210 }
1211
1212 function wp_die( $message, $title = '' ) {
1213         global $wp_locale;
1214
1215         if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
1216                 if ( empty($title) ) {
1217                         $error_data = $message->get_error_data();
1218                         if ( is_array($error_data) && isset($error_data['title']) )
1219                                 $title = $error_data['title'];
1220                 }
1221                 $errors = $message->get_error_messages();
1222                 switch ( count($errors) ) :
1223                 case 0 :
1224                         $message = '';
1225                         break;
1226                 case 1 :
1227                         $message = "<p>{$errors[0]}</p>";
1228                         break;
1229                 default :
1230                         $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
1231                         break;
1232                 endswitch;
1233         } elseif ( is_string($message) ) {
1234                 $message = "<p>$message</p>";
1235         }
1236
1237         if ( defined('WP_SITEURL') && '' != WP_SITEURL ) 
1238                 $admin_dir = WP_SITEURL.'/wp-admin/'; 
1239         elseif (function_exists('get_bloginfo') && '' != get_bloginfo('wpurl'))
1240                 $admin_dir = get_bloginfo('wpurl').'/wp-admin/'; 
1241         elseif (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false)
1242                 $admin_dir = '';
1243         else
1244                 $admin_dir = 'wp-admin/';
1245
1246         if ( !function_exists('did_action') || !did_action('admin_head') ) :
1247         if( !headers_sent() ){
1248                 status_header(500);
1249                 nocache_headers();
1250                 header('Content-Type: text/html; charset=utf-8');
1251         }
1252
1253         if ( empty($title) ){
1254                 if( function_exists('__') )
1255                         $title = __('WordPress &rsaquo; Error');
1256                 else
1257                         $title = 'WordPress &rsaquo; Error';
1258         }
1259
1260 ?>
1261 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1262 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists('language_attributes') ) language_attributes(); ?>>
1263 <head>
1264         <title><?php echo $title ?></title>
1265         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1266         <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
1267 <?php
1268 if ( ( $wp_locale ) && ('rtl' == $wp_locale->text_direction) ) : ?>
1269         <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
1270 <?php endif; ?>
1271 </head>
1272 <body>
1273 <?php endif; ?>
1274         <h1 id="logo"><img alt="WordPress" src="<?php echo $admin_dir; ?>images/wordpress-logo.png" /></h1>
1275         <?php echo $message; ?>
1276
1277 </body>
1278 </html>
1279 <?php
1280         die();
1281 }
1282
1283 function _config_wp_home($url = '') {
1284         if ( defined( 'WP_HOME' ) )
1285                 return WP_HOME;
1286         else return $url;
1287 }
1288
1289 function _config_wp_siteurl($url = '') {
1290         if ( defined( 'WP_SITEURL' ) )
1291                 return WP_SITEURL;
1292         else return $url;
1293 }
1294
1295 function _mce_set_direction() {
1296         global $wp_locale;
1297
1298         if ('rtl' == $wp_locale->text_direction) {
1299                 echo 'directionality : "rtl" ,';
1300                 echo 'theme_advanced_toolbar_align : "right" ,';
1301         }
1302 }
1303
1304 function _mce_load_rtl_plugin($input) {
1305         global $wp_locale;
1306
1307         if ('rtl' == $wp_locale->text_direction)
1308                 $input[] = 'directionality';
1309
1310         return $input;
1311 }
1312
1313 function _mce_add_direction_buttons($input) {
1314         global $wp_locale;
1315
1316         if ('rtl' == $wp_locale->text_direction) {
1317                 $new_buttons = array('separator', 'ltr', 'rtl');
1318                 $input = array_merge($input, $new_buttons);
1319         }
1320
1321         return $input;
1322 }
1323
1324 function smilies_init() {
1325         global $wpsmiliestrans, $wp_smiliessearch, $wp_smiliesreplace;
1326
1327         // don't bother setting up smilies if they are disabled
1328         if ( !get_option('use_smilies') )
1329                 return;
1330
1331         if (!isset($wpsmiliestrans)) {
1332                 $wpsmiliestrans = array(
1333                 ':mrgreen:' => 'icon_mrgreen.gif',
1334                 ':neutral:' => 'icon_neutral.gif',
1335                 ':twisted:' => 'icon_twisted.gif',
1336                   ':arrow:' => 'icon_arrow.gif',
1337                   ':shock:' => 'icon_eek.gif',
1338                   ':smile:' => 'icon_smile.gif',
1339                     ':???:' => 'icon_confused.gif',
1340                    ':cool:' => 'icon_cool.gif',
1341                    ':evil:' => 'icon_evil.gif',
1342                    ':grin:' => 'icon_biggrin.gif',
1343                    ':idea:' => 'icon_idea.gif',
1344                    ':oops:' => 'icon_redface.gif',
1345                    ':razz:' => 'icon_razz.gif',
1346                    ':roll:' => 'icon_rolleyes.gif',
1347                    ':wink:' => 'icon_wink.gif',
1348                     ':cry:' => 'icon_cry.gif',
1349                     ':eek:' => 'icon_surprised.gif',
1350                     ':lol:' => 'icon_lol.gif',
1351                     ':mad:' => 'icon_mad.gif',
1352                     ':sad:' => 'icon_sad.gif',
1353                       '8-)' => 'icon_cool.gif',
1354                       '8-O' => 'icon_eek.gif',
1355                       ':-(' => 'icon_sad.gif',
1356                       ':-)' => 'icon_smile.gif',
1357                       ':-?' => 'icon_confused.gif',
1358                       ':-D' => 'icon_biggrin.gif',
1359                       ':-P' => 'icon_razz.gif',
1360                       ':-o' => 'icon_surprised.gif',
1361                       ':-x' => 'icon_mad.gif',
1362                       ':-|' => 'icon_neutral.gif',
1363                       ';-)' => 'icon_wink.gif',
1364                        '8)' => 'icon_cool.gif',
1365                        '8O' => 'icon_eek.gif',
1366                        ':(' => 'icon_sad.gif',
1367                        ':)' => 'icon_smile.gif',
1368                        ':?' => 'icon_confused.gif',
1369                        ':D' => 'icon_biggrin.gif',
1370                        ':P' => 'icon_razz.gif',
1371                        ':o' => 'icon_surprised.gif',
1372                        ':x' => 'icon_mad.gif',
1373                        ':|' => 'icon_neutral.gif',
1374                        ';)' => 'icon_wink.gif',
1375                       ':!:' => 'icon_exclaim.gif',
1376                       ':?:' => 'icon_question.gif',
1377                 );
1378         }
1379
1380         $siteurl = get_option('siteurl');
1381         foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
1382                 $wp_smiliessearch[] = '/(\s|^)'.preg_quote($smiley, '/').'(\s|$)/';
1383                 $smiley_masked = htmlspecialchars(trim($smiley), ENT_QUOTES);
1384                 $wp_smiliesreplace[] = " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
1385         }
1386 }
1387
1388 function wp_parse_args( $args, $defaults = '' ) {
1389         if ( is_object($args) )
1390                 $r = get_object_vars($args);
1391         else if ( is_array( $args ) )
1392                 $r =& $args;
1393         else
1394                 wp_parse_str( $args, $r );
1395
1396         if ( is_array( $defaults ) )
1397                 return array_merge( $defaults, $r );
1398         else
1399                 return $r;
1400 }
1401
1402 function wp_maybe_load_widgets() {
1403         if ( !function_exists( 'dynamic_sidebar' ) ) {
1404                 require_once ABSPATH . WPINC . '/widgets.php';
1405                 add_action( '_admin_menu', 'wp_widgets_add_menu' );
1406         }
1407 }
1408
1409 function wp_widgets_add_menu() {
1410         global $submenu;
1411         $submenu['themes.php'][7] = array( __( 'Widgets' ), 'switch_themes', 'widgets.php' );
1412         ksort($submenu['themes.php'], SORT_NUMERIC);
1413 }
1414
1415 // For PHP 5.2, make sure all output buffers are flushed
1416 // before our singletons our destroyed.
1417 function wp_ob_end_flush_all()
1418 {
1419         while ( @ob_end_flush() );
1420 }
1421
1422 function dead_db() {
1423         global $wpdb;
1424
1425         // Load custom DB error template, if present.
1426         if ( file_exists( ABSPATH . 'wp-content/db-error.php' ) ) {
1427                 require_once( ABSPATH . 'wp-content/db-error.php' );
1428                 die();
1429         }
1430
1431         // If installing or in the admin, provide the verbose message.
1432         if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
1433                 wp_die($wpdb->error);
1434
1435         // Otherwise, be terse.
1436         status_header( 500 );
1437         nocache_headers();
1438         header( 'Content-Type: text/html; charset=utf-8' );
1439 ?>
1440 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1441 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
1442 <head>
1443         <title>Database Error</title>
1444         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1445 </head>
1446 <body>
1447         <h1>Error establishing a database connection</h1>
1448 </body>
1449 </html>
1450 <?php
1451         die();
1452 }
1453
1454 ?>