Make WordPress Core

Ticket #22423: functions.php

File functions.php, 115.4 KB (added by MatthewRuddy, 14 years ago)

Said modification to wp-includes/functions.php file

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