]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions.php
Wordpress 3.5.2
[autoinstalls/wordpress.git] / wp-includes / functions.php
1 <?php
2 /**
3  * Main WordPress API
4  *
5  * @package WordPress
6  */
7
8 require( ABSPATH . WPINC . '/option.php' );
9
10 /**
11  * Converts given date string into a different format.
12  *
13  * $format should be either a PHP date format string, e.g. 'U' for a Unix
14  * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
15  *
16  * If $translate is true then the given date and format string will
17  * be passed to date_i18n() for translation.
18  *
19  * @since 0.71
20  *
21  * @param string $format Format of the date to return.
22  * @param string $date Date string to convert.
23  * @param bool $translate Whether the return date should be translated. Default is true.
24  * @return string|int Formatted date string, or Unix timestamp.
25  */
26 function mysql2date( $format, $date, $translate = true ) {
27         if ( empty( $date ) )
28                 return false;
29
30         if ( 'G' == $format )
31                 return strtotime( $date . ' +0000' );
32
33         $i = strtotime( $date );
34
35         if ( 'U' == $format )
36                 return $i;
37
38         if ( $translate )
39                 return date_i18n( $format, $i );
40         else
41                 return date( $format, $i );
42 }
43
44 /**
45  * Retrieve the current time based on specified type.
46  *
47  * The 'mysql' type will return the time in the format for MySQL DATETIME field.
48  * The 'timestamp' type will return the current timestamp.
49  *
50  * If $gmt is set to either '1' or 'true', then both types will use GMT time.
51  * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
52  *
53  * @since 1.0.0
54  *
55  * @param string $type Either 'mysql' or 'timestamp'.
56  * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
57  * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
58  */
59 function current_time( $type, $gmt = 0 ) {
60         switch ( $type ) {
61                 case 'mysql':
62                         return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
63                         break;
64                 case 'timestamp':
65                         return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
66                         break;
67         }
68 }
69
70 /**
71  * Retrieve the date in localized format, based on timestamp.
72  *
73  * If the locale specifies the locale month and weekday, then the locale will
74  * take over the format for the date. If it isn't, then the date format string
75  * will be used instead.
76  *
77  * @since 0.71
78  *
79  * @param string $dateformatstring Format to display the date.
80  * @param int $unixtimestamp Optional. Unix timestamp.
81  * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
82  * @return string The date, translated if locale specifies it.
83  */
84 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
85         global $wp_locale;
86         $i = $unixtimestamp;
87
88         if ( false === $i ) {
89                 if ( ! $gmt )
90                         $i = current_time( 'timestamp' );
91                 else
92                         $i = time();
93                 // we should not let date() interfere with our
94                 // specially computed timestamp
95                 $gmt = true;
96         }
97
98         // store original value for language with untypical grammars
99         // see http://core.trac.wordpress.org/ticket/9396
100         $req_format = $dateformatstring;
101
102         $datefunc = $gmt? 'gmdate' : 'date';
103
104         if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
105                 $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
106                 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
107                 $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
108                 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
109                 $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
110                 $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
111                 $dateformatstring = ' '.$dateformatstring;
112                 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
113                 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
114                 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
115                 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
116                 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
117                 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
118
119                 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
120         }
121         $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
122         $timezone_formats_re = implode( '|', $timezone_formats );
123         if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
124                 $timezone_string = get_option( 'timezone_string' );
125                 if ( $timezone_string ) {
126                         $timezone_object = timezone_open( $timezone_string );
127                         $date_object = date_create( null, $timezone_object );
128                         foreach( $timezone_formats as $timezone_format ) {
129                                 if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
130                                         $formatted = date_format( $date_object, $timezone_format );
131                                         $dateformatstring = ' '.$dateformatstring;
132                                         $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
133                                         $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
134                                 }
135                         }
136                 }
137         }
138         $j = @$datefunc( $dateformatstring, $i );
139         // allow plugins to redo this entirely for languages with untypical grammars
140         $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
141         return $j;
142 }
143
144 /**
145  * Convert integer number to format based on the locale.
146  *
147  * @since 2.3.0
148  *
149  * @param int $number The number to convert based on locale.
150  * @param int $decimals Precision of the number of decimal places.
151  * @return string Converted number in string format.
152  */
153 function number_format_i18n( $number, $decimals = 0 ) {
154         global $wp_locale;
155         $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
156         return apply_filters( 'number_format_i18n', $formatted );
157 }
158
159 /**
160  * Convert number of bytes largest unit bytes will fit into.
161  *
162  * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
163  * number of bytes to human readable number by taking the number of that unit
164  * that the bytes will go into it. Supports TB value.
165  *
166  * Please note that integers in PHP are limited to 32 bits, unless they are on
167  * 64 bit architecture, then they have 64 bit size. If you need to place the
168  * larger size then what PHP integer type will hold, then use a string. It will
169  * be converted to a double, which should always have 64 bit length.
170  *
171  * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
172  * @link http://en.wikipedia.org/wiki/Byte
173  *
174  * @since 2.3.0
175  *
176  * @param int|string $bytes Number of bytes. Note max integer size for integers.
177  * @param int $decimals Precision of number of decimal places. Deprecated.
178  * @return bool|string False on failure. Number string on success.
179  */
180 function size_format( $bytes, $decimals = 0 ) {
181         $quant = array(
182                 // ========================= Origin ====
183                 'TB' => 1099511627776,  // pow( 1024, 4)
184                 'GB' => 1073741824,     // pow( 1024, 3)
185                 'MB' => 1048576,        // pow( 1024, 2)
186                 'kB' => 1024,           // pow( 1024, 1)
187                 'B ' => 1,              // pow( 1024, 0)
188         );
189         foreach ( $quant as $unit => $mag )
190                 if ( doubleval($bytes) >= $mag )
191                         return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
192
193         return false;
194 }
195
196 /**
197  * Get the week start and end from the datetime or date string from mysql.
198  *
199  * @since 0.71
200  *
201  * @param string $mysqlstring Date or datetime field type from mysql.
202  * @param int $start_of_week Optional. Start of the week as an integer.
203  * @return array Keys are 'start' and 'end'.
204  */
205 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
206         $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
207         $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
208         $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
209         $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
210         $weekday = date( 'w', $day ); // The day of the week from the timestamp
211         if ( !is_numeric($start_of_week) )
212                 $start_of_week = get_option( 'start_of_week' );
213
214         if ( $weekday < $start_of_week )
215                 $weekday += 7;
216
217         $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
218         $end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
219         return compact( 'start', 'end' );
220 }
221
222 /**
223  * Unserialize value only if it was serialized.
224  *
225  * @since 2.0.0
226  *
227  * @param string $original Maybe unserialized original, if is needed.
228  * @return mixed Unserialized data can be any type.
229  */
230 function maybe_unserialize( $original ) {
231         if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
232                 return @unserialize( $original );
233         return $original;
234 }
235
236 /**
237  * Check value to find if it was serialized.
238  *
239  * If $data is not an string, then returned value will always be false.
240  * Serialized data is always a string.
241  *
242  * @since 2.0.5
243  *
244  * @param mixed $data Value to check to see if was serialized.
245  * @return bool False if not serialized and true if it was.
246  */
247 function is_serialized( $data ) {
248         // if it isn't a string, it isn't serialized
249         if ( ! is_string( $data ) )
250                 return false;
251         $data = trim( $data );
252         if ( 'N;' == $data )
253                 return true;
254         $length = strlen( $data );
255         if ( $length < 4 )
256                 return false;
257         if ( ':' !== $data[1] )
258                 return false;
259         $lastc = $data[$length-1];
260         if ( ';' !== $lastc && '}' !== $lastc )
261                 return false;
262         $token = $data[0];
263         switch ( $token ) {
264                 case 's' :
265                         if ( '"' !== $data[$length-2] )
266                                 return false;
267                 case 'a' :
268                 case 'O' :
269                         return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
270                 case 'b' :
271                 case 'i' :
272                 case 'd' :
273                         return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
274         }
275         return false;
276 }
277
278 /**
279  * Check whether serialized data is of string type.
280  *
281  * @since 2.0.5
282  *
283  * @param mixed $data Serialized data
284  * @return bool False if not a serialized string, true if it is.
285  */
286 function is_serialized_string( $data ) {
287         // if it isn't a string, it isn't a serialized string
288         if ( !is_string( $data ) )
289                 return false;
290         $data = trim( $data );
291         $length = strlen( $data );
292         if ( $length < 4 )
293                 return false;
294         elseif ( ':' !== $data[1] )
295                 return false;
296         elseif ( ';' !== $data[$length-1] )
297                 return false;
298         elseif ( $data[0] !== 's' )
299                 return false;
300         elseif ( '"' !== $data[$length-2] )
301                 return false;
302         else
303                 return true;
304 }
305
306 /**
307  * Serialize data, if needed.
308  *
309  * @since 2.0.5
310  *
311  * @param mixed $data Data that might be serialized.
312  * @return mixed A scalar data
313  */
314 function maybe_serialize( $data ) {
315         if ( is_array( $data ) || is_object( $data ) )
316                 return serialize( $data );
317
318         // Double serialization is required for backward compatibility.
319         // See http://core.trac.wordpress.org/ticket/12930
320         if ( is_serialized( $data ) )
321                 return serialize( $data );
322
323         return $data;
324 }
325
326 /**
327  * Retrieve post title from XMLRPC XML.
328  *
329  * If the title element is not part of the XML, then the default post title from
330  * the $post_default_title will be used instead.
331  *
332  * @package WordPress
333  * @subpackage XMLRPC
334  * @since 0.71
335  *
336  * @global string $post_default_title Default XMLRPC post title.
337  *
338  * @param string $content XMLRPC XML Request content
339  * @return string Post title
340  */
341 function xmlrpc_getposttitle( $content ) {
342         global $post_default_title;
343         if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
344                 $post_title = $matchtitle[1];
345         } else {
346                 $post_title = $post_default_title;
347         }
348         return $post_title;
349 }
350
351 /**
352  * Retrieve the post category or categories from XMLRPC XML.
353  *
354  * If the category element is not found, then the default post category will be
355  * used. The return type then would be what $post_default_category. If the
356  * category is found, then it will always be an array.
357  *
358  * @package WordPress
359  * @subpackage XMLRPC
360  * @since 0.71
361  *
362  * @global string $post_default_category Default XMLRPC post category.
363  *
364  * @param string $content XMLRPC XML Request content
365  * @return string|array List of categories or category name.
366  */
367 function xmlrpc_getpostcategory( $content ) {
368         global $post_default_category;
369         if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
370                 $post_category = trim( $matchcat[1], ',' );
371                 $post_category = explode( ',', $post_category );
372         } else {
373                 $post_category = $post_default_category;
374         }
375         return $post_category;
376 }
377
378 /**
379  * XMLRPC XML content without title and category elements.
380  *
381  * @package WordPress
382  * @subpackage XMLRPC
383  * @since 0.71
384  *
385  * @param string $content XMLRPC XML Request content
386  * @return string XMLRPC XML Request content without title and category elements.
387  */
388 function xmlrpc_removepostdata( $content ) {
389         $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
390         $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
391         $content = trim( $content );
392         return $content;
393 }
394
395 /**
396  * Check content for video and audio links to add as enclosures.
397  *
398  * Will not add enclosures that have already been added and will
399  * remove enclosures that are no longer in the post. This is called as
400  * pingbacks and trackbacks.
401  *
402  * @package WordPress
403  * @since 1.5.0
404  *
405  * @uses $wpdb
406  *
407  * @param string $content Post Content
408  * @param int $post_ID Post ID
409  */
410 function do_enclose( $content, $post_ID ) {
411         global $wpdb;
412
413         //TODO: Tidy this ghetto code up and make the debug code optional
414         include_once( ABSPATH . WPINC . '/class-IXR.php' );
415
416         $post_links = array();
417
418         $pung = get_enclosed( $post_ID );
419
420         $ltrs = '\w';
421         $gunk = '/#~:.?+=&%@!\-';
422         $punc = '.:?\-';
423         $any = $ltrs . $gunk . $punc;
424
425         preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
426
427         foreach ( $pung as $link_test ) {
428                 if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
429                         $mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
430                         foreach ( $mids as $mid )
431                                 delete_metadata_by_mid( 'post', $mid );
432                 }
433         }
434
435         foreach ( (array) $post_links_temp[0] as $link_test ) {
436                 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
437                         $test = @parse_url( $link_test );
438                         if ( false === $test )
439                                 continue;
440                         if ( isset( $test['query'] ) )
441                                 $post_links[] = $link_test;
442                         elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
443                                 $post_links[] = $link_test;
444                 }
445         }
446
447         foreach ( (array) $post_links as $url ) {
448                 if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
449
450                         if ( $headers = wp_get_http_headers( $url) ) {
451                                 $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
452                                 $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
453                                 $allowed_types = array( 'video', 'audio' );
454
455                                 // Check to see if we can figure out the mime type from
456                                 // the extension
457                                 $url_parts = @parse_url( $url );
458                                 if ( false !== $url_parts ) {
459                                         $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
460                                         if ( !empty( $extension ) ) {
461                                                 foreach ( wp_get_mime_types() as $exts => $mime ) {
462                                                         if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
463                                                                 $type = $mime;
464                                                                 break;
465                                                         }
466                                                 }
467                                         }
468                                 }
469
470                                 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
471                                         add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
472                                 }
473                         }
474                 }
475         }
476 }
477
478 /**
479  * Perform a HTTP HEAD or GET request.
480  *
481  * If $file_path is a writable filename, this will do a GET request and write
482  * the file to that path.
483  *
484  * @since 2.5.0
485  *
486  * @param string $url URL to fetch.
487  * @param string|bool $file_path Optional. File path to write request to.
488  * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
489  * @return bool|string False on failure and string of headers if HEAD request.
490  */
491 function wp_get_http( $url, $file_path = false, $red = 1 ) {
492         @set_time_limit( 60 );
493
494         if ( $red > 5 )
495                 return false;
496
497         $options = array();
498         $options['redirection'] = 5;
499         $options['reject_unsafe_urls'] = true;
500
501         if ( false == $file_path )
502                 $options['method'] = 'HEAD';
503         else
504                 $options['method'] = 'GET';
505
506         $response = wp_remote_request($url, $options);
507
508         if ( is_wp_error( $response ) )
509                 return false;
510
511         $headers = wp_remote_retrieve_headers( $response );
512         $headers['response'] = wp_remote_retrieve_response_code( $response );
513
514         // WP_HTTP no longer follows redirects for HEAD requests.
515         if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
516                 return wp_get_http( $headers['location'], $file_path, ++$red );
517         }
518
519         if ( false == $file_path )
520                 return $headers;
521
522         // GET request - write it to the supplied filename
523         $out_fp = fopen($file_path, 'w');
524         if ( !$out_fp )
525                 return $headers;
526
527         fwrite( $out_fp,  wp_remote_retrieve_body( $response ) );
528         fclose($out_fp);
529         clearstatcache();
530
531         return $headers;
532 }
533
534 /**
535  * Retrieve HTTP Headers from URL.
536  *
537  * @since 1.5.1
538  *
539  * @param string $url
540  * @param bool $deprecated Not Used.
541  * @return bool|string False on failure, headers on success.
542  */
543 function wp_get_http_headers( $url, $deprecated = false ) {
544         if ( !empty( $deprecated ) )
545                 _deprecated_argument( __FUNCTION__, '2.7' );
546
547         $response = wp_remote_head( $url, array( 'reject_unsafe_urls' => true ) );
548
549         if ( is_wp_error( $response ) )
550                 return false;
551
552         return wp_remote_retrieve_headers( $response );
553 }
554
555 /**
556  * Whether today is a new day.
557  *
558  * @since 0.71
559  * @uses $day Today
560  * @uses $previousday Previous day
561  *
562  * @return int 1 when new day, 0 if not a new day.
563  */
564 function is_new_day() {
565         global $currentday, $previousday;
566         if ( $currentday != $previousday )
567                 return 1;
568         else
569                 return 0;
570 }
571
572 /**
573  * Build URL query based on an associative and, or indexed array.
574  *
575  * This is a convenient function for easily building url queries. It sets the
576  * separator to '&' and uses _http_build_query() function.
577  *
578  * @see _http_build_query() Used to build the query
579  * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
580  *              http_build_query() does.
581  *
582  * @since 2.3.0
583  *
584  * @param array $data URL-encode key/value pairs.
585  * @return string URL encoded string
586  */
587 function build_query( $data ) {
588         return _http_build_query( $data, null, '&', '', false );
589 }
590
591 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
592 function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
593         $ret = array();
594
595         foreach ( (array) $data as $k => $v ) {
596                 if ( $urlencode)
597                         $k = urlencode($k);
598                 if ( is_int($k) && $prefix != null )
599                         $k = $prefix.$k;
600                 if ( !empty($key) )
601                         $k = $key . '%5B' . $k . '%5D';
602                 if ( $v === null )
603                         continue;
604                 elseif ( $v === FALSE )
605                         $v = '0';
606
607                 if ( is_array($v) || is_object($v) )
608                         array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
609                 elseif ( $urlencode )
610                         array_push($ret, $k.'='.urlencode($v));
611                 else
612                         array_push($ret, $k.'='.$v);
613         }
614
615         if ( null === $sep )
616                 $sep = ini_get('arg_separator.output');
617
618         return implode($sep, $ret);
619 }
620
621 /**
622  * Retrieve a modified URL query string.
623  *
624  * You can rebuild the URL and append a new query variable to the URL query by
625  * using this function. You can also retrieve the full URL with query data.
626  *
627  * Adding a single key & value or an associative array. Setting a key value to
628  * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
629  * value. Additional values provided are expected to be encoded appropriately
630  * with urlencode() or rawurlencode().
631  *
632  * @since 1.5.0
633  *
634  * @param mixed $param1 Either newkey or an associative_array
635  * @param mixed $param2 Either newvalue or oldquery or uri
636  * @param mixed $param3 Optional. Old query or uri
637  * @return string New URL query string.
638  */
639 function add_query_arg() {
640         $ret = '';
641         $args = func_get_args();
642         if ( is_array( $args[0] ) ) {
643                 if ( count( $args ) < 2 || false === $args[1] )
644                         $uri = $_SERVER['REQUEST_URI'];
645                 else
646                         $uri = $args[1];
647         } else {
648                 if ( count( $args ) < 3 || false === $args[2] )
649                         $uri = $_SERVER['REQUEST_URI'];
650                 else
651                         $uri = $args[2];
652         }
653
654         if ( $frag = strstr( $uri, '#' ) )
655                 $uri = substr( $uri, 0, -strlen( $frag ) );
656         else
657                 $frag = '';
658
659         if ( 0 === stripos( $uri, 'http://' ) ) {
660                 $protocol = 'http://';
661                 $uri = substr( $uri, 7 );
662         } elseif ( 0 === stripos( $uri, 'https://' ) ) {
663                 $protocol = 'https://';
664                 $uri = substr( $uri, 8 );
665         } else {
666                 $protocol = '';
667         }
668
669         if ( strpos( $uri, '?' ) !== false ) {
670                 $parts = explode( '?', $uri, 2 );
671                 if ( 1 == count( $parts ) ) {
672                         $base = '?';
673                         $query = $parts[0];
674                 } else {
675                         $base = $parts[0] . '?';
676                         $query = $parts[1];
677                 }
678         } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
679                 $base = $uri . '?';
680                 $query = '';
681         } else {
682                 $base = '';
683                 $query = $uri;
684         }
685
686         wp_parse_str( $query, $qs );
687         $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
688         if ( is_array( $args[0] ) ) {
689                 $kayvees = $args[0];
690                 $qs = array_merge( $qs, $kayvees );
691         } else {
692                 $qs[ $args[0] ] = $args[1];
693         }
694
695         foreach ( $qs as $k => $v ) {
696                 if ( $v === false )
697                         unset( $qs[$k] );
698         }
699
700         $ret = build_query( $qs );
701         $ret = trim( $ret, '?' );
702         $ret = preg_replace( '#=(&|$)#', '$1', $ret );
703         $ret = $protocol . $base . $ret . $frag;
704         $ret = rtrim( $ret, '?' );
705         return $ret;
706 }
707
708 /**
709  * Removes an item or list from the query string.
710  *
711  * @since 1.5.0
712  *
713  * @param string|array $key Query key or keys to remove.
714  * @param bool $query When false uses the $_SERVER value.
715  * @return string New URL query string.
716  */
717 function remove_query_arg( $key, $query=false ) {
718         if ( is_array( $key ) ) { // removing multiple keys
719                 foreach ( $key as $k )
720                         $query = add_query_arg( $k, false, $query );
721                 return $query;
722         }
723         return add_query_arg( $key, false, $query );
724 }
725
726 /**
727  * Walks the array while sanitizing the contents.
728  *
729  * @since 0.71
730  *
731  * @param array $array Array to used to walk while sanitizing contents.
732  * @return array Sanitized $array.
733  */
734 function add_magic_quotes( $array ) {
735         foreach ( (array) $array as $k => $v ) {
736                 if ( is_array( $v ) ) {
737                         $array[$k] = add_magic_quotes( $v );
738                 } else {
739                         $array[$k] = addslashes( $v );
740                 }
741         }
742         return $array;
743 }
744
745 /**
746  * HTTP request for URI to retrieve content.
747  *
748  * @since 1.5.1
749  * @uses wp_remote_get()
750  *
751  * @param string $uri URI/URL of web page to retrieve.
752  * @return bool|string HTTP content. False on failure.
753  */
754 function wp_remote_fopen( $uri ) {
755         $parsed_url = @parse_url( $uri );
756
757         if ( !$parsed_url || !is_array( $parsed_url ) )
758                 return false;
759
760         $options = array();
761         $options['timeout'] = 10;
762         $options['reject_unsafe_urls'] = true;
763
764         $response = wp_remote_get( $uri, $options );
765
766         if ( is_wp_error( $response ) )
767                 return false;
768
769         return wp_remote_retrieve_body( $response );
770 }
771
772 /**
773  * Set up the WordPress query.
774  *
775  * @since 2.0.0
776  *
777  * @param string $query_vars Default WP_Query arguments.
778  */
779 function wp( $query_vars = '' ) {
780         global $wp, $wp_query, $wp_the_query;
781         $wp->main( $query_vars );
782
783         if ( !isset($wp_the_query) )
784                 $wp_the_query = $wp_query;
785 }
786
787 /**
788  * Retrieve the description for the HTTP status.
789  *
790  * @since 2.3.0
791  *
792  * @param int $code HTTP status code.
793  * @return string Empty string if not found, or description if found.
794  */
795 function get_status_header_desc( $code ) {
796         global $wp_header_to_desc;
797
798         $code = absint( $code );
799
800         if ( !isset( $wp_header_to_desc ) ) {
801                 $wp_header_to_desc = array(
802                         100 => 'Continue',
803                         101 => 'Switching Protocols',
804                         102 => 'Processing',
805
806                         200 => 'OK',
807                         201 => 'Created',
808                         202 => 'Accepted',
809                         203 => 'Non-Authoritative Information',
810                         204 => 'No Content',
811                         205 => 'Reset Content',
812                         206 => 'Partial Content',
813                         207 => 'Multi-Status',
814                         226 => 'IM Used',
815
816                         300 => 'Multiple Choices',
817                         301 => 'Moved Permanently',
818                         302 => 'Found',
819                         303 => 'See Other',
820                         304 => 'Not Modified',
821                         305 => 'Use Proxy',
822                         306 => 'Reserved',
823                         307 => 'Temporary Redirect',
824
825                         400 => 'Bad Request',
826                         401 => 'Unauthorized',
827                         402 => 'Payment Required',
828                         403 => 'Forbidden',
829                         404 => 'Not Found',
830                         405 => 'Method Not Allowed',
831                         406 => 'Not Acceptable',
832                         407 => 'Proxy Authentication Required',
833                         408 => 'Request Timeout',
834                         409 => 'Conflict',
835                         410 => 'Gone',
836                         411 => 'Length Required',
837                         412 => 'Precondition Failed',
838                         413 => 'Request Entity Too Large',
839                         414 => 'Request-URI Too Long',
840                         415 => 'Unsupported Media Type',
841                         416 => 'Requested Range Not Satisfiable',
842                         417 => 'Expectation Failed',
843                         422 => 'Unprocessable Entity',
844                         423 => 'Locked',
845                         424 => 'Failed Dependency',
846                         426 => 'Upgrade Required',
847
848                         500 => 'Internal Server Error',
849                         501 => 'Not Implemented',
850                         502 => 'Bad Gateway',
851                         503 => 'Service Unavailable',
852                         504 => 'Gateway Timeout',
853                         505 => 'HTTP Version Not Supported',
854                         506 => 'Variant Also Negotiates',
855                         507 => 'Insufficient Storage',
856                         510 => 'Not Extended'
857                 );
858         }
859
860         if ( isset( $wp_header_to_desc[$code] ) )
861                 return $wp_header_to_desc[$code];
862         else
863                 return '';
864 }
865
866 /**
867  * Set HTTP status header.
868  *
869  * @since 2.0.0
870  * @uses apply_filters() Calls 'status_header' on status header string, HTTP
871  *              HTTP code, HTTP code description, and protocol string as separate
872  *              parameters.
873  *
874  * @param int $header HTTP status code
875  * @return unknown
876  */
877 function status_header( $header ) {
878         $text = get_status_header_desc( $header );
879
880         if ( empty( $text ) )
881                 return false;
882
883         $protocol = $_SERVER["SERVER_PROTOCOL"];
884         if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
885                 $protocol = 'HTTP/1.0';
886         $status_header = "$protocol $header $text";
887         if ( function_exists( 'apply_filters' ) )
888                 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
889
890         return @header( $status_header, true, $header );
891 }
892
893 /**
894  * Gets the header information to prevent caching.
895  *
896  * The several different headers cover the different ways cache prevention is handled
897  * by different browsers
898  *
899  * @since 2.8.0
900  *
901  * @uses apply_filters()
902  * @return array The associative array of header names and field values.
903  */
904 function wp_get_nocache_headers() {
905         $headers = array(
906                 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
907                 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
908                 'Pragma' => 'no-cache',
909         );
910
911         if ( function_exists('apply_filters') ) {
912                 $headers = (array) apply_filters('nocache_headers', $headers);
913         }
914         $headers['Last-Modified'] = false;
915         return $headers;
916 }
917
918 /**
919  * Sets the headers to prevent caching for the different browsers.
920  *
921  * Different browsers support different nocache headers, so several headers must
922  * be sent so that all of them get the point that no caching should occur.
923  *
924  * @since 2.0.0
925  * @uses wp_get_nocache_headers()
926  */
927 function nocache_headers() {
928         $headers = wp_get_nocache_headers();
929
930         unset( $headers['Last-Modified'] );
931
932         // In PHP 5.3+, make sure we are not sending a Last-Modified header.
933         if ( function_exists( 'header_remove' ) ) {
934                 @header_remove( 'Last-Modified' );
935         } else {
936                 // In PHP 5.2, send an empty Last-Modified header, but only as a
937                 // last resort to override a header already sent. #WP23021
938                 foreach ( headers_list() as $header ) {
939                         if ( 0 === stripos( $header, 'Last-Modified' ) ) {
940                                 $headers['Last-Modified'] = '';
941                                 break;
942                         }
943                 }
944         }
945
946         foreach( $headers as $name => $field_value )
947                 @header("{$name}: {$field_value}");
948 }
949
950 /**
951  * Set the headers for caching for 10 days with JavaScript content type.
952  *
953  * @since 2.1.0
954  */
955 function cache_javascript_headers() {
956         $expiresOffset = 10 * DAY_IN_SECONDS;
957         header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
958         header( "Vary: Accept-Encoding" ); // Handle proxies
959         header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
960 }
961
962 /**
963  * Retrieve the number of database queries during the WordPress execution.
964  *
965  * @since 2.0.0
966  *
967  * @return int Number of database queries
968  */
969 function get_num_queries() {
970         global $wpdb;
971         return $wpdb->num_queries;
972 }
973
974 /**
975  * Whether input is yes or no. Must be 'y' to be true.
976  *
977  * @since 1.0.0
978  *
979  * @param string $yn Character string containing either 'y' or 'n'
980  * @return bool True if yes, false on anything else
981  */
982 function bool_from_yn( $yn ) {
983         return ( strtolower( $yn ) == 'y' );
984 }
985
986 /**
987  * Loads the feed template from the use of an action hook.
988  *
989  * If the feed action does not have a hook, then the function will die with a
990  * message telling the visitor that the feed is not valid.
991  *
992  * It is better to only have one hook for each feed.
993  *
994  * @since 2.1.0
995  * @uses $wp_query Used to tell if the use a comment feed.
996  * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
997  */
998 function do_feed() {
999         global $wp_query;
1000
1001         $feed = get_query_var( 'feed' );
1002
1003         // Remove the pad, if present.
1004         $feed = preg_replace( '/^_+/', '', $feed );
1005
1006         if ( $feed == '' || $feed == 'feed' )
1007                 $feed = get_default_feed();
1008
1009         $hook = 'do_feed_' . $feed;
1010         if ( !has_action($hook) ) {
1011                 $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
1012                 wp_die( $message, '', array( 'response' => 404 ) );
1013         }
1014
1015         do_action( $hook, $wp_query->is_comment_feed );
1016 }
1017
1018 /**
1019  * Load the RDF RSS 0.91 Feed template.
1020  *
1021  * @since 2.1.0
1022  */
1023 function do_feed_rdf() {
1024         load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1025 }
1026
1027 /**
1028  * Load the RSS 1.0 Feed Template.
1029  *
1030  * @since 2.1.0
1031  */
1032 function do_feed_rss() {
1033         load_template( ABSPATH . WPINC . '/feed-rss.php' );
1034 }
1035
1036 /**
1037  * Load either the RSS2 comment feed or the RSS2 posts feed.
1038  *
1039  * @since 2.1.0
1040  *
1041  * @param bool $for_comments True for the comment feed, false for normal feed.
1042  */
1043 function do_feed_rss2( $for_comments ) {
1044         if ( $for_comments )
1045                 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1046         else
1047                 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1048 }
1049
1050 /**
1051  * Load either Atom comment feed or Atom posts feed.
1052  *
1053  * @since 2.1.0
1054  *
1055  * @param bool $for_comments True for the comment feed, false for normal feed.
1056  */
1057 function do_feed_atom( $for_comments ) {
1058         if ($for_comments)
1059                 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1060         else
1061                 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1062 }
1063
1064 /**
1065  * Display the robots.txt file content.
1066  *
1067  * The echo content should be with usage of the permalinks or for creating the
1068  * robots.txt file.
1069  *
1070  * @since 2.1.0
1071  * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
1072  */
1073 function do_robots() {
1074         header( 'Content-Type: text/plain; charset=utf-8' );
1075
1076         do_action( 'do_robotstxt' );
1077
1078         $output = "User-agent: *\n";
1079         $public = get_option( 'blog_public' );
1080         if ( '0' == $public ) {
1081                 $output .= "Disallow: /\n";
1082         } else {
1083                 $site_url = parse_url( site_url() );
1084                 $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1085                 $output .= "Disallow: $path/wp-admin/\n";
1086                 $output .= "Disallow: $path/wp-includes/\n";
1087         }
1088
1089         echo apply_filters('robots_txt', $output, $public);
1090 }
1091
1092 /**
1093  * Test whether blog is already installed.
1094  *
1095  * The cache will be checked first. If you have a cache plugin, which saves the
1096  * cache values, then this will work. If you use the default WordPress cache,
1097  * and the database goes away, then you might have problems.
1098  *
1099  * Checks for the option siteurl for whether WordPress is installed.
1100  *
1101  * @since 2.1.0
1102  * @uses $wpdb
1103  *
1104  * @return bool Whether blog is already installed.
1105  */
1106 function is_blog_installed() {
1107         global $wpdb;
1108
1109         // Check cache first. If options table goes away and we have true cached, oh well.
1110         if ( wp_cache_get( 'is_blog_installed' ) )
1111                 return true;
1112
1113         $suppress = $wpdb->suppress_errors();
1114         if ( ! defined( 'WP_INSTALLING' ) ) {
1115                 $alloptions = wp_load_alloptions();
1116         }
1117         // If siteurl is not set to autoload, check it specifically
1118         if ( !isset( $alloptions['siteurl'] ) )
1119                 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1120         else
1121                 $installed = $alloptions['siteurl'];
1122         $wpdb->suppress_errors( $suppress );
1123
1124         $installed = !empty( $installed );
1125         wp_cache_set( 'is_blog_installed', $installed );
1126
1127         if ( $installed )
1128                 return true;
1129
1130         // If visiting repair.php, return true and let it take over.
1131         if ( defined( 'WP_REPAIRING' ) )
1132                 return true;
1133
1134         $suppress = $wpdb->suppress_errors();
1135
1136         // Loop over the WP tables. If none exist, then scratch install is allowed.
1137         // If one or more exist, suggest table repair since we got here because the options
1138         // table could not be accessed.
1139         $wp_tables = $wpdb->tables();
1140         foreach ( $wp_tables as $table ) {
1141                 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1142                 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1143                         continue;
1144                 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1145                         continue;
1146
1147                 if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
1148                         continue;
1149
1150                 // One or more tables exist. We are insane.
1151
1152                 wp_load_translations_early();
1153
1154                 // Die with a DB error.
1155                 $wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
1156                 dead_db();
1157         }
1158
1159         $wpdb->suppress_errors( $suppress );
1160
1161         wp_cache_set( 'is_blog_installed', false );
1162
1163         return false;
1164 }
1165
1166 /**
1167  * Retrieve URL with nonce added to URL query.
1168  *
1169  * @package WordPress
1170  * @subpackage Security
1171  * @since 2.0.4
1172  *
1173  * @param string $actionurl URL to add nonce action
1174  * @param string $action Optional. Nonce action name
1175  * @return string URL with nonce action added.
1176  */
1177 function wp_nonce_url( $actionurl, $action = -1 ) {
1178         $actionurl = str_replace( '&amp;', '&', $actionurl );
1179         return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1180 }
1181
1182 /**
1183  * Retrieve or display nonce hidden field for forms.
1184  *
1185  * The nonce field is used to validate that the contents of the form came from
1186  * the location on the current site and not somewhere else. The nonce does not
1187  * offer absolute protection, but should protect against most cases. It is very
1188  * important to use nonce field in forms.
1189  *
1190  * The $action and $name are optional, but if you want to have better security,
1191  * it is strongly suggested to set those two parameters. It is easier to just
1192  * call the function without any parameters, because validation of the nonce
1193  * doesn't require any parameters, but since crackers know what the default is
1194  * it won't be difficult for them to find a way around your nonce and cause
1195  * damage.
1196  *
1197  * The input name will be whatever $name value you gave. The input value will be
1198  * the nonce creation value.
1199  *
1200  * @package WordPress
1201  * @subpackage Security
1202  * @since 2.0.4
1203  *
1204  * @param string $action Optional. Action name.
1205  * @param string $name Optional. Nonce name.
1206  * @param bool $referer Optional, default true. Whether to set the referer field for validation.
1207  * @param bool $echo Optional, default true. Whether to display or return hidden form field.
1208  * @return string Nonce field.
1209  */
1210 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1211         $name = esc_attr( $name );
1212         $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1213
1214         if ( $referer )
1215                 $nonce_field .= wp_referer_field( false );
1216
1217         if ( $echo )
1218                 echo $nonce_field;
1219
1220         return $nonce_field;
1221 }
1222
1223 /**
1224  * Retrieve or display referer hidden field for forms.
1225  *
1226  * The referer link is the current Request URI from the server super global. The
1227  * input name is '_wp_http_referer', in case you wanted to check manually.
1228  *
1229  * @package WordPress
1230  * @subpackage Security
1231  * @since 2.0.4
1232  *
1233  * @param bool $echo Whether to echo or return the referer field.
1234  * @return string Referer field.
1235  */
1236 function wp_referer_field( $echo = true ) {
1237         $ref = esc_attr( $_SERVER['REQUEST_URI'] );
1238         $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
1239
1240         if ( $echo )
1241                 echo $referer_field;
1242         return $referer_field;
1243 }
1244
1245 /**
1246  * Retrieve or display original referer hidden field for forms.
1247  *
1248  * The input name is '_wp_original_http_referer' and will be either the same
1249  * value of {@link wp_referer_field()}, if that was posted already or it will
1250  * be the current page, if it doesn't exist.
1251  *
1252  * @package WordPress
1253  * @subpackage Security
1254  * @since 2.0.4
1255  *
1256  * @param bool $echo Whether to echo the original http referer
1257  * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
1258  * @return string Original referer field.
1259  */
1260 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1261         $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
1262         $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
1263         $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
1264         if ( $echo )
1265                 echo $orig_referer_field;
1266         return $orig_referer_field;
1267 }
1268
1269 /**
1270  * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
1271  * as the current request URL, will return false.
1272  *
1273  * @package WordPress
1274  * @subpackage Security
1275  * @since 2.0.4
1276  *
1277  * @return string|bool False on failure. Referer URL on success.
1278  */
1279 function wp_get_referer() {
1280         $ref = false;
1281         if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
1282                 $ref = $_REQUEST['_wp_http_referer'];
1283         else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
1284                 $ref = $_SERVER['HTTP_REFERER'];
1285
1286         if ( $ref && $ref !== $_SERVER['REQUEST_URI'] )
1287                 return $ref;
1288         return false;
1289 }
1290
1291 /**
1292  * Retrieve original referer that was posted, if it exists.
1293  *
1294  * @package WordPress
1295  * @subpackage Security
1296  * @since 2.0.4
1297  *
1298  * @return string|bool False if no original referer or original referer if set.
1299  */
1300 function wp_get_original_referer() {
1301         if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
1302                 return $_REQUEST['_wp_original_http_referer'];
1303         return false;
1304 }
1305
1306 /**
1307  * Recursive directory creation based on full path.
1308  *
1309  * Will attempt to set permissions on folders.
1310  *
1311  * @since 2.0.1
1312  *
1313  * @param string $target Full path to attempt to create.
1314  * @return bool Whether the path was created. True if path already exists.
1315  */
1316 function wp_mkdir_p( $target ) {
1317         $wrapper = null;
1318
1319         // strip the protocol
1320         if( wp_is_stream( $target ) ) {
1321                 list( $wrapper, $target ) = explode( '://', $target, 2 );
1322         }
1323
1324         // from php.net/mkdir user contributed notes
1325         $target = str_replace( '//', '/', $target );
1326
1327         // put the wrapper back on the target
1328         if( $wrapper !== null ) {
1329                 $target = $wrapper . '://' . $target;
1330         }
1331
1332         // safe mode fails with a trailing slash under certain PHP versions.
1333         $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1334         if ( empty($target) )
1335                 $target = '/';
1336
1337         if ( file_exists( $target ) )
1338                 return @is_dir( $target );
1339
1340         // Attempting to create the directory may clutter up our display.
1341         if ( @mkdir( $target ) ) {
1342                 $stat = @stat( dirname( $target ) );
1343                 $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
1344                 @chmod( $target, $dir_perms );
1345                 return true;
1346         } elseif ( is_dir( dirname( $target ) ) ) {
1347                         return false;
1348         }
1349
1350         // If the above failed, attempt to create the parent node, then try again.
1351         if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
1352                 return wp_mkdir_p( $target );
1353
1354         return false;
1355 }
1356
1357 /**
1358  * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
1359  *
1360  * @since 2.5.0
1361  *
1362  * @param string $path File path
1363  * @return bool True if path is absolute, false is not absolute.
1364  */
1365 function path_is_absolute( $path ) {
1366         // this is definitive if true but fails if $path does not exist or contains a symbolic link
1367         if ( realpath($path) == $path )
1368                 return true;
1369
1370         if ( strlen($path) == 0 || $path[0] == '.' )
1371                 return false;
1372
1373         // windows allows absolute paths like this
1374         if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1375                 return true;
1376
1377         // a path starting with / or \ is absolute; anything else is relative
1378         return ( $path[0] == '/' || $path[0] == '\\' );
1379 }
1380
1381 /**
1382  * Join two filesystem paths together (e.g. 'give me $path relative to $base').
1383  *
1384  * If the $path is absolute, then it the full path is returned.
1385  *
1386  * @since 2.5.0
1387  *
1388  * @param string $base
1389  * @param string $path
1390  * @return string The path with the base or absolute path.
1391  */
1392 function path_join( $base, $path ) {
1393         if ( path_is_absolute($path) )
1394                 return $path;
1395
1396         return rtrim($base, '/') . '/' . ltrim($path, '/');
1397 }
1398
1399 /**
1400  * Determines a writable directory for temporary files.
1401  * Function's preference is the return value of <code>sys_get_temp_dir()</code>,
1402  * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
1403  * before finally defaulting to /tmp/
1404  *
1405  * In the event that this function does not find a writable location,
1406  * It may be overridden by the <code>WP_TEMP_DIR</code> constant in
1407  * your <code>wp-config.php</code> file.
1408  *
1409  * @since 2.5.0
1410  *
1411  * @return string Writable temporary directory
1412  */
1413 function get_temp_dir() {
1414         static $temp;
1415         if ( defined('WP_TEMP_DIR') )
1416                 return trailingslashit(WP_TEMP_DIR);
1417
1418         if ( $temp )
1419                 return trailingslashit( rtrim( $temp, '\\' ) );
1420
1421         $is_win = ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) );
1422
1423         if ( function_exists('sys_get_temp_dir') ) {
1424                 $temp = sys_get_temp_dir();
1425                 if ( @is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) ) {
1426                         return trailingslashit( rtrim( $temp, '\\' ) );
1427                 }
1428         }
1429
1430         $temp = ini_get('upload_tmp_dir');
1431         if ( is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) )
1432                 return trailingslashit( rtrim( $temp, '\\' ) );
1433
1434         $temp = WP_CONTENT_DIR . '/';
1435         if ( is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) )
1436                 return $temp;
1437
1438         $temp = '/tmp/';
1439         return $temp;
1440 }
1441
1442 /**
1443  * Workaround for Windows bug in is_writable() function
1444  *
1445  * @since 2.8.0
1446  *
1447  * @param string $path
1448  * @return bool
1449  */
1450 function win_is_writable( $path ) {
1451         /* will work in despite of Windows ACLs bug
1452          * NOTE: use a trailing slash for folders!!!
1453          * see http://bugs.php.net/bug.php?id=27609
1454          * see http://bugs.php.net/bug.php?id=30931
1455          */
1456
1457         if ( $path[strlen( $path ) - 1] == '/' ) // recursively return a temporary file path
1458                 return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
1459         else if ( is_dir( $path ) )
1460                 return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
1461         // check tmp file for read/write capabilities
1462         $should_delete_tmp_file = !file_exists( $path );
1463         $f = @fopen( $path, 'a' );
1464         if ( $f === false )
1465                 return false;
1466         fclose( $f );
1467         if ( $should_delete_tmp_file )
1468                 unlink( $path );
1469         return true;
1470 }
1471
1472 /**
1473  * Get an array containing the current upload directory's path and url.
1474  *
1475  * Checks the 'upload_path' option, which should be from the web root folder,
1476  * and if it isn't empty it will be used. If it is empty, then the path will be
1477  * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
1478  * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
1479  *
1480  * The upload URL path is set either by the 'upload_url_path' option or by using
1481  * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
1482  *
1483  * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
1484  * the administration settings panel), then the time will be used. The format
1485  * will be year first and then month.
1486  *
1487  * If the path couldn't be created, then an error will be returned with the key
1488  * 'error' containing the error message. The error suggests that the parent
1489  * directory is not writable by the server.
1490  *
1491  * On success, the returned array will have many indices:
1492  * 'path' - base directory and sub directory or full path to upload directory.
1493  * 'url' - base url and sub directory or absolute URL to upload directory.
1494  * 'subdir' - sub directory if uploads use year/month folders option is on.
1495  * 'basedir' - path without subdir.
1496  * 'baseurl' - URL path without subdir.
1497  * 'error' - set to false.
1498  *
1499  * @since 2.0.0
1500  * @uses apply_filters() Calls 'upload_dir' on returned array.
1501  *
1502  * @param string $time Optional. Time formatted in 'yyyy/mm'.
1503  * @return array See above for description.
1504  */
1505 function wp_upload_dir( $time = null ) {
1506         $siteurl = get_option( 'siteurl' );
1507         $upload_path = trim( get_option( 'upload_path' ) );
1508
1509         if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
1510                 $dir = WP_CONTENT_DIR . '/uploads';
1511         } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
1512                 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
1513                 $dir = path_join( ABSPATH, $upload_path );
1514         } else {
1515                 $dir = $upload_path;
1516         }
1517
1518         if ( !$url = get_option( 'upload_url_path' ) ) {
1519                 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
1520                         $url = WP_CONTENT_URL . '/uploads';
1521                 else
1522                         $url = trailingslashit( $siteurl ) . $upload_path;
1523         }
1524
1525         // Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
1526         // We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
1527         if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
1528                 $dir = ABSPATH . UPLOADS;
1529                 $url = trailingslashit( $siteurl ) . UPLOADS;
1530         }
1531
1532         // If multisite (and if not the main site in a post-MU network)
1533         if ( is_multisite() && ! ( is_main_site() && defined( 'MULTISITE' ) ) ) {
1534
1535                 if ( ! get_site_option( 'ms_files_rewriting' ) ) {
1536                         // If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
1537                         // Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
1538                         // prevents a four-digit ID from conflicting with a year-based directory for the main site.
1539                         // But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
1540                         // directory, as they never had wp-content/uploads for the main site.)
1541
1542                         if ( defined( 'MULTISITE' ) )
1543                                 $ms_dir = '/sites/' . get_current_blog_id();
1544                         else
1545                                 $ms_dir = '/' . get_current_blog_id();
1546
1547                         $dir .= $ms_dir;
1548                         $url .= $ms_dir;
1549
1550                 } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
1551                         // Handle the old-form ms-files.php rewriting if the network still has that enabled.
1552                         // When ms-files rewriting is enabled, then we only listen to UPLOADS when:
1553                         //   1) we are not on the main site in a post-MU network,
1554                         //      as wp-content/uploads is used there, and
1555                         //   2) we are not switched, as ms_upload_constants() hardcodes
1556                         //      these constants to reflect the original blog ID.
1557                         //
1558                         // Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
1559                         // (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
1560                         // as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
1561                         // rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
1562
1563                         if ( defined( 'BLOGUPLOADDIR' ) )
1564                                 $dir = untrailingslashit( BLOGUPLOADDIR );
1565                         else
1566                                 $dir = ABSPATH . UPLOADS;
1567                         $url = trailingslashit( $siteurl ) . 'files';
1568                 }
1569         }
1570
1571         $basedir = $dir;
1572         $baseurl = $url;
1573
1574         $subdir = '';
1575         if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
1576                 // Generate the yearly and monthly dirs
1577                 if ( !$time )
1578                         $time = current_time( 'mysql' );
1579                 $y = substr( $time, 0, 4 );
1580                 $m = substr( $time, 5, 2 );
1581                 $subdir = "/$y/$m";
1582         }
1583
1584         $dir .= $subdir;
1585         $url .= $subdir;
1586
1587         $uploads = apply_filters( 'upload_dir',
1588                 array(
1589                         'path'    => $dir,
1590                         'url'     => $url,
1591                         'subdir'  => $subdir,
1592                         'basedir' => $basedir,
1593                         'baseurl' => $baseurl,
1594                         'error'   => false,
1595                 ) );
1596
1597         // Make sure we have an uploads dir
1598         if ( ! wp_mkdir_p( $uploads['path'] ) ) {
1599                 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
1600                         $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
1601                 else
1602                         $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
1603
1604                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
1605                 $uploads['error'] = $message;
1606         }
1607
1608         return $uploads;
1609 }
1610
1611 /**
1612  * Get a filename that is sanitized and unique for the given directory.
1613  *
1614  * If the filename is not unique, then a number will be added to the filename
1615  * before the extension, and will continue adding numbers until the filename is
1616  * unique.
1617  *
1618  * The callback is passed three parameters, the first one is the directory, the
1619  * second is the filename, and the third is the extension.
1620  *
1621  * @since 2.5.0
1622  *
1623  * @param string $dir
1624  * @param string $filename
1625  * @param mixed $unique_filename_callback Callback.
1626  * @return string New filename, if given wasn't unique.
1627  */
1628 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
1629         // sanitize the file name before we begin processing
1630         $filename = sanitize_file_name($filename);
1631
1632         // separate the filename into a name and extension
1633         $info = pathinfo($filename);
1634         $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
1635         $name = basename($filename, $ext);
1636
1637         // edge case: if file is named '.ext', treat as an empty name
1638         if ( $name === $ext )
1639                 $name = '';
1640
1641         // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
1642         if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
1643                 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
1644         } else {
1645                 $number = '';
1646
1647                 // change '.ext' to lower case
1648                 if ( $ext && strtolower($ext) != $ext ) {
1649                         $ext2 = strtolower($ext);
1650                         $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
1651
1652                         // check for both lower and upper case extension or image sub-sizes may be overwritten
1653                         while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
1654                                 $new_number = $number + 1;
1655                                 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
1656                                 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
1657                                 $number = $new_number;
1658                         }
1659                         return $filename2;
1660                 }
1661
1662                 while ( file_exists( $dir . "/$filename" ) ) {
1663                         if ( '' == "$number$ext" )
1664                                 $filename = $filename . ++$number . $ext;
1665                         else
1666                                 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
1667                 }
1668         }
1669
1670         return $filename;
1671 }
1672
1673 /**
1674  * Create a file in the upload folder with given content.
1675  *
1676  * If there is an error, then the key 'error' will exist with the error message.
1677  * If success, then the key 'file' will have the unique file path, the 'url' key
1678  * will have the link to the new file. and the 'error' key will be set to false.
1679  *
1680  * This function will not move an uploaded file to the upload folder. It will
1681  * create a new file with the content in $bits parameter. If you move the upload
1682  * file, read the content of the uploaded file, and then you can give the
1683  * filename and content to this function, which will add it to the upload
1684  * folder.
1685  *
1686  * The permissions will be set on the new file automatically by this function.
1687  *
1688  * @since 2.0.0
1689  *
1690  * @param string $name
1691  * @param null $deprecated Never used. Set to null.
1692  * @param mixed $bits File content
1693  * @param string $time Optional. Time formatted in 'yyyy/mm'.
1694  * @return array
1695  */
1696 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
1697         if ( !empty( $deprecated ) )
1698                 _deprecated_argument( __FUNCTION__, '2.0' );
1699
1700         if ( empty( $name ) )
1701                 return array( 'error' => __( 'Empty filename' ) );
1702
1703         $wp_filetype = wp_check_filetype( $name );
1704         if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
1705                 return array( 'error' => __( 'Invalid file type' ) );
1706
1707         $upload = wp_upload_dir( $time );
1708
1709         if ( $upload['error'] !== false )
1710                 return $upload;
1711
1712         $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
1713         if ( !is_array( $upload_bits_error ) ) {
1714                 $upload[ 'error' ] = $upload_bits_error;
1715                 return $upload;
1716         }
1717
1718         $filename = wp_unique_filename( $upload['path'], $name );
1719
1720         $new_file = $upload['path'] . "/$filename";
1721         if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
1722                 if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
1723                         $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
1724                 else
1725                         $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
1726
1727                 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
1728                 return array( 'error' => $message );
1729         }
1730
1731         $ifp = @ fopen( $new_file, 'wb' );
1732         if ( ! $ifp )
1733                 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
1734
1735         @fwrite( $ifp, $bits );
1736         fclose( $ifp );
1737         clearstatcache();
1738
1739         // Set correct file permissions
1740         $stat = @ stat( dirname( $new_file ) );
1741         $perms = $stat['mode'] & 0007777;
1742         $perms = $perms & 0000666;
1743         @ chmod( $new_file, $perms );
1744         clearstatcache();
1745
1746         // Compute the URL
1747         $url = $upload['url'] . "/$filename";
1748
1749         return array( 'file' => $new_file, 'url' => $url, 'error' => false );
1750 }
1751
1752 /**
1753  * Retrieve the file type based on the extension name.
1754  *
1755  * @package WordPress
1756  * @since 2.5.0
1757  * @uses apply_filters() Calls 'ext2type' hook on default supported types.
1758  *
1759  * @param string $ext The extension to search.
1760  * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
1761  */
1762 function wp_ext2type( $ext ) {
1763         $ext2type = apply_filters( 'ext2type', array(
1764                 'audio'       => array( 'aac', 'ac3',  'aif',  'aiff', 'm3a',  'm4a',   'm4b',  'mka',  'mp1',  'mp2',  'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
1765                 'video'       => array( 'asf', 'avi',  'divx', 'dv',   'flv',  'm4v',   'mkv',  'mov',  'mp4',  'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt',  'rm', 'vob', 'wmv' ),
1766                 'document'    => array( 'doc', 'docx', 'docm', 'dotm', 'odt',  'pages', 'pdf',  'rtf',  'wp',   'wpd' ),
1767                 'spreadsheet' => array( 'numbers',     'ods',  'xls',  'xlsx', 'xlsm',  'xlsb' ),
1768                 'interactive' => array( 'swf', 'key',  'ppt',  'pptx', 'pptm', 'pps',   'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
1769                 'text'        => array( 'asc', 'csv',  'tsv',  'txt' ),
1770                 'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit',  'sqx',  'tar',  'tgz',  'zip', '7z' ),
1771                 'code'        => array( 'css', 'htm',  'html', 'php',  'js' ),
1772         ));
1773         foreach ( $ext2type as $type => $exts )
1774                 if ( in_array( $ext, $exts ) )
1775                         return $type;
1776 }
1777
1778 /**
1779  * Retrieve the file type from the file name.
1780  *
1781  * You can optionally define the mime array, if needed.
1782  *
1783  * @since 2.0.4
1784  *
1785  * @param string $filename File name or path.
1786  * @param array $mimes Optional. Key is the file extension with value as the mime type.
1787  * @return array Values with extension first and mime type.
1788  */
1789 function wp_check_filetype( $filename, $mimes = null ) {
1790         if ( empty($mimes) )
1791                 $mimes = get_allowed_mime_types();
1792         $type = false;
1793         $ext = false;
1794
1795         foreach ( $mimes as $ext_preg => $mime_match ) {
1796                 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1797                 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
1798                         $type = $mime_match;
1799                         $ext = $ext_matches[1];
1800                         break;
1801                 }
1802         }
1803
1804         return compact( 'ext', 'type' );
1805 }
1806
1807 /**
1808  * Attempt to determine the real file type of a file.
1809  * If unable to, the file name extension will be used to determine type.
1810  *
1811  * If it's determined that the extension does not match the file's real type,
1812  * then the "proper_filename" value will be set with a proper filename and extension.
1813  *
1814  * Currently this function only supports validating images known to getimagesize().
1815  *
1816  * @since 3.0.0
1817  *
1818  * @param string $file Full path to the image.
1819  * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
1820  * @param array $mimes Optional. Key is the file extension with value as the mime type.
1821  * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
1822  */
1823 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
1824
1825         $proper_filename = false;
1826
1827         // Do basic extension validation and MIME mapping
1828         $wp_filetype = wp_check_filetype( $filename, $mimes );
1829         extract( $wp_filetype );
1830
1831         // We can't do any further validation without a file to work with
1832         if ( ! file_exists( $file ) )
1833                 return compact( 'ext', 'type', 'proper_filename' );
1834
1835         // We're able to validate images using GD
1836         if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
1837
1838                 // Attempt to figure out what type of image it actually is
1839                 $imgstats = @getimagesize( $file );
1840
1841                 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
1842                 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
1843                         // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
1844                         // You shouldn't need to use this filter, but it's here just in case
1845                         $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
1846                                 'image/jpeg' => 'jpg',
1847                                 'image/png'  => 'png',
1848                                 'image/gif'  => 'gif',
1849                                 'image/bmp'  => 'bmp',
1850                                 'image/tiff' => 'tif',
1851                         ) );
1852
1853                         // Replace whatever is after the last period in the filename with the correct extension
1854                         if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
1855                                 $filename_parts = explode( '.', $filename );
1856                                 array_pop( $filename_parts );
1857                                 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
1858                                 $new_filename = implode( '.', $filename_parts );
1859
1860                                 if ( $new_filename != $filename )
1861                                         $proper_filename = $new_filename; // Mark that it changed
1862
1863                                 // Redefine the extension / MIME
1864                                 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
1865                                 extract( $wp_filetype );
1866                         }
1867                 }
1868         }
1869
1870         // Let plugins try and validate other types of files
1871         // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
1872         return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
1873 }
1874
1875 /**
1876  * Retrieve list of mime types and file extensions.
1877  *
1878  * @since 3.5.0
1879  *
1880  * @uses apply_filters() Calls 'mime_types' on returned array. This filter should
1881  * be used to add types, not remove them. To remove types use the upload_mimes filter.
1882  *
1883  * @return array Array of mime types keyed by the file extension regex corresponding to those types.
1884  */
1885 function wp_get_mime_types() {
1886         // Accepted MIME types are set here as PCRE unless provided.
1887         return apply_filters( 'mime_types', array(
1888         // Image formats
1889         'jpg|jpeg|jpe' => 'image/jpeg',
1890         'gif' => 'image/gif',
1891         'png' => 'image/png',
1892         'bmp' => 'image/bmp',
1893         'tif|tiff' => 'image/tiff',
1894         'ico' => 'image/x-icon',
1895         // Video formats
1896         'asf|asx|wax|wmv|wmx' => 'video/asf',
1897         'avi' => 'video/avi',
1898         'divx' => 'video/divx',
1899         'flv' => 'video/x-flv',
1900         'mov|qt' => 'video/quicktime',
1901         'mpeg|mpg|mpe' => 'video/mpeg',
1902         'mp4|m4v' => 'video/mp4',
1903         'ogv' => 'video/ogg',
1904         'mkv' => 'video/x-matroska',
1905         // Text formats
1906         'txt|asc|c|cc|h' => 'text/plain',
1907         'csv' => 'text/csv',
1908         'tsv' => 'text/tab-separated-values',
1909         'ics' => 'text/calendar',
1910         'rtx' => 'text/richtext',
1911         'css' => 'text/css',
1912         'htm|html' => 'text/html',
1913         // Audio formats
1914         'mp3|m4a|m4b' => 'audio/mpeg',
1915         'ra|ram' => 'audio/x-realaudio',
1916         'wav' => 'audio/wav',
1917         'ogg|oga' => 'audio/ogg',
1918         'mid|midi' => 'audio/midi',
1919         'wma' => 'audio/wma',
1920         'mka' => 'audio/x-matroska',
1921         // Misc application formats
1922         'rtf' => 'application/rtf',
1923         'js' => 'application/javascript',
1924         'pdf' => 'application/pdf',
1925         'swf' => 'application/x-shockwave-flash',
1926         'class' => 'application/java',
1927         'tar' => 'application/x-tar',
1928         'zip' => 'application/zip',
1929         'gz|gzip' => 'application/x-gzip',
1930         'rar' => 'application/rar',
1931         '7z' => 'application/x-7z-compressed',
1932         'exe' => 'application/x-msdownload',
1933         // MS Office formats
1934         'doc' => 'application/msword',
1935         'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
1936         'wri' => 'application/vnd.ms-write',
1937         'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
1938         'mdb' => 'application/vnd.ms-access',
1939         'mpp' => 'application/vnd.ms-project',
1940         'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1941         'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
1942         'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
1943         'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
1944         'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1945         'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
1946         'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
1947         'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
1948         'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
1949         'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
1950         'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
1951         'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
1952         'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
1953         'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
1954         'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
1955         'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
1956         'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
1957         'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
1958         'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
1959         'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
1960         // OpenOffice formats
1961         'odt' => 'application/vnd.oasis.opendocument.text',
1962         'odp' => 'application/vnd.oasis.opendocument.presentation',
1963         'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1964         'odg' => 'application/vnd.oasis.opendocument.graphics',
1965         'odc' => 'application/vnd.oasis.opendocument.chart',
1966         'odb' => 'application/vnd.oasis.opendocument.database',
1967         'odf' => 'application/vnd.oasis.opendocument.formula',
1968         // WordPerfect formats
1969         'wp|wpd' => 'application/wordperfect',
1970         ) );
1971 }
1972 /**
1973  * Retrieve list of allowed mime types and file extensions.
1974  *
1975  * @since 2.8.6
1976  *
1977  * @uses apply_filters() Calls 'upload_mimes' on returned array
1978  * @uses wp_get_upload_mime_types() to fetch the list of mime types
1979  *
1980  * @return array Array of mime types keyed by the file extension regex corresponding to those types.
1981  */
1982 function get_allowed_mime_types() {
1983         return apply_filters( 'upload_mimes', wp_get_mime_types() );
1984 }
1985
1986 /**
1987  * Display "Are You Sure" message to confirm the action being taken.
1988  *
1989  * If the action has the nonce explain message, then it will be displayed along
1990  * with the "Are you sure?" message.
1991  *
1992  * @package WordPress
1993  * @subpackage Security
1994  * @since 2.0.4
1995  *
1996  * @param string $action The nonce action.
1997  */
1998 function wp_nonce_ays( $action ) {
1999         $title = __( 'WordPress Failure Notice' );
2000         if ( 'log-out' == $action ) {
2001                 $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
2002                 $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
2003         } else {
2004                 $html = __( 'Are you sure you want to do this?' );
2005                 if ( wp_get_referer() )
2006                         $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
2007         }
2008
2009         wp_die( $html, $title, array('response' => 403) );
2010 }
2011
2012 /**
2013  * Kill WordPress execution and display HTML message with error message.
2014  *
2015  * This function complements the die() PHP function. The difference is that
2016  * HTML will be displayed to the user. It is recommended to use this function
2017  * only, when the execution should not continue any further. It is not
2018  * recommended to call this function very often and try to handle as many errors
2019  * as possible silently.
2020  *
2021  * @since 2.0.4
2022  *
2023  * @param string $message Error message.
2024  * @param string $title Error title.
2025  * @param string|array $args Optional arguments to control behavior.
2026  */
2027 function wp_die( $message = '', $title = '', $args = array() ) {
2028         if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2029                 $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
2030         elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2031                 $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
2032         else
2033                 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
2034
2035         call_user_func( $function, $message, $title, $args );
2036 }
2037
2038 /**
2039  * Kill WordPress execution and display HTML message with error message.
2040  *
2041  * This is the default handler for wp_die if you want a custom one for your
2042  * site then you can overload using the wp_die_handler filter in wp_die
2043  *
2044  * @since 3.0.0
2045  * @access private
2046  *
2047  * @param string $message Error message.
2048  * @param string $title Error title.
2049  * @param string|array $args Optional arguments to control behavior.
2050  */
2051 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
2052         $defaults = array( 'response' => 500 );
2053         $r = wp_parse_args($args, $defaults);
2054
2055         $have_gettext = function_exists('__');
2056
2057         if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
2058                 if ( empty( $title ) ) {
2059                         $error_data = $message->get_error_data();
2060                         if ( is_array( $error_data ) && isset( $error_data['title'] ) )
2061                                 $title = $error_data['title'];
2062                 }
2063                 $errors = $message->get_error_messages();
2064                 switch ( count( $errors ) ) :
2065                 case 0 :
2066                         $message = '';
2067                         break;
2068                 case 1 :
2069                         $message = "<p>{$errors[0]}</p>";
2070                         break;
2071                 default :
2072                         $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
2073                         break;
2074                 endswitch;
2075         } elseif ( is_string( $message ) ) {
2076                 $message = "<p>$message</p>";
2077         }
2078
2079         if ( isset( $r['back_link'] ) && $r['back_link'] ) {
2080                 $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
2081                 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
2082         }
2083
2084         if ( ! did_action( 'admin_head' ) ) :
2085                 if ( !headers_sent() ) {
2086                         status_header( $r['response'] );
2087                         nocache_headers();
2088                         header( 'Content-Type: text/html; charset=utf-8' );
2089                 }
2090
2091                 if ( empty($title) )
2092                         $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
2093
2094                 $text_direction = 'ltr';
2095                 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
2096                         $text_direction = 'rtl';
2097                 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
2098                         $text_direction = 'rtl';
2099 ?>
2100 <!DOCTYPE html>
2101 <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono
2102 -->
2103 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) language_attributes(); else echo "dir='$text_direction'"; ?>>
2104 <head>
2105         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2106         <title><?php echo $title ?></title>
2107         <style type="text/css">
2108                 html {
2109                         background: #f9f9f9;
2110                 }
2111                 body {
2112                         background: #fff;
2113                         color: #333;
2114                         font-family: sans-serif;
2115                         margin: 2em auto;
2116                         padding: 1em 2em;
2117                         -webkit-border-radius: 3px;
2118                         border-radius: 3px;
2119                         border: 1px solid #dfdfdf;
2120                         max-width: 700px;
2121                 }
2122                 h1 {
2123                         border-bottom: 1px solid #dadada;
2124                         clear: both;
2125                         color: #666;
2126                         font: 24px Georgia, "Times New Roman", Times, serif;
2127                         margin: 30px 0 0 0;
2128                         padding: 0;
2129                         padding-bottom: 7px;
2130                 }
2131                 #error-page {
2132                         margin-top: 50px;
2133                 }
2134                 #error-page p {
2135                         font-size: 14px;
2136                         line-height: 1.5;
2137                         margin: 25px 0 20px;
2138                 }
2139                 #error-page code {
2140                         font-family: Consolas, Monaco, monospace;
2141                 }
2142                 ul li {
2143                         margin-bottom: 10px;
2144                         font-size: 14px ;
2145                 }
2146                 a {
2147                         color: #21759B;
2148                         text-decoration: none;
2149                 }
2150                 a:hover {
2151                         color: #D54E21;
2152                 }
2153                 .button {
2154                         display: inline-block;
2155                         text-decoration: none;
2156                         font-size: 14px;
2157                         line-height: 23px;
2158                         height: 24px;
2159                         margin: 0;
2160                         padding: 0 10px 1px;
2161                         cursor: pointer;
2162                         border-width: 1px;
2163                         border-style: solid;
2164                         -webkit-border-radius: 3px;
2165                         border-radius: 3px;
2166                         white-space: nowrap;
2167                         -webkit-box-sizing: border-box;
2168                         -moz-box-sizing:    border-box;
2169                         box-sizing:         border-box;
2170                         background: #f3f3f3;
2171                         background-image: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#f4f4f4));
2172                         background-image: -webkit-linear-gradient(top, #fefefe, #f4f4f4);
2173                         background-image:    -moz-linear-gradient(top, #fefefe, #f4f4f4);
2174                         background-image:      -o-linear-gradient(top, #fefefe, #f4f4f4);
2175                         background-image:   linear-gradient(to bottom, #fefefe, #f4f4f4);
2176                         border-color: #bbb;
2177                         color: #333;
2178                         text-shadow: 0 1px 0 #fff;
2179                 }
2180
2181                 .button.button-large {
2182                         height: 29px;
2183                         line-height: 28px;
2184                         padding: 0 12px;
2185                 }
2186
2187                 .button:hover,
2188                 .button:focus {
2189                         background: #f3f3f3;
2190                         background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f3f3f3));
2191                         background-image: -webkit-linear-gradient(top, #fff, #f3f3f3);
2192                         background-image:    -moz-linear-gradient(top, #fff, #f3f3f3);
2193                         background-image:     -ms-linear-gradient(top, #fff, #f3f3f3);
2194                         background-image:      -o-linear-gradient(top, #fff, #f3f3f3);
2195                         background-image:   linear-gradient(to bottom, #fff, #f3f3f3);
2196                         border-color: #999;
2197                         color: #222;
2198                 }
2199
2200                 .button:focus  {
2201                         -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2);
2202                         box-shadow: 1px 1px 1px rgba(0,0,0,.2);
2203                 }
2204
2205                 .button:active {
2206                         outline: none;
2207                         background: #eee;
2208                         background-image: -webkit-gradient(linear, left top, left bottom, from(#f4f4f4), to(#fefefe));
2209                         background-image: -webkit-linear-gradient(top, #f4f4f4, #fefefe);
2210                         background-image:    -moz-linear-gradient(top, #f4f4f4, #fefefe);
2211                         background-image:     -ms-linear-gradient(top, #f4f4f4, #fefefe);
2212                         background-image:      -o-linear-gradient(top, #f4f4f4, #fefefe);
2213                         background-image:   linear-gradient(to bottom, #f4f4f4, #fefefe);
2214                         border-color: #999;
2215                         color: #333;
2216                         text-shadow: 0 -1px 0 #fff;
2217                         -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2218                         box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2219                 }
2220
2221                 <?php if ( 'rtl' == $text_direction ) : ?>
2222                 body { font-family: Tahoma, Arial; }
2223                 <?php endif; ?>
2224         </style>
2225 </head>
2226 <body id="error-page">
2227 <?php endif; // ! did_action( 'admin_head' ) ?>
2228         <?php echo $message; ?>
2229 </body>
2230 </html>
2231 <?php
2232         die();
2233 }
2234
2235 /**
2236  * Kill WordPress execution and display XML message with error message.
2237  *
2238  * This is the handler for wp_die when processing XMLRPC requests.
2239  *
2240  * @since 3.2.0
2241  * @access private
2242  *
2243  * @param string $message Error message.
2244  * @param string $title Error title.
2245  * @param string|array $args Optional arguments to control behavior.
2246  */
2247 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
2248         global $wp_xmlrpc_server;
2249         $defaults = array( 'response' => 500 );
2250
2251         $r = wp_parse_args($args, $defaults);
2252
2253         if ( $wp_xmlrpc_server ) {
2254                 $error = new IXR_Error( $r['response'] , $message);
2255                 $wp_xmlrpc_server->output( $error->getXml() );
2256         }
2257         die();
2258 }
2259
2260 /**
2261  * Kill WordPress ajax execution.
2262  *
2263  * This is the handler for wp_die when processing Ajax requests.
2264  *
2265  * @since 3.4.0
2266  * @access private
2267  *
2268  * @param string $message Optional. Response to print.
2269  */
2270 function _ajax_wp_die_handler( $message = '' ) {
2271         if ( is_scalar( $message ) )
2272                 die( (string) $message );
2273         die( '0' );
2274 }
2275
2276 /**
2277  * Kill WordPress execution.
2278  *
2279  * This is the handler for wp_die when processing APP requests.
2280  *
2281  * @since 3.4.0
2282  * @access private
2283  *
2284  * @param string $message Optional. Response to print.
2285  */
2286 function _scalar_wp_die_handler( $message = '' ) {
2287         if ( is_scalar( $message ) )
2288                 die( (string) $message );
2289         die();
2290 }
2291
2292 /**
2293  * Send a JSON response back to an Ajax request.
2294  *
2295  * @since 3.5.0
2296  *
2297  * @param mixed $response Variable (usually an array or object) to encode as JSON, then print and die.
2298  */
2299 function wp_send_json( $response ) {
2300         @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
2301         echo json_encode( $response );
2302         if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2303                 wp_die();
2304         else
2305                 die;
2306 }
2307
2308 /**
2309  * Send a JSON response back to an Ajax request, indicating success.
2310  *
2311  * @since 3.5.0
2312  *
2313  * @param mixed $data Data to encode as JSON, then print and die.
2314  */
2315 function wp_send_json_success( $data = null ) {
2316         $response = array( 'success' => true );
2317
2318         if ( isset( $data ) )
2319                 $response['data'] = $data;
2320
2321         wp_send_json( $response );
2322 }
2323
2324 /**
2325  * Send a JSON response back to an Ajax request, indicating failure.
2326  *
2327  * @since 3.5.0
2328  *
2329  * @param mixed $data Data to encode as JSON, then print and die.
2330  */
2331 function wp_send_json_error( $data = null ) {
2332         $response = array( 'success' => false );
2333
2334         if ( isset( $data ) )
2335                 $response['data'] = $data;
2336
2337         wp_send_json( $response );
2338 }
2339
2340 /**
2341  * Retrieve the WordPress home page URL.
2342  *
2343  * If the constant named 'WP_HOME' exists, then it will be used and returned by
2344  * the function. This can be used to counter the redirection on your local
2345  * development environment.
2346  *
2347  * @access private
2348  * @package WordPress
2349  * @since 2.2.0
2350  *
2351  * @param string $url URL for the home location
2352  * @return string Homepage location.
2353  */
2354 function _config_wp_home( $url = '' ) {
2355         if ( defined( 'WP_HOME' ) )
2356                 return untrailingslashit( WP_HOME );
2357         return $url;
2358 }
2359
2360 /**
2361  * Retrieve the WordPress site URL.
2362  *
2363  * If the constant named 'WP_SITEURL' is defined, then the value in that
2364  * constant will always be returned. This can be used for debugging a site on
2365  * your localhost while not having to change the database to your URL.
2366  *
2367  * @access private
2368  * @package WordPress
2369  * @since 2.2.0
2370  *
2371  * @param string $url URL to set the WordPress site location.
2372  * @return string The WordPress Site URL
2373  */
2374 function _config_wp_siteurl( $url = '' ) {
2375         if ( defined( 'WP_SITEURL' ) )
2376                 return untrailingslashit( WP_SITEURL );
2377         return $url;
2378 }
2379
2380 /**
2381  * Set the localized direction for MCE plugin.
2382  *
2383  * Will only set the direction to 'rtl', if the WordPress locale has the text
2384  * direction set to 'rtl'.
2385  *
2386  * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
2387  * keys. These keys are then returned in the $input array.
2388  *
2389  * @access private
2390  * @package WordPress
2391  * @subpackage MCE
2392  * @since 2.1.0
2393  *
2394  * @param array $input MCE plugin array.
2395  * @return array Direction set for 'rtl', if needed by locale.
2396  */
2397 function _mce_set_direction( $input ) {
2398         if ( is_rtl() ) {
2399                 $input['directionality'] = 'rtl';
2400                 $input['plugins'] .= ',directionality';
2401                 $input['theme_advanced_buttons1'] .= ',ltr';
2402         }
2403
2404         return $input;
2405 }
2406
2407 /**
2408  * Convert smiley code to the icon graphic file equivalent.
2409  *
2410  * You can turn off smilies, by going to the write setting screen and unchecking
2411  * the box, or by setting 'use_smilies' option to false or removing the option.
2412  *
2413  * Plugins may override the default smiley list by setting the $wpsmiliestrans
2414  * to an array, with the key the code the blogger types in and the value the
2415  * image file.
2416  *
2417  * The $wp_smiliessearch global is for the regular expression and is set each
2418  * time the function is called.
2419  *
2420  * The full list of smilies can be found in the function and won't be listed in
2421  * the description. Probably should create a Codex page for it, so that it is
2422  * available.
2423  *
2424  * @global array $wpsmiliestrans
2425  * @global array $wp_smiliessearch
2426  * @since 2.2.0
2427  */
2428 function smilies_init() {
2429         global $wpsmiliestrans, $wp_smiliessearch;
2430
2431         // don't bother setting up smilies if they are disabled
2432         if ( !get_option( 'use_smilies' ) )
2433                 return;
2434
2435         if ( !isset( $wpsmiliestrans ) ) {
2436                 $wpsmiliestrans = array(
2437                 ':mrgreen:' => 'icon_mrgreen.gif',
2438                 ':neutral:' => 'icon_neutral.gif',
2439                 ':twisted:' => 'icon_twisted.gif',
2440                   ':arrow:' => 'icon_arrow.gif',
2441                   ':shock:' => 'icon_eek.gif',
2442                   ':smile:' => 'icon_smile.gif',
2443                     ':???:' => 'icon_confused.gif',
2444                    ':cool:' => 'icon_cool.gif',
2445                    ':evil:' => 'icon_evil.gif',
2446                    ':grin:' => 'icon_biggrin.gif',
2447                    ':idea:' => 'icon_idea.gif',
2448                    ':oops:' => 'icon_redface.gif',
2449                    ':razz:' => 'icon_razz.gif',
2450                    ':roll:' => 'icon_rolleyes.gif',
2451                    ':wink:' => 'icon_wink.gif',
2452                     ':cry:' => 'icon_cry.gif',
2453                     ':eek:' => 'icon_surprised.gif',
2454                     ':lol:' => 'icon_lol.gif',
2455                     ':mad:' => 'icon_mad.gif',
2456                     ':sad:' => 'icon_sad.gif',
2457                       '8-)' => 'icon_cool.gif',
2458                       '8-O' => 'icon_eek.gif',
2459                       ':-(' => 'icon_sad.gif',
2460                       ':-)' => 'icon_smile.gif',
2461                       ':-?' => 'icon_confused.gif',
2462                       ':-D' => 'icon_biggrin.gif',
2463                       ':-P' => 'icon_razz.gif',
2464                       ':-o' => 'icon_surprised.gif',
2465                       ':-x' => 'icon_mad.gif',
2466                       ':-|' => 'icon_neutral.gif',
2467                       ';-)' => 'icon_wink.gif',
2468                 // This one transformation breaks regular text with frequency.
2469                 //     '8)' => 'icon_cool.gif',
2470                        '8O' => 'icon_eek.gif',
2471                        ':(' => 'icon_sad.gif',
2472                        ':)' => 'icon_smile.gif',
2473                        ':?' => 'icon_confused.gif',
2474                        ':D' => 'icon_biggrin.gif',
2475                        ':P' => 'icon_razz.gif',
2476                        ':o' => 'icon_surprised.gif',
2477                        ':x' => 'icon_mad.gif',
2478                        ':|' => 'icon_neutral.gif',
2479                        ';)' => 'icon_wink.gif',
2480                       ':!:' => 'icon_exclaim.gif',
2481                       ':?:' => 'icon_question.gif',
2482                 );
2483         }
2484
2485         if (count($wpsmiliestrans) == 0) {
2486                 return;
2487         }
2488
2489         /*
2490          * NOTE: we sort the smilies in reverse key order. This is to make sure
2491          * we match the longest possible smilie (:???: vs :?) as the regular
2492          * expression used below is first-match
2493          */
2494         krsort($wpsmiliestrans);
2495
2496         $wp_smiliessearch = '/(?:\s|^)';
2497
2498         $subchar = '';
2499         foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
2500                 $firstchar = substr($smiley, 0, 1);
2501                 $rest = substr($smiley, 1);
2502
2503                 // new subpattern?
2504                 if ($firstchar != $subchar) {
2505                         if ($subchar != '') {
2506                                 $wp_smiliessearch .= ')|(?:\s|^)';
2507                         }
2508                         $subchar = $firstchar;
2509                         $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
2510                 } else {
2511                         $wp_smiliessearch .= '|';
2512                 }
2513                 $wp_smiliessearch .= preg_quote($rest, '/');
2514         }
2515
2516         $wp_smiliessearch .= ')(?:\s|$)/m';
2517 }
2518
2519 /**
2520  * Merge user defined arguments into defaults array.
2521  *
2522  * This function is used throughout WordPress to allow for both string or array
2523  * to be merged into another array.
2524  *
2525  * @since 2.2.0
2526  *
2527  * @param string|array $args Value to merge with $defaults
2528  * @param array $defaults Array that serves as the defaults.
2529  * @return array Merged user defined values with defaults.
2530  */
2531 function wp_parse_args( $args, $defaults = '' ) {
2532         if ( is_object( $args ) )
2533                 $r = get_object_vars( $args );
2534         elseif ( is_array( $args ) )
2535                 $r =& $args;
2536         else
2537                 wp_parse_str( $args, $r );
2538
2539         if ( is_array( $defaults ) )
2540                 return array_merge( $defaults, $r );
2541         return $r;
2542 }
2543
2544 /**
2545  * Clean up an array, comma- or space-separated list of IDs.
2546  *
2547  * @since 3.0.0
2548  *
2549  * @param array|string $list
2550  * @return array Sanitized array of IDs
2551  */
2552 function wp_parse_id_list( $list ) {
2553         if ( !is_array($list) )
2554                 $list = preg_split('/[\s,]+/', $list);
2555
2556         return array_unique(array_map('absint', $list));
2557 }
2558
2559 /**
2560  * Extract a slice of an array, given a list of keys.
2561  *
2562  * @since 3.1.0
2563  *
2564  * @param array $array The original array
2565  * @param array $keys The list of keys
2566  * @return array The array slice
2567  */
2568 function wp_array_slice_assoc( $array, $keys ) {
2569         $slice = array();
2570         foreach ( $keys as $key )
2571                 if ( isset( $array[ $key ] ) )
2572                         $slice[ $key ] = $array[ $key ];
2573
2574         return $slice;
2575 }
2576
2577 /**
2578  * Filters a list of objects, based on a set of key => value arguments.
2579  *
2580  * @since 3.0.0
2581  *
2582  * @param array $list An array of objects to filter
2583  * @param array $args An array of key => value arguments to match against each object
2584  * @param string $operator The logical operation to perform. 'or' means only one element
2585  *      from the array needs to match; 'and' means all elements must match. The default is 'and'.
2586  * @param bool|string $field A field from the object to place instead of the entire object
2587  * @return array A list of objects or object fields
2588  */
2589 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
2590         if ( ! is_array( $list ) )
2591                 return array();
2592
2593         $list = wp_list_filter( $list, $args, $operator );
2594
2595         if ( $field )
2596                 $list = wp_list_pluck( $list, $field );
2597
2598         return $list;
2599 }
2600
2601 /**
2602  * Filters a list of objects, based on a set of key => value arguments.
2603  *
2604  * @since 3.1.0
2605  *
2606  * @param array $list An array of objects to filter
2607  * @param array $args An array of key => value arguments to match against each object
2608  * @param string $operator The logical operation to perform:
2609  *    'AND' means all elements from the array must match;
2610  *    'OR' means only one element needs to match;
2611  *    'NOT' means no elements may match.
2612  *   The default is 'AND'.
2613  * @return array
2614  */
2615 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
2616         if ( ! is_array( $list ) )
2617                 return array();
2618
2619         if ( empty( $args ) )
2620                 return $list;
2621
2622         $operator = strtoupper( $operator );
2623         $count = count( $args );
2624         $filtered = array();
2625
2626         foreach ( $list as $key => $obj ) {
2627                 $to_match = (array) $obj;
2628
2629                 $matched = 0;
2630                 foreach ( $args as $m_key => $m_value ) {
2631                         if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
2632                                 $matched++;
2633                 }
2634
2635                 if ( ( 'AND' == $operator && $matched == $count )
2636                   || ( 'OR' == $operator && $matched > 0 )
2637                   || ( 'NOT' == $operator && 0 == $matched ) ) {
2638                         $filtered[$key] = $obj;
2639                 }
2640         }
2641
2642         return $filtered;
2643 }
2644
2645 /**
2646  * Pluck a certain field out of each object in a list.
2647  *
2648  * @since 3.1.0
2649  *
2650  * @param array $list A list of objects or arrays
2651  * @param int|string $field A field from the object to place instead of the entire object
2652  * @return array
2653  */
2654 function wp_list_pluck( $list, $field ) {
2655         foreach ( $list as $key => $value ) {
2656                 if ( is_object( $value ) )
2657                         $list[ $key ] = $value->$field;
2658                 else
2659                         $list[ $key ] = $value[ $field ];
2660         }
2661
2662         return $list;
2663 }
2664
2665 /**
2666  * Determines if Widgets library should be loaded.
2667  *
2668  * Checks to make sure that the widgets library hasn't already been loaded. If
2669  * it hasn't, then it will load the widgets library and run an action hook.
2670  *
2671  * @since 2.2.0
2672  * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
2673  */
2674 function wp_maybe_load_widgets() {
2675         if ( ! apply_filters('load_default_widgets', true) )
2676                 return;
2677         require_once( ABSPATH . WPINC . '/default-widgets.php' );
2678         add_action( '_admin_menu', 'wp_widgets_add_menu' );
2679 }
2680
2681 /**
2682  * Append the Widgets menu to the themes main menu.
2683  *
2684  * @since 2.2.0
2685  * @uses $submenu The administration submenu list.
2686  */
2687 function wp_widgets_add_menu() {
2688         global $submenu;
2689
2690         if ( ! current_theme_supports( 'widgets' ) )
2691                 return;
2692
2693         $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
2694         ksort( $submenu['themes.php'], SORT_NUMERIC );
2695 }
2696
2697 /**
2698  * Flush all output buffers for PHP 5.2.
2699  *
2700  * Make sure all output buffers are flushed before our singletons our destroyed.
2701  *
2702  * @since 2.2.0
2703  */
2704 function wp_ob_end_flush_all() {
2705         $levels = ob_get_level();
2706         for ($i=0; $i<$levels; $i++)
2707                 ob_end_flush();
2708 }
2709
2710 /**
2711  * Load custom DB error or display WordPress DB error.
2712  *
2713  * If a file exists in the wp-content directory named db-error.php, then it will
2714  * be loaded instead of displaying the WordPress DB error. If it is not found,
2715  * then the WordPress DB error will be displayed instead.
2716  *
2717  * The WordPress DB error sets the HTTP status header to 500 to try to prevent
2718  * search engines from caching the message. Custom DB messages should do the
2719  * same.
2720  *
2721  * This function was backported to the the WordPress 2.3.2, but originally was
2722  * added in WordPress 2.5.0.
2723  *
2724  * @since 2.3.2
2725  * @uses $wpdb
2726  */
2727 function dead_db() {
2728         global $wpdb;
2729
2730         // Load custom DB error template, if present.
2731         if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
2732                 require_once( WP_CONTENT_DIR . '/db-error.php' );
2733                 die();
2734         }
2735
2736         // If installing or in the admin, provide the verbose message.
2737         if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
2738                 wp_die($wpdb->error);
2739
2740         // Otherwise, be terse.
2741         status_header( 500 );
2742         nocache_headers();
2743         header( 'Content-Type: text/html; charset=utf-8' );
2744
2745         wp_load_translations_early();
2746 ?>
2747 <!DOCTYPE html>
2748 <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
2749 <head>
2750 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2751         <title><?php _e( 'Database Error' ); ?></title>
2752
2753 </head>
2754 <body>
2755         <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
2756 </body>
2757 </html>
2758 <?php
2759         die();
2760 }
2761
2762 /**
2763  * Converts value to nonnegative integer.
2764  *
2765  * @since 2.5.0
2766  *
2767  * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
2768  * @return int An nonnegative integer
2769  */
2770 function absint( $maybeint ) {
2771         return abs( intval( $maybeint ) );
2772 }
2773
2774 /**
2775  * Determines if the blog can be accessed over SSL.
2776  *
2777  * Determines if blog can be accessed over SSL by using cURL to access the site
2778  * using the https in the siteurl. Requires cURL extension to work correctly.
2779  *
2780  * @since 2.5.0
2781  *
2782  * @param string $url
2783  * @return bool Whether SSL access is available
2784  */
2785 function url_is_accessable_via_ssl($url)
2786 {
2787         if ( in_array( 'curl', get_loaded_extensions() ) ) {
2788                 $ssl = set_url_scheme( $url, 'https' );
2789
2790                 $ch = curl_init();
2791                 curl_setopt($ch, CURLOPT_URL, $ssl);
2792                 curl_setopt($ch, CURLOPT_FAILONERROR, true);
2793                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2794                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
2795                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
2796
2797                 curl_exec($ch);
2798
2799                 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2800                 curl_close ($ch);
2801
2802                 if ($status == 200 || $status == 401) {
2803                         return true;
2804                 }
2805         }
2806         return false;
2807 }
2808
2809 /**
2810  * Marks a function as deprecated and informs when it has been used.
2811  *
2812  * There is a hook deprecated_function_run that will be called that can be used
2813  * to get the backtrace up to what file and function called the deprecated
2814  * function.
2815  *
2816  * The current behavior is to trigger a user error if WP_DEBUG is true.
2817  *
2818  * This function is to be used in every function that is deprecated.
2819  *
2820  * @package WordPress
2821  * @subpackage Debug
2822  * @since 2.5.0
2823  * @access private
2824  *
2825  * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
2826  *   and the version the function was deprecated in.
2827  * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2828  *   trigger or false to not trigger error.
2829  *
2830  * @param string $function The function that was called
2831  * @param string $version The version of WordPress that deprecated the function
2832  * @param string $replacement Optional. The function that should have been called
2833  */
2834 function _deprecated_function( $function, $version, $replacement = null ) {
2835
2836         do_action( 'deprecated_function_run', $function, $replacement, $version );
2837
2838         // Allow plugin to filter the output error trigger
2839         if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
2840                 if ( ! is_null($replacement) )
2841                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2842                 else
2843                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2844         }
2845 }
2846
2847 /**
2848  * Marks a file as deprecated and informs when it has been used.
2849  *
2850  * There is a hook deprecated_file_included that will be called that can be used
2851  * to get the backtrace up to what file and function included the deprecated
2852  * file.
2853  *
2854  * The current behavior is to trigger a user error if WP_DEBUG is true.
2855  *
2856  * This function is to be used in every file that is deprecated.
2857  *
2858  * @package WordPress
2859  * @subpackage Debug
2860  * @since 2.5.0
2861  * @access private
2862  *
2863  * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
2864  *   the version in which the file was deprecated, and any message regarding the change.
2865  * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
2866  *   trigger or false to not trigger error.
2867  *
2868  * @param string $file The file that was included
2869  * @param string $version The version of WordPress that deprecated the file
2870  * @param string $replacement Optional. The file that should have been included based on ABSPATH
2871  * @param string $message Optional. A message regarding the change
2872  */
2873 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
2874
2875         do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
2876
2877         // Allow plugin to filter the output error trigger
2878         if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
2879                 $message = empty( $message ) ? '' : ' ' . $message;
2880                 if ( ! is_null( $replacement ) )
2881                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
2882                 else
2883                         trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
2884         }
2885 }
2886 /**
2887  * Marks a function argument as deprecated and informs when it has been used.
2888  *
2889  * This function is to be used whenever a deprecated function argument is used.
2890  * Before this function is called, the argument must be checked for whether it was
2891  * used by comparing it to its default value or evaluating whether it is empty.
2892  * For example:
2893  * <code>
2894  * if ( !empty($deprecated) )
2895  *      _deprecated_argument( __FUNCTION__, '3.0' );
2896  * </code>
2897  *
2898  * There is a hook deprecated_argument_run that will be called that can be used
2899  * to get the backtrace up to what file and function used the deprecated
2900  * argument.
2901  *
2902  * The current behavior is to trigger a user error if WP_DEBUG is true.
2903  *
2904  * @package WordPress
2905  * @subpackage Debug
2906  * @since 3.0.0
2907  * @access private
2908  *
2909  * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
2910  *   and the version in which the argument was deprecated.
2911  * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
2912  *   trigger or false to not trigger error.
2913  *
2914  * @param string $function The function that was called
2915  * @param string $version The version of WordPress that deprecated the argument used
2916  * @param string $message Optional. A message regarding the change.
2917  */
2918 function _deprecated_argument( $function, $version, $message = null ) {
2919
2920         do_action( 'deprecated_argument_run', $function, $message, $version );
2921
2922         // Allow plugin to filter the output error trigger
2923         if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
2924                 if ( ! is_null( $message ) )
2925                         trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
2926                 else
2927                         trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2928         }
2929 }
2930
2931 /**
2932  * Marks something as being incorrectly called.
2933  *
2934  * There is a hook doing_it_wrong_run that will be called that can be used
2935  * to get the backtrace up to what file and function called the deprecated
2936  * function.
2937  *
2938  * The current behavior is to trigger a user error if WP_DEBUG is true.
2939  *
2940  * @package WordPress
2941  * @subpackage Debug
2942  * @since 3.1.0
2943  * @access private
2944  *
2945  * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
2946  * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
2947  *   trigger or false to not trigger error.
2948  *
2949  * @param string $function The function that was called.
2950  * @param string $message A message explaining what has been done incorrectly.
2951  * @param string $version The version of WordPress where the message was added.
2952  */
2953 function _doing_it_wrong( $function, $message, $version ) {
2954
2955         do_action( 'doing_it_wrong_run', $function, $message, $version );
2956
2957         // Allow plugin to filter the output error trigger
2958         if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
2959                 if ( function_exists( '__' ) ) {
2960                         $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
2961                         $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
2962                         trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
2963                 } else {
2964                         $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
2965                         $message .= ' Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.';
2966                         trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
2967                 }
2968         }
2969 }
2970
2971 /**
2972  * Is the server running earlier than 1.5.0 version of lighttpd?
2973  *
2974  * @since 2.5.0
2975  *
2976  * @return bool Whether the server is running lighttpd < 1.5.0
2977  */
2978 function is_lighttpd_before_150() {
2979         $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
2980         $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
2981         return  'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
2982 }
2983
2984 /**
2985  * Does the specified module exist in the Apache config?
2986  *
2987  * @since 2.5.0
2988  *
2989  * @param string $mod e.g. mod_rewrite
2990  * @param bool $default The default return value if the module is not found
2991  * @return bool
2992  */
2993 function apache_mod_loaded($mod, $default = false) {
2994         global $is_apache;
2995
2996         if ( !$is_apache )
2997                 return false;
2998
2999         if ( function_exists('apache_get_modules') ) {
3000                 $mods = apache_get_modules();
3001                 if ( in_array($mod, $mods) )
3002                         return true;
3003         } elseif ( function_exists('phpinfo') ) {
3004                         ob_start();
3005                         phpinfo(8);
3006                         $phpinfo = ob_get_clean();
3007                         if ( false !== strpos($phpinfo, $mod) )
3008                                 return true;
3009         }
3010         return $default;
3011 }
3012
3013 /**
3014  * Check if IIS 7 supports pretty permalinks.
3015  *
3016  * @since 2.8.0
3017  *
3018  * @return bool
3019  */
3020 function iis7_supports_permalinks() {
3021         global $is_iis7;
3022
3023         $supports_permalinks = false;
3024         if ( $is_iis7 ) {
3025                 /* First we check if the DOMDocument class exists. If it does not exist,
3026                  * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
3027                  * hence we just bail out and tell user that pretty permalinks cannot be used.
3028                  * This is not a big issue because PHP 4.X is going to be deprecated and for IIS it
3029                  * is recommended to use PHP 5.X NTS.
3030                  * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
3031                  * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
3032                  * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
3033                  * via ISAPI then pretty permalinks will not work.
3034                  */
3035                 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
3036         }
3037
3038         return apply_filters('iis7_supports_permalinks', $supports_permalinks);
3039 }
3040
3041 /**
3042  * File validates against allowed set of defined rules.
3043  *
3044  * A return value of '1' means that the $file contains either '..' or './'. A
3045  * return value of '2' means that the $file contains ':' after the first
3046  * character. A return value of '3' means that the file is not in the allowed
3047  * files list.
3048  *
3049  * @since 1.2.0
3050  *
3051  * @param string $file File path.
3052  * @param array $allowed_files List of allowed files.
3053  * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
3054  */
3055 function validate_file( $file, $allowed_files = '' ) {
3056         if ( false !== strpos( $file, '..' ) )
3057                 return 1;
3058
3059         if ( false !== strpos( $file, './' ) )
3060                 return 1;
3061
3062         if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
3063                 return 3;
3064
3065         if (':' == substr( $file, 1, 1 ) )
3066                 return 2;
3067
3068         return 0;
3069 }
3070
3071 /**
3072  * Determine if SSL is used.
3073  *
3074  * @since 2.6.0
3075  *
3076  * @return bool True if SSL, false if not used.
3077  */
3078 function is_ssl() {
3079         if ( isset($_SERVER['HTTPS']) ) {
3080                 if ( 'on' == strtolower($_SERVER['HTTPS']) )
3081                         return true;
3082                 if ( '1' == $_SERVER['HTTPS'] )
3083                         return true;
3084         } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
3085                 return true;
3086         }
3087         return false;
3088 }
3089
3090 /**
3091  * Whether SSL login should be forced.
3092  *
3093  * @since 2.6.0
3094  *
3095  * @param string|bool $force Optional.
3096  * @return bool True if forced, false if not forced.
3097  */
3098 function force_ssl_login( $force = null ) {
3099         static $forced = false;
3100
3101         if ( !is_null( $force ) ) {
3102                 $old_forced = $forced;
3103                 $forced = $force;
3104                 return $old_forced;
3105         }
3106
3107         return $forced;
3108 }
3109
3110 /**
3111  * Whether to force SSL used for the Administration Screens.
3112  *
3113  * @since 2.6.0
3114  *
3115  * @param string|bool $force
3116  * @return bool True if forced, false if not forced.
3117  */
3118 function force_ssl_admin( $force = null ) {
3119         static $forced = false;
3120
3121         if ( !is_null( $force ) ) {
3122                 $old_forced = $forced;
3123                 $forced = $force;
3124                 return $old_forced;
3125         }
3126
3127         return $forced;
3128 }
3129
3130 /**
3131  * Guess the URL for the site.
3132  *
3133  * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
3134  * directory.
3135  *
3136  * @since 2.6.0
3137  *
3138  * @return string
3139  */
3140 function wp_guess_url() {
3141         if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
3142                 $url = WP_SITEURL;
3143         } else {
3144                 $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
3145                 $url = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
3146         }
3147
3148         return rtrim($url, '/');
3149 }
3150
3151 /**
3152  * Temporarily suspend cache additions.
3153  *
3154  * Stops more data being added to the cache, but still allows cache retrieval.
3155  * This is useful for actions, such as imports, when a lot of data would otherwise
3156  * be almost uselessly added to the cache.
3157  *
3158  * Suspension lasts for a single page load at most. Remember to call this
3159  * function again if you wish to re-enable cache adds earlier.
3160  *
3161  * @since 3.3.0
3162  *
3163  * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
3164  * @return bool The current suspend setting
3165  */
3166 function wp_suspend_cache_addition( $suspend = null ) {
3167         static $_suspend = false;
3168
3169         if ( is_bool( $suspend ) )
3170                 $_suspend = $suspend;
3171
3172         return $_suspend;
3173 }
3174
3175 /**
3176  * Suspend cache invalidation.
3177  *
3178  * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
3179  * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
3180  * cache when invalidation is suspended.
3181  *
3182  * @since 2.7.0
3183  *
3184  * @param bool $suspend Whether to suspend or enable cache invalidation
3185  * @return bool The current suspend setting
3186  */
3187 function wp_suspend_cache_invalidation($suspend = true) {
3188         global $_wp_suspend_cache_invalidation;
3189
3190         $current_suspend = $_wp_suspend_cache_invalidation;
3191         $_wp_suspend_cache_invalidation = $suspend;
3192         return $current_suspend;
3193 }
3194
3195 /**
3196  * Is main site?
3197  *
3198  *
3199  * @since 3.0.0
3200  * @package WordPress
3201  *
3202  * @param int $blog_id optional blog id to test (default current blog)
3203  * @return bool True if not multisite or $blog_id is main site
3204  */
3205 function is_main_site( $blog_id = '' ) {
3206         global $current_site;
3207
3208         if ( ! is_multisite() )
3209                 return true;
3210
3211         if ( ! $blog_id )
3212                 $blog_id = get_current_blog_id();
3213
3214         return $blog_id == $current_site->blog_id;
3215 }
3216
3217 /**
3218  * Whether global terms are enabled.
3219  *
3220  *
3221  * @since 3.0.0
3222  * @package WordPress
3223  *
3224  * @return bool True if multisite and global terms enabled
3225  */
3226 function global_terms_enabled() {
3227         if ( ! is_multisite() )
3228                 return false;
3229
3230         static $global_terms = null;
3231         if ( is_null( $global_terms ) ) {
3232                 $filter = apply_filters( 'global_terms_enabled', null );
3233                 if ( ! is_null( $filter ) )
3234                         $global_terms = (bool) $filter;
3235                 else
3236                         $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
3237         }
3238         return $global_terms;
3239 }
3240
3241 /**
3242  * gmt_offset modification for smart timezone handling.
3243  *
3244  * Overrides the gmt_offset option if we have a timezone_string available.
3245  *
3246  * @since 2.8.0
3247  *
3248  * @return float|bool
3249  */
3250 function wp_timezone_override_offset() {
3251         if ( !$timezone_string = get_option( 'timezone_string' ) ) {
3252                 return false;
3253         }
3254
3255         $timezone_object = timezone_open( $timezone_string );
3256         $datetime_object = date_create();
3257         if ( false === $timezone_object || false === $datetime_object ) {
3258                 return false;
3259         }
3260         return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
3261 }
3262
3263 /**
3264  * {@internal Missing Short Description}}
3265  *
3266  * @since 2.9.0
3267  *
3268  * @param unknown_type $a
3269  * @param unknown_type $b
3270  * @return int
3271  */
3272 function _wp_timezone_choice_usort_callback( $a, $b ) {
3273         // Don't use translated versions of Etc
3274         if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
3275                 // Make the order of these more like the old dropdown
3276                 if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3277                         return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
3278                 }
3279                 if ( 'UTC' === $a['city'] ) {
3280                         if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3281                                 return 1;
3282                         }
3283                         return -1;
3284                 }
3285                 if ( 'UTC' === $b['city'] ) {
3286                         if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
3287                                 return -1;
3288                         }
3289                         return 1;
3290                 }
3291                 return strnatcasecmp( $a['city'], $b['city'] );
3292         }
3293         if ( $a['t_continent'] == $b['t_continent'] ) {
3294                 if ( $a['t_city'] == $b['t_city'] ) {
3295                         return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
3296                 }
3297                 return strnatcasecmp( $a['t_city'], $b['t_city'] );
3298         } else {
3299                 // Force Etc to the bottom of the list
3300                 if ( 'Etc' === $a['continent'] ) {
3301                         return 1;
3302                 }
3303                 if ( 'Etc' === $b['continent'] ) {
3304                         return -1;
3305                 }
3306                 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
3307         }
3308 }
3309
3310 /**
3311  * Gives a nicely formatted list of timezone strings. // temporary! Not in final
3312  *
3313  * @since 2.9.0
3314  *
3315  * @param string $selected_zone Selected Zone
3316  * @return string
3317  */
3318 function wp_timezone_choice( $selected_zone ) {
3319         static $mo_loaded = false;
3320
3321         $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
3322
3323         // Load translations for continents and cities
3324         if ( !$mo_loaded ) {
3325                 $locale = get_locale();
3326                 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
3327                 load_textdomain( 'continents-cities', $mofile );
3328                 $mo_loaded = true;
3329         }
3330
3331         $zonen = array();
3332         foreach ( timezone_identifiers_list() as $zone ) {
3333                 $zone = explode( '/', $zone );
3334                 if ( !in_array( $zone[0], $continents ) ) {
3335                         continue;
3336                 }
3337
3338                 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
3339                 $exists = array(
3340                         0 => ( isset( $zone[0] ) && $zone[0] ),
3341                         1 => ( isset( $zone[1] ) && $zone[1] ),
3342                         2 => ( isset( $zone[2] ) && $zone[2] ),
3343                 );
3344                 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
3345                 $exists[4] = ( $exists[1] && $exists[3] );
3346                 $exists[5] = ( $exists[2] && $exists[3] );
3347
3348                 $zonen[] = array(
3349                         'continent'   => ( $exists[0] ? $zone[0] : '' ),
3350                         'city'        => ( $exists[1] ? $zone[1] : '' ),
3351                         'subcity'     => ( $exists[2] ? $zone[2] : '' ),
3352                         't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
3353                         't_city'      => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
3354                         't_subcity'   => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
3355                 );
3356         }
3357         usort( $zonen, '_wp_timezone_choice_usort_callback' );
3358
3359         $structure = array();
3360
3361         if ( empty( $selected_zone ) ) {
3362                 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
3363         }
3364
3365         foreach ( $zonen as $key => $zone ) {
3366                 // Build value in an array to join later
3367                 $value = array( $zone['continent'] );
3368
3369                 if ( empty( $zone['city'] ) ) {
3370                         // It's at the continent level (generally won't happen)
3371                         $display = $zone['t_continent'];
3372                 } else {
3373                         // It's inside a continent group
3374
3375                         // Continent optgroup
3376                         if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
3377                                 $label = $zone['t_continent'];
3378                                 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
3379                         }
3380
3381                         // Add the city to the value
3382                         $value[] = $zone['city'];
3383
3384                         $display = $zone['t_city'];
3385                         if ( !empty( $zone['subcity'] ) ) {
3386                                 // Add the subcity to the value
3387                                 $value[] = $zone['subcity'];
3388                                 $display .= ' - ' . $zone['t_subcity'];
3389                         }
3390                 }
3391
3392                 // Build the value
3393                 $value = join( '/', $value );
3394                 $selected = '';
3395                 if ( $value === $selected_zone ) {
3396                         $selected = 'selected="selected" ';
3397                 }
3398                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
3399
3400                 // Close continent optgroup
3401                 if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
3402                         $structure[] = '</optgroup>';
3403                 }
3404         }
3405
3406         // Do UTC
3407         $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
3408         $selected = '';
3409         if ( 'UTC' === $selected_zone )
3410                 $selected = 'selected="selected" ';
3411         $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
3412         $structure[] = '</optgroup>';
3413
3414         // Do manual UTC offsets
3415         $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
3416         $offset_range = array (-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
3417                 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14);
3418         foreach ( $offset_range as $offset ) {
3419                 if ( 0 <= $offset )
3420                         $offset_name = '+' . $offset;
3421                 else
3422                         $offset_name = (string) $offset;
3423
3424                 $offset_value = $offset_name;
3425                 $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
3426                 $offset_name = 'UTC' . $offset_name;
3427                 $offset_value = 'UTC' . $offset_value;
3428                 $selected = '';
3429                 if ( $offset_value === $selected_zone )
3430                         $selected = 'selected="selected" ';
3431                 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
3432
3433         }
3434         $structure[] = '</optgroup>';
3435
3436         return join( "\n", $structure );
3437 }
3438
3439 /**
3440  * Strip close comment and close php tags from file headers used by WP.
3441  * See http://core.trac.wordpress.org/ticket/8497
3442  *
3443  * @since 2.8.0
3444  *
3445  * @param string $str
3446  * @return string
3447  */
3448 function _cleanup_header_comment($str) {
3449         return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
3450 }
3451
3452 /**
3453  * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
3454  *
3455  * @since 2.9.0
3456  */
3457 function wp_scheduled_delete() {
3458         global $wpdb;
3459
3460         $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
3461
3462         $posts_to_delete = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
3463
3464         foreach ( (array) $posts_to_delete as $post ) {
3465                 $post_id = (int) $post['post_id'];
3466                 if ( !$post_id )
3467                         continue;
3468
3469                 $del_post = get_post($post_id);
3470
3471                 if ( !$del_post || 'trash' != $del_post->post_status ) {
3472                         delete_post_meta($post_id, '_wp_trash_meta_status');
3473                         delete_post_meta($post_id, '_wp_trash_meta_time');
3474                 } else {
3475                         wp_delete_post($post_id);
3476                 }
3477         }
3478
3479         $comments_to_delete = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
3480
3481         foreach ( (array) $comments_to_delete as $comment ) {
3482                 $comment_id = (int) $comment['comment_id'];
3483                 if ( !$comment_id )
3484                         continue;
3485
3486                 $del_comment = get_comment($comment_id);
3487
3488                 if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
3489                         delete_comment_meta($comment_id, '_wp_trash_meta_time');
3490                         delete_comment_meta($comment_id, '_wp_trash_meta_status');
3491                 } else {
3492                         wp_delete_comment($comment_id);
3493                 }
3494         }
3495 }
3496
3497 /**
3498  * Retrieve metadata from a file.
3499  *
3500  * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
3501  * Each piece of metadata must be on its own line. Fields can not span multiple
3502  * lines, the value will get cut at the end of the first line.
3503  *
3504  * If the file data is not within that first 8kiB, then the author should correct
3505  * their plugin file and move the data headers to the top.
3506  *
3507  * @see http://codex.wordpress.org/File_Header
3508  *
3509  * @since 2.9.0
3510  * @param string $file Path to the file
3511  * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
3512  * @param string $context If specified adds filter hook "extra_{$context}_headers"
3513  */
3514 function get_file_data( $file, $default_headers, $context = '' ) {
3515         // We don't need to write to the file, so just open for reading.
3516         $fp = fopen( $file, 'r' );
3517
3518         // Pull only the first 8kiB of the file in.
3519         $file_data = fread( $fp, 8192 );
3520
3521         // PHP will close file handle, but we are good citizens.
3522         fclose( $fp );
3523
3524         // Make sure we catch CR-only line endings.
3525         $file_data = str_replace( "\r", "\n", $file_data );
3526
3527         if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
3528                 $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
3529                 $all_headers = array_merge( $extra_headers, (array) $default_headers );
3530         } else {
3531                 $all_headers = $default_headers;
3532         }
3533
3534         foreach ( $all_headers as $field => $regex ) {
3535                 if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
3536                         $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
3537                 else
3538                         $all_headers[ $field ] = '';
3539         }
3540
3541         return $all_headers;
3542 }
3543
3544 /**
3545  * Used internally to tidy up the search terms.
3546  *
3547  * @access private
3548  * @since 2.9.0
3549  *
3550  * @param string $t
3551  * @return string
3552  */
3553 function _search_terms_tidy($t) {
3554         return trim($t, "\"'\n\r ");
3555 }
3556
3557 /**
3558  * Returns true.
3559  *
3560  * Useful for returning true to filters easily.
3561  *
3562  * @since 3.0.0
3563  * @see __return_false()
3564  * @return bool true
3565  */
3566 function __return_true() {
3567         return true;
3568 }
3569
3570 /**
3571  * Returns false.
3572  *
3573  * Useful for returning false to filters easily.
3574  *
3575  * @since 3.0.0
3576  * @see __return_true()
3577  * @return bool false
3578  */
3579 function __return_false() {
3580         return false;
3581 }
3582
3583 /**
3584  * Returns 0.
3585  *
3586  * Useful for returning 0 to filters easily.
3587  *
3588  * @since 3.0.0
3589  * @see __return_zero()
3590  * @return int 0
3591  */
3592 function __return_zero() {
3593         return 0;
3594 }
3595
3596 /**
3597  * Returns an empty array.
3598  *
3599  * Useful for returning an empty array to filters easily.
3600  *
3601  * @since 3.0.0
3602  * @see __return_zero()
3603  * @return array Empty array
3604  */
3605 function __return_empty_array() {
3606         return array();
3607 }
3608
3609 /**
3610  * Returns null.
3611  *
3612  * Useful for returning null to filters easily.
3613  *
3614  * @since 3.4.0
3615  * @return null
3616  */
3617 function __return_null() {
3618         return null;
3619 }
3620
3621 /**
3622  * Send a HTTP header to disable content type sniffing in browsers which support it.
3623  *
3624  * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
3625  * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
3626  *
3627  * @since 3.0.0
3628  * @return none
3629  */
3630 function send_nosniff_header() {
3631         @header( 'X-Content-Type-Options: nosniff' );
3632 }
3633
3634 /**
3635  * Returns a MySQL expression for selecting the week number based on the start_of_week option.
3636  *
3637  * @internal
3638  * @since 3.0.0
3639  * @param string $column
3640  * @return string
3641  */
3642 function _wp_mysql_week( $column ) {
3643         switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
3644         default :
3645         case 0 :
3646                 return "WEEK( $column, 0 )";
3647         case 1 :
3648                 return "WEEK( $column, 1 )";
3649         case 2 :
3650         case 3 :
3651         case 4 :
3652         case 5 :
3653         case 6 :
3654                 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
3655         }
3656 }
3657
3658 /**
3659  * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
3660  *
3661  * @since 3.1.0
3662  * @access private
3663  *
3664  * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
3665  * @param int $start The ID to start the loop check at
3666  * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
3667  * @param array $callback_args optional additional arguments to send to $callback
3668  * @return array IDs of all members of loop
3669  */
3670 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
3671         $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
3672
3673         if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
3674                 return array();
3675
3676         return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
3677 }
3678
3679 /**
3680  * Uses the "The Tortoise and the Hare" algorithm to detect loops.
3681  *
3682  * For every step of the algorithm, the hare takes two steps and the tortoise one.
3683  * If the hare ever laps the tortoise, there must be a loop.
3684  *
3685  * @since 3.1.0
3686  * @access private
3687  *
3688  * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
3689  * @param int $start The ID to start the loop check at
3690  * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
3691  * @param array $callback_args optional additional arguments to send to $callback
3692  * @param bool $_return_loop Return loop members or just detect presence of loop?
3693  *             Only set to true if you already know the given $start is part of a loop
3694  *             (otherwise the returned array might include branches)
3695  * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
3696  */
3697 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
3698         $tortoise = $hare = $evanescent_hare = $start;
3699         $return = array();
3700
3701         // Set evanescent_hare to one past hare
3702         // Increment hare two steps
3703         while (
3704                 $tortoise
3705         &&
3706                 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
3707         &&
3708                 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
3709         ) {
3710                 if ( $_return_loop )
3711                         $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
3712
3713                 // tortoise got lapped - must be a loop
3714                 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
3715                         return $_return_loop ? $return : $tortoise;
3716
3717                 // Increment tortoise by one step
3718                 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
3719         }
3720
3721         return false;
3722 }
3723
3724 /**
3725  * Send a HTTP header to limit rendering of pages to same origin iframes.
3726  *
3727  * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
3728  *
3729  * @since 3.1.3
3730  * @return none
3731  */
3732 function send_frame_options_header() {
3733         @header( 'X-Frame-Options: SAMEORIGIN' );
3734 }
3735
3736 /**
3737  * Retrieve a list of protocols to allow in HTML attributes.
3738  *
3739  * @since 3.3.0
3740  * @see wp_kses()
3741  * @see esc_url()
3742  *
3743  * @return array Array of allowed protocols
3744  */
3745 function wp_allowed_protocols() {
3746         static $protocols;
3747
3748         if ( empty( $protocols ) ) {
3749                 $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
3750                 $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
3751         }
3752
3753         return $protocols;
3754 }
3755
3756 /**
3757  * Return a comma separated string of functions that have been called to get to the current point in code.
3758  *
3759  * @link http://core.trac.wordpress.org/ticket/19589
3760  * @since 3.4
3761  *
3762  * @param string $ignore_class A class to ignore all function calls within - useful when you want to just give info about the callee
3763  * @param int $skip_frames A number of stack frames to skip - useful for unwinding back to the source of the issue
3764  * @param bool $pretty Whether or not you want a comma separated string or raw array returned
3765  * @return string|array Either a string containing a reversed comma separated trace or an array of individual calls.
3766  */
3767 function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
3768         if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
3769                 $trace = debug_backtrace( false );
3770         else
3771                 $trace = debug_backtrace();
3772
3773         $caller = array();
3774         $check_class = ! is_null( $ignore_class );
3775         $skip_frames++; // skip this function
3776
3777         foreach ( $trace as $call ) {
3778                 if ( $skip_frames > 0 ) {
3779                         $skip_frames--;
3780                 } elseif ( isset( $call['class'] ) ) {
3781                         if ( $check_class && $ignore_class == $call['class'] )
3782                                 continue; // Filter out calls
3783
3784                         $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
3785                 } else {
3786                         if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
3787                                 $caller[] = "{$call['function']}('{$call['args'][0]}')";
3788                         } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
3789                                 $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
3790                         } else {
3791                                 $caller[] = $call['function'];
3792                         }
3793                 }
3794         }
3795         if ( $pretty )
3796                 return join( ', ', array_reverse( $caller ) );
3797         else
3798                 return $caller;
3799 }
3800
3801 /**
3802  * Retrieve ids that are not already present in the cache
3803  *
3804  * @since 3.4.0
3805  *
3806  * @param array $object_ids ID list
3807  * @param string $cache_key The cache bucket to check against
3808  *
3809  * @return array
3810  */
3811 function _get_non_cached_ids( $object_ids, $cache_key ) {
3812         $clean = array();
3813         foreach ( $object_ids as $id ) {
3814                 $id = (int) $id;
3815                 if ( !wp_cache_get( $id, $cache_key ) ) {
3816                         $clean[] = $id;
3817                 }
3818         }
3819
3820         return $clean;
3821 }
3822
3823 /**
3824  * Test if the current device has the capability to upload files.
3825  *
3826  * @since 3.4.0
3827  * @access private
3828  *
3829  * @return bool true|false
3830  */
3831 function _device_can_upload() {
3832         if ( ! wp_is_mobile() )
3833                 return true;
3834
3835         $ua = $_SERVER['HTTP_USER_AGENT'];
3836
3837         if ( strpos($ua, 'iPhone') !== false
3838                 || strpos($ua, 'iPad') !== false
3839                 || strpos($ua, 'iPod') !== false ) {
3840                         return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
3841         }
3842
3843         return true;
3844 }
3845
3846 /**
3847  * Test if a given path is a stream URL
3848  *
3849  * @param string $path The resource path or URL
3850  * @return bool True if the path is a stream URL
3851  */
3852 function wp_is_stream( $path ) {
3853         $wrappers = stream_get_wrappers();
3854         $wrappers_re = '(' . join('|', $wrappers) . ')';
3855
3856         return preg_match( "!^$wrappers_re://!", $path ) === 1;
3857 }
3858
3859 /**
3860  * Test if the supplied date is valid for the Gregorian calendar
3861  *
3862  * @since 3.5.0
3863  *
3864  * @return bool true|false
3865  */
3866 function wp_checkdate( $month, $day, $year, $source_date ) {
3867         return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
3868 }