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