8 require( ABSPATH . WPINC . '/option.php' );
11 * Converts given date string into a different format.
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.
16 * If $translate is true then the given date and format string will
17 * be passed to date_i18n() for translation.
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.
26 function mysql2date( $format, $date, $translate = true ) {
31 return strtotime( $date . ' +0000' );
33 $i = strtotime( $date );
39 return date_i18n( $format, $i );
41 return date( $format, $i );
45 * Retrieve the current time based on specified type.
47 * The 'mysql' type will return the time in the format for MySQL DATETIME field.
48 * The 'timestamp' type will return the current timestamp.
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.
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'.
59 function current_time( $type, $gmt = 0 ) {
62 return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
65 return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
71 * Retrieve the date in localized format, based on timestamp.
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.
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.
84 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
90 $i = current_time( 'timestamp' );
93 // we should not let date() interfere with our
94 // specially computed timestamp
98 // store original value for language with untypical grammars
99 // see http://core.trac.wordpress.org/ticket/9396
100 $req_format = $dateformatstring;
102 $datefunc = $gmt? 'gmdate' : 'date';
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 );
119 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
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 );
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);
145 * Convert integer number to format based on the locale.
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.
153 function number_format_i18n( $number, $decimals = 0 ) {
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 );
160 * Convert number of bytes largest unit bytes will fit into.
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.
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.
171 * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
172 * @link http://en.wikipedia.org/wiki/Byte
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.
180 function size_format( $bytes, $decimals = 0 ) {
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)
189 foreach ( $quant as $unit => $mag )
190 if ( doubleval($bytes) >= $mag )
191 return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
197 * Get the week start and end from the datetime or date string from mysql.
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'.
205 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
206 $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
207 $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
208 $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
209 $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
210 $weekday = date( 'w', $day ); // The day of the week from the timestamp
211 if ( !is_numeric($start_of_week) )
212 $start_of_week = get_option( 'start_of_week' );
214 if ( $weekday < $start_of_week )
217 $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
218 $end = $start + 604799; // $start + 7 days - 1 second
219 return compact( 'start', 'end' );
223 * Unserialize value only if it was serialized.
227 * @param string $original Maybe unserialized original, if is needed.
228 * @return mixed Unserialized data can be any type.
230 function maybe_unserialize( $original ) {
231 if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
232 return @unserialize( $original );
237 * Check value to find if it was serialized.
239 * If $data is not an string, then returned value will always be false.
240 * Serialized data is always a string.
244 * @param mixed $data Value to check to see if was serialized.
245 * @return bool False if not serialized and true if it was.
247 function is_serialized( $data ) {
248 // if it isn't a string, it isn't serialized
249 if ( ! is_string( $data ) )
251 $data = trim( $data );
254 $length = strlen( $data );
257 if ( ':' !== $data[1] )
259 $lastc = $data[$length-1];
260 if ( ';' !== $lastc && '}' !== $lastc )
265 if ( '"' !== $data[$length-2] )
269 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
273 return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
279 * Check whether serialized data is of string type.
283 * @param mixed $data Serialized data
284 * @return bool False if not a serialized string, true if it is.
286 function is_serialized_string( $data ) {
287 // if it isn't a string, it isn't a serialized string
288 if ( !is_string( $data ) )
290 $data = trim( $data );
291 $length = strlen( $data );
294 elseif ( ':' !== $data[1] )
296 elseif ( ';' !== $data[$length-1] )
298 elseif ( $data[0] !== 's' )
300 elseif ( '"' !== $data[$length-2] )
307 * Serialize data, if needed.
311 * @param mixed $data Data that might be serialized.
312 * @return mixed A scalar data
314 function maybe_serialize( $data ) {
315 if ( is_array( $data ) || is_object( $data ) )
316 return serialize( $data );
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 );
327 * Retrieve post title from XMLRPC XML.
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.
336 * @global string $post_default_title Default XMLRPC post title.
338 * @param string $content XMLRPC XML Request content
339 * @return string Post title
341 function xmlrpc_getposttitle( $content ) {
342 global $post_default_title;
343 if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
344 $post_title = $matchtitle[1];
346 $post_title = $post_default_title;
352 * Retrieve the post category or categories from XMLRPC XML.
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.
362 * @global string $post_default_category Default XMLRPC post category.
364 * @param string $content XMLRPC XML Request content
365 * @return string|array List of categories or category name.
367 function xmlrpc_getpostcategory( $content ) {
368 global $post_default_category;
369 if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
370 $post_category = trim( $matchcat[1], ',' );
371 $post_category = explode( ',', $post_category );
373 $post_category = $post_default_category;
375 return $post_category;
379 * XMLRPC XML content without title and category elements.
385 * @param string $content XMLRPC XML Request content
386 * @return string XMLRPC XML Request content without title and category elements.
388 function xmlrpc_removepostdata( $content ) {
389 $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
390 $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
391 $content = trim( $content );
396 * Check content for video and audio links to add as enclosures.
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.
407 * @param string $content Post Content
408 * @param int $post_ID Post ID
410 function do_enclose( $content, $post_ID ) {
413 //TODO: Tidy this ghetto code up and make the debug code optional
414 include_once( ABSPATH . WPINC . '/class-IXR.php' );
416 $post_links = array();
418 $pung = get_enclosed( $post_ID );
421 $gunk = '/#~:.?+=&%@!\-';
423 $any = $ltrs . $gunk . $punc;
425 preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
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 );
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 )
440 if ( isset( $test['query'] ) )
441 $post_links[] = $link_test;
442 elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
443 $post_links[] = $link_test;
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 ) . '%' ) ) ) {
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' );
455 // Check to see if we can figure out the mime type from
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 ( get_allowed_mime_types( ) as $exts => $mime ) {
462 if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
470 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
471 add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
479 * Perform a HTTP HEAD or GET request.
481 * If $file_path is a writable filename, this will do a GET request and write
482 * the file to that path.
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.
491 function wp_get_http( $url, $file_path = false, $red = 1 ) {
492 @set_time_limit( 60 );
498 $options['redirection'] = 5;
500 if ( false == $file_path )
501 $options['method'] = 'HEAD';
503 $options['method'] = 'GET';
505 $response = wp_remote_request($url, $options);
507 if ( is_wp_error( $response ) )
510 $headers = wp_remote_retrieve_headers( $response );
511 $headers['response'] = wp_remote_retrieve_response_code( $response );
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 );
518 if ( false == $file_path )
521 // GET request - write it to the supplied filename
522 $out_fp = fopen($file_path, 'w');
526 fwrite( $out_fp, wp_remote_retrieve_body( $response ) );
534 * Retrieve HTTP Headers from URL.
539 * @param bool $deprecated Not Used.
540 * @return bool|string False on failure, headers on success.
542 function wp_get_http_headers( $url, $deprecated = false ) {
543 if ( !empty( $deprecated ) )
544 _deprecated_argument( __FUNCTION__, '2.7' );
546 $response = wp_remote_head( $url );
548 if ( is_wp_error( $response ) )
551 return wp_remote_retrieve_headers( $response );
555 * Whether today is a new day.
559 * @uses $previousday Previous day
561 * @return int 1 when new day, 0 if not a new day.
563 function is_new_day() {
564 global $currentday, $previousday;
565 if ( $currentday != $previousday )
572 * Build URL query based on an associative and, or indexed array.
574 * This is a convenient function for easily building url queries. It sets the
575 * separator to '&' and uses _http_build_query() function.
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.
583 * @param array $data URL-encode key/value pairs.
584 * @return string URL encoded string
586 function build_query( $data ) {
587 return _http_build_query( $data, null, '&', '', false );
590 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
591 function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
594 foreach ( (array) $data as $k => $v ) {
597 if ( is_int($k) && $prefix != null )
600 $k = $key . '%5B' . $k . '%5D';
603 elseif ( $v === FALSE )
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));
611 array_push($ret, $k.'='.$v);
615 $sep = ini_get('arg_separator.output');
617 return implode($sep, $ret);
621 * Retrieve a modified URL query string.
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.
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().
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.
638 function add_query_arg() {
640 if ( is_array( func_get_arg(0) ) ) {
641 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
642 $uri = $_SERVER['REQUEST_URI'];
644 $uri = @func_get_arg( 1 );
646 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
647 $uri = $_SERVER['REQUEST_URI'];
649 $uri = @func_get_arg( 2 );
652 if ( $frag = strstr( $uri, '#' ) )
653 $uri = substr( $uri, 0, -strlen( $frag ) );
657 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
658 $protocol = $matches[0];
659 $uri = substr( $uri, strlen( $protocol ) );
664 if ( strpos( $uri, '?' ) !== false ) {
665 $parts = explode( '?', $uri, 2 );
666 if ( 1 == count( $parts ) ) {
670 $base = $parts[0] . '?';
673 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
681 wp_parse_str( $query, $qs );
682 $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
683 if ( is_array( func_get_arg( 0 ) ) ) {
684 $kayvees = func_get_arg( 0 );
685 $qs = array_merge( $qs, $kayvees );
687 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
690 foreach ( (array) $qs as $k => $v ) {
695 $ret = build_query( $qs );
696 $ret = trim( $ret, '?' );
697 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
698 $ret = $protocol . $base . $ret . $frag;
699 $ret = rtrim( $ret, '?' );
704 * Removes an item or list from the query string.
708 * @param string|array $key Query key or keys to remove.
709 * @param bool $query When false uses the $_SERVER value.
710 * @return string New URL query string.
712 function remove_query_arg( $key, $query=false ) {
713 if ( is_array( $key ) ) { // removing multiple keys
714 foreach ( $key as $k )
715 $query = add_query_arg( $k, false, $query );
718 return add_query_arg( $key, false, $query );
722 * Walks the array while sanitizing the contents.
726 * @param array $array Array to used to walk while sanitizing contents.
727 * @return array Sanitized $array.
729 function add_magic_quotes( $array ) {
730 foreach ( (array) $array as $k => $v ) {
731 if ( is_array( $v ) ) {
732 $array[$k] = add_magic_quotes( $v );
734 $array[$k] = addslashes( $v );
741 * HTTP request for URI to retrieve content.
744 * @uses wp_remote_get()
746 * @param string $uri URI/URL of web page to retrieve.
747 * @return bool|string HTTP content. False on failure.
749 function wp_remote_fopen( $uri ) {
750 $parsed_url = @parse_url( $uri );
752 if ( !$parsed_url || !is_array( $parsed_url ) )
756 $options['timeout'] = 10;
758 $response = wp_remote_get( $uri, $options );
760 if ( is_wp_error( $response ) )
763 return wp_remote_retrieve_body( $response );
767 * Set up the WordPress query.
771 * @param string $query_vars Default WP_Query arguments.
773 function wp( $query_vars = '' ) {
774 global $wp, $wp_query, $wp_the_query;
775 $wp->main( $query_vars );
777 if ( !isset($wp_the_query) )
778 $wp_the_query = $wp_query;
782 * Retrieve the description for the HTTP status.
786 * @param int $code HTTP status code.
787 * @return string Empty string if not found, or description if found.
789 function get_status_header_desc( $code ) {
790 global $wp_header_to_desc;
792 $code = absint( $code );
794 if ( !isset( $wp_header_to_desc ) ) {
795 $wp_header_to_desc = array(
797 101 => 'Switching Protocols',
803 203 => 'Non-Authoritative Information',
805 205 => 'Reset Content',
806 206 => 'Partial Content',
807 207 => 'Multi-Status',
810 300 => 'Multiple Choices',
811 301 => 'Moved Permanently',
814 304 => 'Not Modified',
817 307 => 'Temporary Redirect',
819 400 => 'Bad Request',
820 401 => 'Unauthorized',
821 402 => 'Payment Required',
824 405 => 'Method Not Allowed',
825 406 => 'Not Acceptable',
826 407 => 'Proxy Authentication Required',
827 408 => 'Request Timeout',
830 411 => 'Length Required',
831 412 => 'Precondition Failed',
832 413 => 'Request Entity Too Large',
833 414 => 'Request-URI Too Long',
834 415 => 'Unsupported Media Type',
835 416 => 'Requested Range Not Satisfiable',
836 417 => 'Expectation Failed',
837 422 => 'Unprocessable Entity',
839 424 => 'Failed Dependency',
840 426 => 'Upgrade Required',
842 500 => 'Internal Server Error',
843 501 => 'Not Implemented',
844 502 => 'Bad Gateway',
845 503 => 'Service Unavailable',
846 504 => 'Gateway Timeout',
847 505 => 'HTTP Version Not Supported',
848 506 => 'Variant Also Negotiates',
849 507 => 'Insufficient Storage',
850 510 => 'Not Extended'
854 if ( isset( $wp_header_to_desc[$code] ) )
855 return $wp_header_to_desc[$code];
861 * Set HTTP status header.
864 * @uses apply_filters() Calls 'status_header' on status header string, HTTP
865 * HTTP code, HTTP code description, and protocol string as separate
868 * @param int $header HTTP status code
871 function status_header( $header ) {
872 $text = get_status_header_desc( $header );
874 if ( empty( $text ) )
877 $protocol = $_SERVER["SERVER_PROTOCOL"];
878 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
879 $protocol = 'HTTP/1.0';
880 $status_header = "$protocol $header $text";
881 if ( function_exists( 'apply_filters' ) )
882 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
884 return @header( $status_header, true, $header );
888 * Gets the header information to prevent caching.
890 * The several different headers cover the different ways cache prevention is handled
891 * by different browsers
895 * @uses apply_filters()
896 * @return array The associative array of header names and field values.
898 function wp_get_nocache_headers() {
900 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
901 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
902 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
903 'Pragma' => 'no-cache',
906 if ( function_exists('apply_filters') ) {
907 $headers = (array) apply_filters('nocache_headers', $headers);
913 * Sets the headers to prevent caching for the different browsers.
915 * Different browsers support different nocache headers, so several headers must
916 * be sent so that all of them get the point that no caching should occur.
919 * @uses wp_get_nocache_headers()
921 function nocache_headers() {
922 $headers = wp_get_nocache_headers();
923 foreach( $headers as $name => $field_value )
924 @header("{$name}: {$field_value}");
928 * Set the headers for caching for 10 days with JavaScript content type.
932 function cache_javascript_headers() {
933 $expiresOffset = 864000; // 10 days
934 header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
935 header( "Vary: Accept-Encoding" ); // Handle proxies
936 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
940 * Retrieve the number of database queries during the WordPress execution.
944 * @return int Number of database queries
946 function get_num_queries() {
948 return $wpdb->num_queries;
952 * Whether input is yes or no. Must be 'y' to be true.
956 * @param string $yn Character string containing either 'y' or 'n'
957 * @return bool True if yes, false on anything else
959 function bool_from_yn( $yn ) {
960 return ( strtolower( $yn ) == 'y' );
964 * Loads the feed template from the use of an action hook.
966 * If the feed action does not have a hook, then the function will die with a
967 * message telling the visitor that the feed is not valid.
969 * It is better to only have one hook for each feed.
972 * @uses $wp_query Used to tell if the use a comment feed.
973 * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
978 $feed = get_query_var( 'feed' );
980 // Remove the pad, if present.
981 $feed = preg_replace( '/^_+/', '', $feed );
983 if ( $feed == '' || $feed == 'feed' )
984 $feed = get_default_feed();
986 $hook = 'do_feed_' . $feed;
987 if ( !has_action($hook) ) {
988 $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
989 wp_die( $message, '', array( 'response' => 404 ) );
992 do_action( $hook, $wp_query->is_comment_feed );
996 * Load the RDF RSS 0.91 Feed template.
1000 function do_feed_rdf() {
1001 load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1005 * Load the RSS 1.0 Feed Template.
1009 function do_feed_rss() {
1010 load_template( ABSPATH . WPINC . '/feed-rss.php' );
1014 * Load either the RSS2 comment feed or the RSS2 posts feed.
1018 * @param bool $for_comments True for the comment feed, false for normal feed.
1020 function do_feed_rss2( $for_comments ) {
1021 if ( $for_comments )
1022 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1024 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1028 * Load either Atom comment feed or Atom posts feed.
1032 * @param bool $for_comments True for the comment feed, false for normal feed.
1034 function do_feed_atom( $for_comments ) {
1036 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1038 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1042 * Display the robots.txt file content.
1044 * The echo content should be with usage of the permalinks or for creating the
1048 * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
1050 function do_robots() {
1051 header( 'Content-Type: text/plain; charset=utf-8' );
1053 do_action( 'do_robotstxt' );
1055 $output = "User-agent: *\n";
1056 $public = get_option( 'blog_public' );
1057 if ( '0' == $public ) {
1058 $output .= "Disallow: /\n";
1060 $site_url = parse_url( site_url() );
1061 $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1062 $output .= "Disallow: $path/wp-admin/\n";
1063 $output .= "Disallow: $path/wp-includes/\n";
1066 echo apply_filters('robots_txt', $output, $public);
1070 * Test whether blog is already installed.
1072 * The cache will be checked first. If you have a cache plugin, which saves the
1073 * cache values, then this will work. If you use the default WordPress cache,
1074 * and the database goes away, then you might have problems.
1076 * Checks for the option siteurl for whether WordPress is installed.
1081 * @return bool Whether blog is already installed.
1083 function is_blog_installed() {
1086 // Check cache first. If options table goes away and we have true cached, oh well.
1087 if ( wp_cache_get( 'is_blog_installed' ) )
1090 $suppress = $wpdb->suppress_errors();
1091 if ( ! defined( 'WP_INSTALLING' ) ) {
1092 $alloptions = wp_load_alloptions();
1094 // If siteurl is not set to autoload, check it specifically
1095 if ( !isset( $alloptions['siteurl'] ) )
1096 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1098 $installed = $alloptions['siteurl'];
1099 $wpdb->suppress_errors( $suppress );
1101 $installed = !empty( $installed );
1102 wp_cache_set( 'is_blog_installed', $installed );
1107 // If visiting repair.php, return true and let it take over.
1108 if ( defined( 'WP_REPAIRING' ) )
1111 $suppress = $wpdb->suppress_errors();
1113 // Loop over the WP tables. If none exist, then scratch install is allowed.
1114 // If one or more exist, suggest table repair since we got here because the options
1115 // table could not be accessed.
1116 $wp_tables = $wpdb->tables();
1117 foreach ( $wp_tables as $table ) {
1118 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1119 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1121 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1124 if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
1127 // One or more tables exist. We are insane.
1129 wp_load_translations_early();
1131 // Die with a DB error.
1132 $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' );
1136 $wpdb->suppress_errors( $suppress );
1138 wp_cache_set( 'is_blog_installed', false );
1144 * Retrieve URL with nonce added to URL query.
1146 * @package WordPress
1147 * @subpackage Security
1150 * @param string $actionurl URL to add nonce action
1151 * @param string $action Optional. Nonce action name
1152 * @return string URL with nonce action added.
1154 function wp_nonce_url( $actionurl, $action = -1 ) {
1155 $actionurl = str_replace( '&', '&', $actionurl );
1156 return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1160 * Retrieve or display nonce hidden field for forms.
1162 * The nonce field is used to validate that the contents of the form came from
1163 * the location on the current site and not somewhere else. The nonce does not
1164 * offer absolute protection, but should protect against most cases. It is very
1165 * important to use nonce field in forms.
1167 * The $action and $name are optional, but if you want to have better security,
1168 * it is strongly suggested to set those two parameters. It is easier to just
1169 * call the function without any parameters, because validation of the nonce
1170 * doesn't require any parameters, but since crackers know what the default is
1171 * it won't be difficult for them to find a way around your nonce and cause
1174 * The input name will be whatever $name value you gave. The input value will be
1175 * the nonce creation value.
1177 * @package WordPress
1178 * @subpackage Security
1181 * @param string $action Optional. Action name.
1182 * @param string $name Optional. Nonce name.
1183 * @param bool $referer Optional, default true. Whether to set the referer field for validation.
1184 * @param bool $echo Optional, default true. Whether to display or return hidden form field.
1185 * @return string Nonce field.
1187 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1188 $name = esc_attr( $name );
1189 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1192 $nonce_field .= wp_referer_field( false );
1197 return $nonce_field;
1201 * Retrieve or display referer hidden field for forms.
1203 * The referer link is the current Request URI from the server super global. The
1204 * input name is '_wp_http_referer', in case you wanted to check manually.
1206 * @package WordPress
1207 * @subpackage Security
1210 * @param bool $echo Whether to echo or return the referer field.
1211 * @return string Referer field.
1213 function wp_referer_field( $echo = true ) {
1214 $ref = esc_attr( $_SERVER['REQUEST_URI'] );
1215 $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
1218 echo $referer_field;
1219 return $referer_field;
1223 * Retrieve or display original referer hidden field for forms.
1225 * The input name is '_wp_original_http_referer' and will be either the same
1226 * value of {@link wp_referer_field()}, if that was posted already or it will
1227 * be the current page, if it doesn't exist.
1229 * @package WordPress
1230 * @subpackage Security
1233 * @param bool $echo Whether to echo the original http referer
1234 * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
1235 * @return string Original referer field.
1237 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1238 $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
1239 $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
1240 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
1242 echo $orig_referer_field;
1243 return $orig_referer_field;
1247 * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
1248 * as the current request URL, will return false.
1250 * @package WordPress
1251 * @subpackage Security
1254 * @return string|bool False on failure. Referer URL on success.
1256 function wp_get_referer() {
1258 if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
1259 $ref = $_REQUEST['_wp_http_referer'];
1260 else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
1261 $ref = $_SERVER['HTTP_REFERER'];
1263 if ( $ref && $ref !== $_SERVER['REQUEST_URI'] )
1269 * Retrieve original referer that was posted, if it exists.
1271 * @package WordPress
1272 * @subpackage Security
1275 * @return string|bool False if no original referer or original referer if set.
1277 function wp_get_original_referer() {
1278 if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
1279 return $_REQUEST['_wp_original_http_referer'];
1284 * Recursive directory creation based on full path.
1286 * Will attempt to set permissions on folders.
1290 * @param string $target Full path to attempt to create.
1291 * @return bool Whether the path was created. True if path already exists.
1293 function wp_mkdir_p( $target ) {
1294 // from php.net/mkdir user contributed notes
1295 $target = str_replace( '//', '/', $target );
1297 // safe mode fails with a trailing slash under certain PHP versions.
1298 $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1299 if ( empty($target) )
1302 if ( file_exists( $target ) )
1303 return @is_dir( $target );
1305 // Attempting to create the directory may clutter up our display.
1306 if ( @mkdir( $target ) ) {
1307 $stat = @stat( dirname( $target ) );
1308 $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
1309 @chmod( $target, $dir_perms );
1311 } elseif ( is_dir( dirname( $target ) ) ) {
1315 // If the above failed, attempt to create the parent node, then try again.
1316 if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
1317 return wp_mkdir_p( $target );
1323 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
1327 * @param string $path File path
1328 * @return bool True if path is absolute, false is not absolute.
1330 function path_is_absolute( $path ) {
1331 // this is definitive if true but fails if $path does not exist or contains a symbolic link
1332 if ( realpath($path) == $path )
1335 if ( strlen($path) == 0 || $path[0] == '.' )
1338 // windows allows absolute paths like this
1339 if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1342 // a path starting with / or \ is absolute; anything else is relative
1343 return ( $path[0] == '/' || $path[0] == '\\' );
1347 * Join two filesystem paths together (e.g. 'give me $path relative to $base').
1349 * If the $path is absolute, then it the full path is returned.
1353 * @param string $base
1354 * @param string $path
1355 * @return string The path with the base or absolute path.
1357 function path_join( $base, $path ) {
1358 if ( path_is_absolute($path) )
1361 return rtrim($base, '/') . '/' . ltrim($path, '/');
1365 * Determines a writable directory for temporary files.
1366 * Function's preference is to WP_CONTENT_DIR followed by the return value of <code>sys_get_temp_dir()</code>, before finally defaulting to /tmp/
1368 * In the event that this function does not find a writable location, It may be overridden by the <code>WP_TEMP_DIR</code> constant in your <code>wp-config.php</code> file.
1372 * @return string Writable temporary directory
1374 function get_temp_dir() {
1376 if ( defined('WP_TEMP_DIR') )
1377 return trailingslashit(WP_TEMP_DIR);
1380 return trailingslashit($temp);
1382 $temp = WP_CONTENT_DIR . '/';
1383 if ( is_dir($temp) && @is_writable($temp) )
1386 if ( function_exists('sys_get_temp_dir') ) {
1387 $temp = sys_get_temp_dir();
1388 if ( @is_writable($temp) )
1389 return trailingslashit($temp);
1392 $temp = ini_get('upload_tmp_dir');
1393 if ( is_dir($temp) && @is_writable($temp) )
1394 return trailingslashit($temp);
1401 * Get an array containing the current upload directory's path and url.
1403 * Checks the 'upload_path' option, which should be from the web root folder,
1404 * and if it isn't empty it will be used. If it is empty, then the path will be
1405 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
1406 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
1408 * The upload URL path is set either by the 'upload_url_path' option or by using
1409 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
1411 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
1412 * the administration settings panel), then the time will be used. The format
1413 * will be year first and then month.
1415 * If the path couldn't be created, then an error will be returned with the key
1416 * 'error' containing the error message. The error suggests that the parent
1417 * directory is not writable by the server.
1419 * On success, the returned array will have many indices:
1420 * 'path' - base directory and sub directory or full path to upload directory.
1421 * 'url' - base url and sub directory or absolute URL to upload directory.
1422 * 'subdir' - sub directory if uploads use year/month folders option is on.
1423 * 'basedir' - path without subdir.
1424 * 'baseurl' - URL path without subdir.
1425 * 'error' - set to false.
1428 * @uses apply_filters() Calls 'upload_dir' on returned array.
1430 * @param string $time Optional. Time formatted in 'yyyy/mm'.
1431 * @return array See above for description.
1433 function wp_upload_dir( $time = null ) {
1435 $siteurl = get_option( 'siteurl' );
1436 $upload_path = get_option( 'upload_path' );
1437 $upload_path = trim($upload_path);
1438 $main_override = is_multisite() && defined( 'MULTISITE' ) && is_main_site();
1439 if ( empty($upload_path) ) {
1440 $dir = WP_CONTENT_DIR . '/uploads';
1442 $dir = $upload_path;
1443 if ( 'wp-content/uploads' == $upload_path ) {
1444 $dir = WP_CONTENT_DIR . '/uploads';
1445 } elseif ( 0 !== strpos($dir, ABSPATH) ) {
1446 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
1447 $dir = path_join( ABSPATH, $dir );
1451 if ( !$url = get_option( 'upload_url_path' ) ) {
1452 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
1453 $url = WP_CONTENT_URL . '/uploads';
1455 $url = trailingslashit( $siteurl ) . $upload_path;
1458 if ( defined('UPLOADS') && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
1459 $dir = ABSPATH . UPLOADS;
1460 $url = trailingslashit( $siteurl ) . UPLOADS;
1463 if ( is_multisite() && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
1464 if ( defined( 'BLOGUPLOADDIR' ) )
1465 $dir = untrailingslashit(BLOGUPLOADDIR);
1466 $url = str_replace( UPLOADS, 'files', $url );
1473 if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
1474 // Generate the yearly and monthly dirs
1476 $time = current_time( 'mysql' );
1477 $y = substr( $time, 0, 4 );
1478 $m = substr( $time, 5, 2 );
1485 $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
1487 // Make sure we have an uploads dir
1488 if ( ! wp_mkdir_p( $uploads['path'] ) ) {
1489 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
1490 return array( 'error' => $message );
1497 * Get a filename that is sanitized and unique for the given directory.
1499 * If the filename is not unique, then a number will be added to the filename
1500 * before the extension, and will continue adding numbers until the filename is
1503 * The callback is passed three parameters, the first one is the directory, the
1504 * second is the filename, and the third is the extension.
1508 * @param string $dir
1509 * @param string $filename
1510 * @param mixed $unique_filename_callback Callback.
1511 * @return string New filename, if given wasn't unique.
1513 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
1514 // sanitize the file name before we begin processing
1515 $filename = sanitize_file_name($filename);
1517 // separate the filename into a name and extension
1518 $info = pathinfo($filename);
1519 $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
1520 $name = basename($filename, $ext);
1522 // edge case: if file is named '.ext', treat as an empty name
1523 if ( $name === $ext )
1526 // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
1527 if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
1528 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
1532 // change '.ext' to lower case
1533 if ( $ext && strtolower($ext) != $ext ) {
1534 $ext2 = strtolower($ext);
1535 $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
1537 // check for both lower and upper case extension or image sub-sizes may be overwritten
1538 while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
1539 $new_number = $number + 1;
1540 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
1541 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
1542 $number = $new_number;
1547 while ( file_exists( $dir . "/$filename" ) ) {
1548 if ( '' == "$number$ext" )
1549 $filename = $filename . ++$number . $ext;
1551 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
1559 * Create a file in the upload folder with given content.
1561 * If there is an error, then the key 'error' will exist with the error message.
1562 * If success, then the key 'file' will have the unique file path, the 'url' key
1563 * will have the link to the new file. and the 'error' key will be set to false.
1565 * This function will not move an uploaded file to the upload folder. It will
1566 * create a new file with the content in $bits parameter. If you move the upload
1567 * file, read the content of the uploaded file, and then you can give the
1568 * filename and content to this function, which will add it to the upload
1571 * The permissions will be set on the new file automatically by this function.
1575 * @param string $name
1576 * @param null $deprecated Never used. Set to null.
1577 * @param mixed $bits File content
1578 * @param string $time Optional. Time formatted in 'yyyy/mm'.
1581 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
1582 if ( !empty( $deprecated ) )
1583 _deprecated_argument( __FUNCTION__, '2.0' );
1585 if ( empty( $name ) )
1586 return array( 'error' => __( 'Empty filename' ) );
1588 $wp_filetype = wp_check_filetype( $name );
1589 if ( !$wp_filetype['ext'] )
1590 return array( 'error' => __( 'Invalid file type' ) );
1592 $upload = wp_upload_dir( $time );
1594 if ( $upload['error'] !== false )
1597 $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
1598 if ( !is_array( $upload_bits_error ) ) {
1599 $upload[ 'error' ] = $upload_bits_error;
1603 $filename = wp_unique_filename( $upload['path'], $name );
1605 $new_file = $upload['path'] . "/$filename";
1606 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
1607 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
1608 return array( 'error' => $message );
1611 $ifp = @ fopen( $new_file, 'wb' );
1613 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
1615 @fwrite( $ifp, $bits );
1619 // Set correct file permissions
1620 $stat = @ stat( dirname( $new_file ) );
1621 $perms = $stat['mode'] & 0007777;
1622 $perms = $perms & 0000666;
1623 @ chmod( $new_file, $perms );
1627 $url = $upload['url'] . "/$filename";
1629 return array( 'file' => $new_file, 'url' => $url, 'error' => false );
1633 * Retrieve the file type based on the extension name.
1635 * @package WordPress
1637 * @uses apply_filters() Calls 'ext2type' hook on default supported types.
1639 * @param string $ext The extension to search.
1640 * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
1642 function wp_ext2type( $ext ) {
1643 $ext2type = apply_filters( 'ext2type', array(
1644 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
1645 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
1646 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
1647 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsb', 'xlsm' ),
1648 'interactive' => array( 'key', 'ppt', 'pptx', 'pptm', 'odp', 'swf' ),
1649 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
1650 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
1651 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
1653 foreach ( $ext2type as $type => $exts )
1654 if ( in_array( $ext, $exts ) )
1659 * Retrieve the file type from the file name.
1661 * You can optionally define the mime array, if needed.
1665 * @param string $filename File name or path.
1666 * @param array $mimes Optional. Key is the file extension with value as the mime type.
1667 * @return array Values with extension first and mime type.
1669 function wp_check_filetype( $filename, $mimes = null ) {
1670 if ( empty($mimes) )
1671 $mimes = get_allowed_mime_types();
1675 foreach ( $mimes as $ext_preg => $mime_match ) {
1676 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1677 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
1678 $type = $mime_match;
1679 $ext = $ext_matches[1];
1684 return compact( 'ext', 'type' );
1688 * Attempt to determine the real file type of a file.
1689 * If unable to, the file name extension will be used to determine type.
1691 * If it's determined that the extension does not match the file's real type,
1692 * then the "proper_filename" value will be set with a proper filename and extension.
1694 * Currently this function only supports validating images known to getimagesize().
1698 * @param string $file Full path to the image.
1699 * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
1700 * @param array $mimes Optional. Key is the file extension with value as the mime type.
1701 * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
1703 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
1705 $proper_filename = false;
1707 // Do basic extension validation and MIME mapping
1708 $wp_filetype = wp_check_filetype( $filename, $mimes );
1709 extract( $wp_filetype );
1711 // We can't do any further validation without a file to work with
1712 if ( ! file_exists( $file ) )
1713 return compact( 'ext', 'type', 'proper_filename' );
1715 // We're able to validate images using GD
1716 if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
1718 // Attempt to figure out what type of image it actually is
1719 $imgstats = @getimagesize( $file );
1721 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
1722 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
1723 // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
1724 // You shouldn't need to use this filter, but it's here just in case
1725 $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
1726 'image/jpeg' => 'jpg',
1727 'image/png' => 'png',
1728 'image/gif' => 'gif',
1729 'image/bmp' => 'bmp',
1730 'image/tiff' => 'tif',
1733 // Replace whatever is after the last period in the filename with the correct extension
1734 if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
1735 $filename_parts = explode( '.', $filename );
1736 array_pop( $filename_parts );
1737 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
1738 $new_filename = implode( '.', $filename_parts );
1740 if ( $new_filename != $filename )
1741 $proper_filename = $new_filename; // Mark that it changed
1743 // Redefine the extension / MIME
1744 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
1745 extract( $wp_filetype );
1750 // Let plugins try and validate other types of files
1751 // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
1752 return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
1756 * Retrieve list of allowed mime types and file extensions.
1760 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
1762 function get_allowed_mime_types() {
1763 static $mimes = false;
1766 // Accepted MIME types are set here as PCRE unless provided.
1767 $mimes = apply_filters( 'upload_mimes', array(
1768 'jpg|jpeg|jpe' => 'image/jpeg',
1769 'gif' => 'image/gif',
1770 'png' => 'image/png',
1771 'bmp' => 'image/bmp',
1772 'tif|tiff' => 'image/tiff',
1773 'ico' => 'image/x-icon',
1774 'asf|asx|wax|wmv|wmx' => 'video/asf',
1775 'avi' => 'video/avi',
1776 'divx' => 'video/divx',
1777 'flv' => 'video/x-flv',
1778 'mov|qt' => 'video/quicktime',
1779 'mpeg|mpg|mpe' => 'video/mpeg',
1780 'txt|asc|c|cc|h' => 'text/plain',
1781 'csv' => 'text/csv',
1782 'tsv' => 'text/tab-separated-values',
1783 'ics' => 'text/calendar',
1784 'rtx' => 'text/richtext',
1785 'css' => 'text/css',
1786 'htm|html' => 'text/html',
1787 'mp3|m4a|m4b' => 'audio/mpeg',
1788 'mp4|m4v' => 'video/mp4',
1789 'ra|ram' => 'audio/x-realaudio',
1790 'wav' => 'audio/wav',
1791 'ogg|oga' => 'audio/ogg',
1792 'ogv' => 'video/ogg',
1793 'mid|midi' => 'audio/midi',
1794 'wma' => 'audio/wma',
1795 'mka' => 'audio/x-matroska',
1796 'mkv' => 'video/x-matroska',
1797 'rtf' => 'application/rtf',
1798 'js' => 'application/javascript',
1799 'pdf' => 'application/pdf',
1800 'doc|docx' => 'application/msword',
1801 'pot|pps|ppt|pptx|ppam|pptm|sldm|ppsm|potm' => 'application/vnd.ms-powerpoint',
1802 'wri' => 'application/vnd.ms-write',
1803 'xla|xls|xlsx|xlt|xlw|xlam|xlsb|xlsm|xltm' => 'application/vnd.ms-excel',
1804 'mdb' => 'application/vnd.ms-access',
1805 'mpp' => 'application/vnd.ms-project',
1806 'docm|dotm' => 'application/vnd.ms-word',
1807 'pptx|sldx|ppsx|potx' => 'application/vnd.openxmlformats-officedocument.presentationml',
1808 'xlsx|xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml',
1809 'docx|dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml',
1810 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
1811 'swf' => 'application/x-shockwave-flash',
1812 'class' => 'application/java',
1813 'tar' => 'application/x-tar',
1814 'zip' => 'application/zip',
1815 'gz|gzip' => 'application/x-gzip',
1816 'rar' => 'application/rar',
1817 '7z' => 'application/x-7z-compressed',
1818 'exe' => 'application/x-msdownload',
1819 // openoffice formats
1820 'odt' => 'application/vnd.oasis.opendocument.text',
1821 'odp' => 'application/vnd.oasis.opendocument.presentation',
1822 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1823 'odg' => 'application/vnd.oasis.opendocument.graphics',
1824 'odc' => 'application/vnd.oasis.opendocument.chart',
1825 'odb' => 'application/vnd.oasis.opendocument.database',
1826 'odf' => 'application/vnd.oasis.opendocument.formula',
1827 // wordperfect formats
1828 'wp|wpd' => 'application/wordperfect',
1836 * Retrieve nonce action "Are you sure" message.
1838 * Deprecated in 3.4.1 and 3.5.0. Backported to 3.3.3.
1842 * @deprecated Use wp_nonce_ays()
1843 * @see wp_nonce_ays()
1845 * @param string $action Nonce action.
1846 * @return string Are you sure message.
1848 function wp_explain_nonce( $action ) {
1849 _deprecated_function( __FUNCTION__, '3.4.1', 'wp_nonce_ays()' );
1850 return __( 'Are you sure you want to do this?' );
1854 * Display "Are You Sure" message to confirm the action being taken.
1856 * If the action has the nonce explain message, then it will be displayed along
1857 * with the "Are you sure?" message.
1859 * @package WordPress
1860 * @subpackage Security
1863 * @param string $action The nonce action.
1865 function wp_nonce_ays( $action ) {
1866 $title = __( 'WordPress Failure Notice' );
1867 if ( 'log-out' == $action ) {
1868 $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
1869 $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
1871 $html = __( 'Are you sure you want to do this?' );
1872 if ( wp_get_referer() )
1873 $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
1876 wp_die( $html, $title, array('response' => 403) );
1880 * Kill WordPress execution and display HTML message with error message.
1882 * This function complements the die() PHP function. The difference is that
1883 * HTML will be displayed to the user. It is recommended to use this function
1884 * only, when the execution should not continue any further. It is not
1885 * recommended to call this function very often and try to handle as many errors
1886 * as possible silently.
1890 * @param string $message Error message.
1891 * @param string $title Error title.
1892 * @param string|array $args Optional arguments to control behavior.
1894 function wp_die( $message = '', $title = '', $args = array() ) {
1895 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
1896 $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
1897 elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
1898 $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
1899 elseif ( defined( 'APP_REQUEST' ) && APP_REQUEST )
1900 $function = apply_filters( 'wp_die_app_handler', '_scalar_wp_die_handler' );
1902 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
1904 call_user_func( $function, $message, $title, $args );
1908 * Kill WordPress execution and display HTML message with error message.
1910 * This is the default handler for wp_die if you want a custom one for your
1911 * site then you can overload using the wp_die_handler filter in wp_die
1916 * @param string $message Error message.
1917 * @param string $title Error title.
1918 * @param string|array $args Optional arguments to control behavior.
1920 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
1921 $defaults = array( 'response' => 500 );
1922 $r = wp_parse_args($args, $defaults);
1924 $have_gettext = function_exists('__');
1926 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
1927 if ( empty( $title ) ) {
1928 $error_data = $message->get_error_data();
1929 if ( is_array( $error_data ) && isset( $error_data['title'] ) )
1930 $title = $error_data['title'];
1932 $errors = $message->get_error_messages();
1933 switch ( count( $errors ) ) :
1938 $message = "<p>{$errors[0]}</p>";
1941 $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
1944 } elseif ( is_string( $message ) ) {
1945 $message = "<p>$message</p>";
1948 if ( isset( $r['back_link'] ) && $r['back_link'] ) {
1949 $back_text = $have_gettext? __('« Back') : '« Back';
1950 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
1953 if ( ! did_action( 'admin_head' ) ) :
1954 if ( !headers_sent() ) {
1955 status_header( $r['response'] );
1957 header( 'Content-Type: text/html; charset=utf-8' );
1960 if ( empty($title) )
1961 $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error';
1963 $text_direction = 'ltr';
1964 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
1965 $text_direction = 'rtl';
1966 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
1967 $text_direction = 'rtl';
1970 <!-- 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
1972 <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'"; ?>>
1974 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1975 <title><?php echo $title ?></title>
1976 <style type="text/css">
1978 background: #f9f9f9;
1983 font-family: sans-serif;
1986 -webkit-border-radius: 3px;
1988 border: 1px solid #dfdfdf;
1992 border-bottom: 1px solid #dadada;
1995 font: 24px Georgia, "Times New Roman", Times, serif;
1998 padding-bottom: 7px;
2006 margin: 25px 0 20px;
2009 font-family: Consolas, Monaco, monospace;
2012 margin-bottom: 10px;
2017 text-decoration: none;
2024 font-family: sans-serif;
2025 text-decoration: none;
2026 font-size: 14px !important;
2030 border: 1px solid #bbb;
2032 -webkit-border-radius: 15px;
2033 border-radius: 15px;
2034 -moz-box-sizing: content-box;
2035 -webkit-box-sizing: content-box;
2036 box-sizing: content-box;
2037 background-color: #f5f5f5;
2038 background-image: -ms-linear-gradient(top, #ffffff, #f2f2f2);
2039 background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2);
2040 background-image: -o-linear-gradient(top, #ffffff, #f2f2f2);
2041 background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f2f2f2));
2042 background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2);
2043 background-image: linear-gradient(top, #ffffff, #f2f2f2);
2052 background-image: -ms-linear-gradient(top, #f2f2f2, #ffffff);
2053 background-image: -moz-linear-gradient(top, #f2f2f2, #ffffff);
2054 background-image: -o-linear-gradient(top, #f2f2f2, #ffffff);
2055 background-image: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#ffffff));
2056 background-image: -webkit-linear-gradient(top, #f2f2f2, #ffffff);
2057 background-image: linear-gradient(top, #f2f2f2, #ffffff);
2060 <?php if ( 'rtl' == $text_direction ) : ?>
2061 body { font-family: Tahoma, Arial; }
2065 <body id="error-page">
2066 <?php endif; // ! did_action( 'admin_head' ) ?>
2067 <?php echo $message; ?>
2075 * Kill WordPress execution and display XML message with error message.
2077 * This is the handler for wp_die when processing XMLRPC requests.
2082 * @param string $message Error message.
2083 * @param string $title Error title.
2084 * @param string|array $args Optional arguments to control behavior.
2086 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
2087 global $wp_xmlrpc_server;
2088 $defaults = array( 'response' => 500 );
2090 $r = wp_parse_args($args, $defaults);
2092 if ( $wp_xmlrpc_server ) {
2093 $error = new IXR_Error( $r['response'] , $message);
2094 $wp_xmlrpc_server->output( $error->getXml() );
2100 * Kill WordPress ajax execution.
2102 * This is the handler for wp_die when processing Ajax requests.
2107 * @param string $message Optional. Response to print.
2109 function _ajax_wp_die_handler( $message = '' ) {
2110 if ( is_scalar( $message ) )
2111 die( (string) $message );
2116 * Kill WordPress execution.
2118 * This is the handler for wp_die when processing APP requests.
2123 * @param string $message Optional. Response to print.
2125 function _scalar_wp_die_handler( $message = '' ) {
2126 if ( is_scalar( $message ) )
2127 die( (string) $message );
2132 * Retrieve the WordPress home page URL.
2134 * If the constant named 'WP_HOME' exists, then it will be used and returned by
2135 * the function. This can be used to counter the redirection on your local
2136 * development environment.
2139 * @package WordPress
2142 * @param string $url URL for the home location
2143 * @return string Homepage location.
2145 function _config_wp_home( $url = '' ) {
2146 if ( defined( 'WP_HOME' ) )
2147 return untrailingslashit( WP_HOME );
2152 * Retrieve the WordPress site URL.
2154 * If the constant named 'WP_SITEURL' is defined, then the value in that
2155 * constant will always be returned. This can be used for debugging a site on
2156 * your localhost while not having to change the database to your URL.
2159 * @package WordPress
2162 * @param string $url URL to set the WordPress site location.
2163 * @return string The WordPress Site URL
2165 function _config_wp_siteurl( $url = '' ) {
2166 if ( defined( 'WP_SITEURL' ) )
2167 return untrailingslashit( WP_SITEURL );
2172 * Set the localized direction for MCE plugin.
2174 * Will only set the direction to 'rtl', if the WordPress locale has the text
2175 * direction set to 'rtl'.
2177 * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
2178 * keys. These keys are then returned in the $input array.
2181 * @package WordPress
2185 * @param array $input MCE plugin array.
2186 * @return array Direction set for 'rtl', if needed by locale.
2188 function _mce_set_direction( $input ) {
2190 $input['directionality'] = 'rtl';
2191 $input['plugins'] .= ',directionality';
2192 $input['theme_advanced_buttons1'] .= ',ltr';
2199 * Convert smiley code to the icon graphic file equivalent.
2201 * You can turn off smilies, by going to the write setting screen and unchecking
2202 * the box, or by setting 'use_smilies' option to false or removing the option.
2204 * Plugins may override the default smiley list by setting the $wpsmiliestrans
2205 * to an array, with the key the code the blogger types in and the value the
2208 * The $wp_smiliessearch global is for the regular expression and is set each
2209 * time the function is called.
2211 * The full list of smilies can be found in the function and won't be listed in
2212 * the description. Probably should create a Codex page for it, so that it is
2215 * @global array $wpsmiliestrans
2216 * @global array $wp_smiliessearch
2219 function smilies_init() {
2220 global $wpsmiliestrans, $wp_smiliessearch;
2222 // don't bother setting up smilies if they are disabled
2223 if ( !get_option( 'use_smilies' ) )
2226 if ( !isset( $wpsmiliestrans ) ) {
2227 $wpsmiliestrans = array(
2228 ':mrgreen:' => 'icon_mrgreen.gif',
2229 ':neutral:' => 'icon_neutral.gif',
2230 ':twisted:' => 'icon_twisted.gif',
2231 ':arrow:' => 'icon_arrow.gif',
2232 ':shock:' => 'icon_eek.gif',
2233 ':smile:' => 'icon_smile.gif',
2234 ':???:' => 'icon_confused.gif',
2235 ':cool:' => 'icon_cool.gif',
2236 ':evil:' => 'icon_evil.gif',
2237 ':grin:' => 'icon_biggrin.gif',
2238 ':idea:' => 'icon_idea.gif',
2239 ':oops:' => 'icon_redface.gif',
2240 ':razz:' => 'icon_razz.gif',
2241 ':roll:' => 'icon_rolleyes.gif',
2242 ':wink:' => 'icon_wink.gif',
2243 ':cry:' => 'icon_cry.gif',
2244 ':eek:' => 'icon_surprised.gif',
2245 ':lol:' => 'icon_lol.gif',
2246 ':mad:' => 'icon_mad.gif',
2247 ':sad:' => 'icon_sad.gif',
2248 '8-)' => 'icon_cool.gif',
2249 '8-O' => 'icon_eek.gif',
2250 ':-(' => 'icon_sad.gif',
2251 ':-)' => 'icon_smile.gif',
2252 ':-?' => 'icon_confused.gif',
2253 ':-D' => 'icon_biggrin.gif',
2254 ':-P' => 'icon_razz.gif',
2255 ':-o' => 'icon_surprised.gif',
2256 ':-x' => 'icon_mad.gif',
2257 ':-|' => 'icon_neutral.gif',
2258 ';-)' => 'icon_wink.gif',
2259 // This one transformation breaks regular text with frequency.
2260 // '8)' => 'icon_cool.gif',
2261 '8O' => 'icon_eek.gif',
2262 ':(' => 'icon_sad.gif',
2263 ':)' => 'icon_smile.gif',
2264 ':?' => 'icon_confused.gif',
2265 ':D' => 'icon_biggrin.gif',
2266 ':P' => 'icon_razz.gif',
2267 ':o' => 'icon_surprised.gif',
2268 ':x' => 'icon_mad.gif',
2269 ':|' => 'icon_neutral.gif',
2270 ';)' => 'icon_wink.gif',
2271 ':!:' => 'icon_exclaim.gif',
2272 ':?:' => 'icon_question.gif',
2276 if (count($wpsmiliestrans) == 0) {
2281 * NOTE: we sort the smilies in reverse key order. This is to make sure
2282 * we match the longest possible smilie (:???: vs :?) as the regular
2283 * expression used below is first-match
2285 krsort($wpsmiliestrans);
2287 $wp_smiliessearch = '/(?:\s|^)';
2290 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
2291 $firstchar = substr($smiley, 0, 1);
2292 $rest = substr($smiley, 1);
2295 if ($firstchar != $subchar) {
2296 if ($subchar != '') {
2297 $wp_smiliessearch .= ')|(?:\s|^)';
2299 $subchar = $firstchar;
2300 $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
2302 $wp_smiliessearch .= '|';
2304 $wp_smiliessearch .= preg_quote($rest, '/');
2307 $wp_smiliessearch .= ')(?:\s|$)/m';
2311 * Merge user defined arguments into defaults array.
2313 * This function is used throughout WordPress to allow for both string or array
2314 * to be merged into another array.
2318 * @param string|array $args Value to merge with $defaults
2319 * @param array $defaults Array that serves as the defaults.
2320 * @return array Merged user defined values with defaults.
2322 function wp_parse_args( $args, $defaults = '' ) {
2323 if ( is_object( $args ) )
2324 $r = get_object_vars( $args );
2325 elseif ( is_array( $args ) )
2328 wp_parse_str( $args, $r );
2330 if ( is_array( $defaults ) )
2331 return array_merge( $defaults, $r );
2336 * Clean up an array, comma- or space-separated list of IDs.
2340 * @param array|string $list
2341 * @return array Sanitized array of IDs
2343 function wp_parse_id_list( $list ) {
2344 if ( !is_array($list) )
2345 $list = preg_split('/[\s,]+/', $list);
2347 return array_unique(array_map('absint', $list));
2351 * Extract a slice of an array, given a list of keys.
2355 * @param array $array The original array
2356 * @param array $keys The list of keys
2357 * @return array The array slice
2359 function wp_array_slice_assoc( $array, $keys ) {
2361 foreach ( $keys as $key )
2362 if ( isset( $array[ $key ] ) )
2363 $slice[ $key ] = $array[ $key ];
2369 * Filters a list of objects, based on a set of key => value arguments.
2373 * @param array $list An array of objects to filter
2374 * @param array $args An array of key => value arguments to match against each object
2375 * @param string $operator The logical operation to perform. 'or' means only one element
2376 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
2377 * @param bool|string $field A field from the object to place instead of the entire object
2378 * @return array A list of objects or object fields
2380 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
2381 if ( ! is_array( $list ) )
2384 $list = wp_list_filter( $list, $args, $operator );
2387 $list = wp_list_pluck( $list, $field );
2393 * Filters a list of objects, based on a set of key => value arguments.
2397 * @param array $list An array of objects to filter
2398 * @param array $args An array of key => value arguments to match against each object
2399 * @param string $operator The logical operation to perform:
2400 * 'AND' means all elements from the array must match;
2401 * 'OR' means only one element needs to match;
2402 * 'NOT' means no elements may match.
2403 * The default is 'AND'.
2406 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
2407 if ( ! is_array( $list ) )
2410 if ( empty( $args ) )
2413 $operator = strtoupper( $operator );
2414 $count = count( $args );
2415 $filtered = array();
2417 foreach ( $list as $key => $obj ) {
2418 $to_match = (array) $obj;
2421 foreach ( $args as $m_key => $m_value ) {
2422 if ( $m_value == $to_match[ $m_key ] )
2426 if ( ( 'AND' == $operator && $matched == $count )
2427 || ( 'OR' == $operator && $matched > 0 )
2428 || ( 'NOT' == $operator && 0 == $matched ) ) {
2429 $filtered[$key] = $obj;
2437 * Pluck a certain field out of each object in a list.
2441 * @param array $list A list of objects or arrays
2442 * @param int|string $field A field from the object to place instead of the entire object
2445 function wp_list_pluck( $list, $field ) {
2446 foreach ( $list as $key => $value ) {
2447 if ( is_object( $value ) )
2448 $list[ $key ] = $value->$field;
2450 $list[ $key ] = $value[ $field ];
2457 * Determines if Widgets library should be loaded.
2459 * Checks to make sure that the widgets library hasn't already been loaded. If
2460 * it hasn't, then it will load the widgets library and run an action hook.
2463 * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
2465 function wp_maybe_load_widgets() {
2466 if ( ! apply_filters('load_default_widgets', true) )
2468 require_once( ABSPATH . WPINC . '/default-widgets.php' );
2469 add_action( '_admin_menu', 'wp_widgets_add_menu' );
2473 * Append the Widgets menu to the themes main menu.
2476 * @uses $submenu The administration submenu list.
2478 function wp_widgets_add_menu() {
2480 $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
2481 ksort( $submenu['themes.php'], SORT_NUMERIC );
2485 * Flush all output buffers for PHP 5.2.
2487 * Make sure all output buffers are flushed before our singletons our destroyed.
2491 function wp_ob_end_flush_all() {
2492 $levels = ob_get_level();
2493 for ($i=0; $i<$levels; $i++)
2498 * Load custom DB error or display WordPress DB error.
2500 * If a file exists in the wp-content directory named db-error.php, then it will
2501 * be loaded instead of displaying the WordPress DB error. If it is not found,
2502 * then the WordPress DB error will be displayed instead.
2504 * The WordPress DB error sets the HTTP status header to 500 to try to prevent
2505 * search engines from caching the message. Custom DB messages should do the
2508 * This function was backported to the the WordPress 2.3.2, but originally was
2509 * added in WordPress 2.5.0.
2514 function dead_db() {
2517 // Load custom DB error template, if present.
2518 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
2519 require_once( WP_CONTENT_DIR . '/db-error.php' );
2523 // If installing or in the admin, provide the verbose message.
2524 if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
2525 wp_die($wpdb->error);
2527 // Otherwise, be terse.
2528 status_header( 500 );
2530 header( 'Content-Type: text/html; charset=utf-8' );
2532 wp_load_translations_early();
2535 <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
2537 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2538 <title><?php _e( 'Database Error' ); ?></title>
2542 <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
2550 * Converts value to nonnegative integer.
2554 * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
2555 * @return int An nonnegative integer
2557 function absint( $maybeint ) {
2558 return abs( intval( $maybeint ) );
2562 * Determines if the blog can be accessed over SSL.
2564 * Determines if blog can be accessed over SSL by using cURL to access the site
2565 * using the https in the siteurl. Requires cURL extension to work correctly.
2569 * @param string $url
2570 * @return bool Whether SSL access is available
2572 function url_is_accessable_via_ssl($url)
2574 if (in_array('curl', get_loaded_extensions())) {
2575 $ssl = preg_replace( '/^http:\/\//', 'https://', $url );
2578 curl_setopt($ch, CURLOPT_URL, $ssl);
2579 curl_setopt($ch, CURLOPT_FAILONERROR, true);
2580 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2581 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
2582 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
2586 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2589 if ($status == 200 || $status == 401) {
2597 * Marks a function as deprecated and informs when it has been used.
2599 * There is a hook deprecated_function_run that will be called that can be used
2600 * to get the backtrace up to what file and function called the deprecated
2603 * The current behavior is to trigger a user error if WP_DEBUG is true.
2605 * This function is to be used in every function that is deprecated.
2607 * @package WordPress
2612 * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
2613 * and the version the function was deprecated in.
2614 * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2615 * trigger or false to not trigger error.
2617 * @param string $function The function that was called
2618 * @param string $version The version of WordPress that deprecated the function
2619 * @param string $replacement Optional. The function that should have been called
2621 function _deprecated_function( $function, $version, $replacement = null ) {
2623 do_action( 'deprecated_function_run', $function, $replacement, $version );
2625 // Allow plugin to filter the output error trigger
2626 if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
2627 if ( ! is_null($replacement) )
2628 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2630 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2635 * Marks a file as deprecated and informs when it has been used.
2637 * There is a hook deprecated_file_included that will be called that can be used
2638 * to get the backtrace up to what file and function included the deprecated
2641 * The current behavior is to trigger a user error if WP_DEBUG is true.
2643 * This function is to be used in every file that is deprecated.
2645 * @package WordPress
2650 * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
2651 * the version in which the file was deprecated, and any message regarding the change.
2652 * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
2653 * trigger or false to not trigger error.
2655 * @param string $file The file that was included
2656 * @param string $version The version of WordPress that deprecated the file
2657 * @param string $replacement Optional. The file that should have been included based on ABSPATH
2658 * @param string $message Optional. A message regarding the change
2660 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
2662 do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
2664 // Allow plugin to filter the output error trigger
2665 if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
2666 $message = empty( $message ) ? '' : ' ' . $message;
2667 if ( ! is_null( $replacement ) )
2668 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
2670 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
2674 * Marks a function argument as deprecated and informs when it has been used.
2676 * This function is to be used whenever a deprecated function argument is used.
2677 * Before this function is called, the argument must be checked for whether it was
2678 * used by comparing it to its default value or evaluating whether it is empty.
2681 * if ( !empty($deprecated) )
2682 * _deprecated_argument( __FUNCTION__, '3.0' );
2685 * There is a hook deprecated_argument_run that will be called that can be used
2686 * to get the backtrace up to what file and function used the deprecated
2689 * The current behavior is to trigger a user error if WP_DEBUG is true.
2691 * @package WordPress
2696 * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
2697 * and the version in which the argument was deprecated.
2698 * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
2699 * trigger or false to not trigger error.
2701 * @param string $function The function that was called
2702 * @param string $version The version of WordPress that deprecated the argument used
2703 * @param string $message Optional. A message regarding the change.
2705 function _deprecated_argument( $function, $version, $message = null ) {
2707 do_action( 'deprecated_argument_run', $function, $message, $version );
2709 // Allow plugin to filter the output error trigger
2710 if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
2711 if ( ! is_null( $message ) )
2712 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
2714 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 ) );
2719 * Marks something as being incorrectly called.
2721 * There is a hook doing_it_wrong_run that will be called that can be used
2722 * to get the backtrace up to what file and function called the deprecated
2725 * The current behavior is to trigger a user error if WP_DEBUG is true.
2727 * @package WordPress
2732 * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
2733 * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
2734 * trigger or false to not trigger error.
2736 * @param string $function The function that was called.
2737 * @param string $message A message explaining what has been done incorrectly.
2738 * @param string $version The version of WordPress where the message was added.
2740 function _doing_it_wrong( $function, $message, $version ) {
2742 do_action( 'doing_it_wrong_run', $function, $message, $version );
2744 // Allow plugin to filter the output error trigger
2745 if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
2746 $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
2747 $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
2748 trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
2753 * Is the server running earlier than 1.5.0 version of lighttpd?
2757 * @return bool Whether the server is running lighttpd < 1.5.0
2759 function is_lighttpd_before_150() {
2760 $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
2761 $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
2762 return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
2766 * Does the specified module exist in the Apache config?
2770 * @param string $mod e.g. mod_rewrite
2771 * @param bool $default The default return value if the module is not found
2774 function apache_mod_loaded($mod, $default = false) {
2780 if ( function_exists('apache_get_modules') ) {
2781 $mods = apache_get_modules();
2782 if ( in_array($mod, $mods) )
2784 } elseif ( function_exists('phpinfo') ) {
2787 $phpinfo = ob_get_clean();
2788 if ( false !== strpos($phpinfo, $mod) )
2795 * Check if IIS 7 supports pretty permalinks.
2801 function iis7_supports_permalinks() {
2804 $supports_permalinks = false;
2806 /* First we check if the DOMDocument class exists. If it does not exist,
2807 * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
2808 * hence we just bail out and tell user that pretty permalinks cannot be used.
2809 * This is not a big issue because PHP 4.X is going to be deprecated and for IIS it
2810 * is recommended to use PHP 5.X NTS.
2811 * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
2812 * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
2813 * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
2814 * via ISAPI then pretty permalinks will not work.
2816 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
2819 return apply_filters('iis7_supports_permalinks', $supports_permalinks);
2823 * File validates against allowed set of defined rules.
2825 * A return value of '1' means that the $file contains either '..' or './'. A
2826 * return value of '2' means that the $file contains ':' after the first
2827 * character. A return value of '3' means that the file is not in the allowed
2832 * @param string $file File path.
2833 * @param array $allowed_files List of allowed files.
2834 * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
2836 function validate_file( $file, $allowed_files = '' ) {
2837 if ( false !== strpos( $file, '..' ) )
2840 if ( false !== strpos( $file, './' ) )
2843 if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
2846 if (':' == substr( $file, 1, 1 ) )
2853 * Determine if SSL is used.
2857 * @return bool True if SSL, false if not used.
2860 if ( isset($_SERVER['HTTPS']) ) {
2861 if ( 'on' == strtolower($_SERVER['HTTPS']) )
2863 if ( '1' == $_SERVER['HTTPS'] )
2865 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
2872 * Whether SSL login should be forced.
2876 * @param string|bool $force Optional.
2877 * @return bool True if forced, false if not forced.
2879 function force_ssl_login( $force = null ) {
2880 static $forced = false;
2882 if ( !is_null( $force ) ) {
2883 $old_forced = $forced;
2892 * Whether to force SSL used for the Administration Screens.
2896 * @param string|bool $force
2897 * @return bool True if forced, false if not forced.
2899 function force_ssl_admin( $force = null ) {
2900 static $forced = false;
2902 if ( !is_null( $force ) ) {
2903 $old_forced = $forced;
2912 * Guess the URL for the site.
2914 * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
2921 function wp_guess_url() {
2922 if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
2925 $schema = is_ssl() ? 'https://' : 'http://';
2926 $url = preg_replace('#/(wp-admin/.*|wp-login.php)#i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
2928 return rtrim($url, '/');
2932 * Temporarily suspend cache additions.
2934 * Stops more data being added to the cache, but still allows cache retrieval.
2935 * This is useful for actions, such as imports, when a lot of data would otherwise
2936 * be almost uselessly added to the cache.
2938 * Suspension lasts for a single page load at most. Remember to call this
2939 * function again if you wish to re-enable cache adds earlier.
2943 * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
2944 * @return bool The current suspend setting
2946 function wp_suspend_cache_addition( $suspend = null ) {
2947 static $_suspend = false;
2949 if ( is_bool( $suspend ) )
2950 $_suspend = $suspend;
2956 * Suspend cache invalidation.
2958 * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
2959 * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
2960 * cache when invalidation is suspended.
2964 * @param bool $suspend Whether to suspend or enable cache invalidation
2965 * @return bool The current suspend setting
2967 function wp_suspend_cache_invalidation($suspend = true) {
2968 global $_wp_suspend_cache_invalidation;
2970 $current_suspend = $_wp_suspend_cache_invalidation;
2971 $_wp_suspend_cache_invalidation = $suspend;
2972 return $current_suspend;
2980 * @package WordPress
2982 * @param int $blog_id optional blog id to test (default current blog)
2983 * @return bool True if not multisite or $blog_id is main site
2985 function is_main_site( $blog_id = '' ) {
2986 global $current_site, $current_blog;
2988 if ( !is_multisite() )
2992 $blog_id = $current_blog->blog_id;
2994 return $blog_id == $current_site->blog_id;
2998 * Whether global terms are enabled.
3002 * @package WordPress
3004 * @return bool True if multisite and global terms enabled
3006 function global_terms_enabled() {
3007 if ( ! is_multisite() )
3010 static $global_terms = null;
3011 if ( is_null( $global_terms ) ) {
3012 $filter = apply_filters( 'global_terms_enabled', null );
3013 if ( ! is_null( $filter ) )
3014 $global_terms = (bool) $filter;
3016 $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
3018 return $global_terms;
3022 * gmt_offset modification for smart timezone handling.
3024 * Overrides the gmt_offset option if we have a timezone_string available.
3028 * @return float|bool
3030 function wp_timezone_override_offset() {
3031 if ( !$timezone_string = get_option( 'timezone_string' ) ) {
3035 $timezone_object = timezone_open( $timezone_string );
3036 $datetime_object = date_create();
3037 if ( false === $timezone_object || false === $datetime_object ) {
3040 return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
3044 * {@internal Missing Short Description}}
3048 * @param unknown_type $a
3049 * @param unknown_type $b
3052 function _wp_timezone_choice_usort_callback( $a, $b ) {
3053 // Don't use translated versions of Etc
3054 if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
3055 // Make the order of these more like the old dropdown
3056 if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3057 return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
3059 if ( 'UTC' === $a['city'] ) {
3060 if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3065 if ( 'UTC' === $b['city'] ) {
3066 if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
3071 return strnatcasecmp( $a['city'], $b['city'] );
3073 if ( $a['t_continent'] == $b['t_continent'] ) {
3074 if ( $a['t_city'] == $b['t_city'] ) {
3075 return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
3077 return strnatcasecmp( $a['t_city'], $b['t_city'] );
3079 // Force Etc to the bottom of the list
3080 if ( 'Etc' === $a['continent'] ) {
3083 if ( 'Etc' === $b['continent'] ) {
3086 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
3091 * Gives a nicely formatted list of timezone strings. // temporary! Not in final
3095 * @param string $selected_zone Selected Zone
3098 function wp_timezone_choice( $selected_zone ) {
3099 static $mo_loaded = false;
3101 $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
3103 // Load translations for continents and cities
3104 if ( !$mo_loaded ) {
3105 $locale = get_locale();
3106 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
3107 load_textdomain( 'continents-cities', $mofile );
3112 foreach ( timezone_identifiers_list() as $zone ) {
3113 $zone = explode( '/', $zone );
3114 if ( !in_array( $zone[0], $continents ) ) {
3118 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
3120 0 => ( isset( $zone[0] ) && $zone[0] ),
3121 1 => ( isset( $zone[1] ) && $zone[1] ),
3122 2 => ( isset( $zone[2] ) && $zone[2] ),
3124 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
3125 $exists[4] = ( $exists[1] && $exists[3] );
3126 $exists[5] = ( $exists[2] && $exists[3] );
3129 'continent' => ( $exists[0] ? $zone[0] : '' ),
3130 'city' => ( $exists[1] ? $zone[1] : '' ),
3131 'subcity' => ( $exists[2] ? $zone[2] : '' ),
3132 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
3133 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
3134 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
3137 usort( $zonen, '_wp_timezone_choice_usort_callback' );
3139 $structure = array();
3141 if ( empty( $selected_zone ) ) {
3142 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
3145 foreach ( $zonen as $key => $zone ) {
3146 // Build value in an array to join later
3147 $value = array( $zone['continent'] );
3149 if ( empty( $zone['city'] ) ) {
3150 // It's at the continent level (generally won't happen)
3151 $display = $zone['t_continent'];
3153 // It's inside a continent group
3155 // Continent optgroup
3156 if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
3157 $label = $zone['t_continent'];
3158 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
3161 // Add the city to the value
3162 $value[] = $zone['city'];
3164 $display = $zone['t_city'];
3165 if ( !empty( $zone['subcity'] ) ) {
3166 // Add the subcity to the value
3167 $value[] = $zone['subcity'];
3168 $display .= ' - ' . $zone['t_subcity'];
3173 $value = join( '/', $value );
3175 if ( $value === $selected_zone ) {
3176 $selected = 'selected="selected" ';
3178 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
3180 // Close continent optgroup
3181 if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
3182 $structure[] = '</optgroup>';
3187 $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
3189 if ( 'UTC' === $selected_zone )
3190 $selected = 'selected="selected" ';
3191 $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
3192 $structure[] = '</optgroup>';
3194 // Do manual UTC offsets
3195 $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
3196 $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,
3197 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);
3198 foreach ( $offset_range as $offset ) {
3200 $offset_name = '+' . $offset;
3202 $offset_name = (string) $offset;
3204 $offset_value = $offset_name;
3205 $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
3206 $offset_name = 'UTC' . $offset_name;
3207 $offset_value = 'UTC' . $offset_value;
3209 if ( $offset_value === $selected_zone )
3210 $selected = 'selected="selected" ';
3211 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
3214 $structure[] = '</optgroup>';
3216 return join( "\n", $structure );
3220 * Strip close comment and close php tags from file headers used by WP.
3221 * See http://core.trac.wordpress.org/ticket/8497
3225 * @param string $str
3228 function _cleanup_header_comment($str) {
3229 return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
3233 * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
3237 function wp_scheduled_delete() {
3240 $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
3242 $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);
3244 foreach ( (array) $posts_to_delete as $post ) {
3245 $post_id = (int) $post['post_id'];
3249 $del_post = get_post($post_id);
3251 if ( !$del_post || 'trash' != $del_post->post_status ) {
3252 delete_post_meta($post_id, '_wp_trash_meta_status');
3253 delete_post_meta($post_id, '_wp_trash_meta_time');
3255 wp_delete_post($post_id);
3259 $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);
3261 foreach ( (array) $comments_to_delete as $comment ) {
3262 $comment_id = (int) $comment['comment_id'];
3266 $del_comment = get_comment($comment_id);
3268 if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
3269 delete_comment_meta($comment_id, '_wp_trash_meta_time');
3270 delete_comment_meta($comment_id, '_wp_trash_meta_status');
3272 wp_delete_comment($comment_id);
3278 * Retrieve metadata from a file.
3280 * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
3281 * Each piece of metadata must be on its own line. Fields can not span multiple
3282 * lines, the value will get cut at the end of the first line.
3284 * If the file data is not within that first 8kiB, then the author should correct
3285 * their plugin file and move the data headers to the top.
3287 * @see http://codex.wordpress.org/File_Header
3290 * @param string $file Path to the file
3291 * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
3292 * @param string $context If specified adds filter hook "extra_{$context}_headers"
3294 function get_file_data( $file, $default_headers, $context = '' ) {
3295 // We don't need to write to the file, so just open for reading.
3296 $fp = fopen( $file, 'r' );
3298 // Pull only the first 8kiB of the file in.
3299 $file_data = fread( $fp, 8192 );
3301 // PHP will close file handle, but we are good citizens.
3304 // Make sure we catch CR-only line endings.
3305 $file_data = str_replace( "\r", "\n", $file_data );
3307 if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
3308 $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
3309 $all_headers = array_merge( $extra_headers, (array) $default_headers );
3311 $all_headers = $default_headers;
3314 foreach ( $all_headers as $field => $regex ) {
3315 if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
3316 $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
3318 $all_headers[ $field ] = '';
3321 return $all_headers;
3325 * Used internally to tidy up the search terms.
3333 function _search_terms_tidy($t) {
3334 return trim($t, "\"'\n\r ");
3340 * Useful for returning true to filters easily.
3343 * @see __return_false()
3346 function __return_true() {
3353 * Useful for returning false to filters easily.
3356 * @see __return_true()
3357 * @return bool false
3359 function __return_false() {
3366 * Useful for returning 0 to filters easily.
3369 * @see __return_zero()
3372 function __return_zero() {
3377 * Returns an empty array.
3379 * Useful for returning an empty array to filters easily.
3382 * @see __return_zero()
3383 * @return array Empty array
3385 function __return_empty_array() {
3392 * Useful for returning null to filters easily.
3397 function __return_null() {
3402 * Send a HTTP header to disable content type sniffing in browsers which support it.
3404 * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
3405 * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
3410 function send_nosniff_header() {
3411 @header( 'X-Content-Type-Options: nosniff' );
3415 * Returns a MySQL expression for selecting the week number based on the start_of_week option.
3419 * @param string $column
3422 function _wp_mysql_week( $column ) {
3423 switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
3426 return "WEEK( $column, 0 )";
3428 return "WEEK( $column, 1 )";
3434 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
3439 * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
3444 * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
3445 * @param int $start The ID to start the loop check at
3446 * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
3447 * @param array $callback_args optional additional arguments to send to $callback
3448 * @return array IDs of all members of loop
3450 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
3451 $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
3453 if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
3456 return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
3460 * Uses the "The Tortoise and the Hare" algorithm to detect loops.
3462 * For every step of the algorithm, the hare takes two steps and the tortoise one.
3463 * If the hare ever laps the tortoise, there must be a loop.
3468 * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
3469 * @param int $start The ID to start the loop check at
3470 * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
3471 * @param array $callback_args optional additional arguments to send to $callback
3472 * @param bool $_return_loop Return loop members or just detect presence of loop?
3473 * Only set to true if you already know the given $start is part of a loop
3474 * (otherwise the returned array might include branches)
3475 * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
3477 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
3478 $tortoise = $hare = $evanescent_hare = $start;
3481 // Set evanescent_hare to one past hare
3482 // Increment hare two steps
3486 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
3488 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
3490 if ( $_return_loop )
3491 $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
3493 // tortoise got lapped - must be a loop
3494 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
3495 return $_return_loop ? $return : $tortoise;
3497 // Increment tortoise by one step
3498 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
3505 * Send a HTTP header to limit rendering of pages to same origin iframes.
3507 * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
3512 function send_frame_options_header() {
3513 @header( 'X-Frame-Options: SAMEORIGIN' );
3517 * Retrieve a list of protocols to allow in HTML attributes.
3523 * @return array Array of allowed protocols
3525 function wp_allowed_protocols() {
3528 if ( empty( $protocols ) ) {
3529 $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' );
3530 $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
3537 * Return a comma separated string of functions that have been called to get to the current point in code.
3539 * @link http://core.trac.wordpress.org/ticket/19589
3542 * @param string $ignore_class A class to ignore all function calls within - useful when you want to just give info about the callee
3543 * @param int $skip_frames A number of stack frames to skip - useful for unwinding back to the source of the issue
3544 * @param bool $pretty Whether or not you want a comma separated string or raw array returned
3545 * @return string|array Either a string containing a reversed comma separated trace or an array of individual calls.
3547 function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
3548 if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
3549 $trace = debug_backtrace( false );
3551 $trace = debug_backtrace();
3554 $check_class = ! is_null( $ignore_class );
3555 $skip_frames++; // skip this function
3557 foreach ( $trace as $call ) {
3558 if ( $skip_frames > 0 ) {
3560 } elseif ( isset( $call['class'] ) ) {
3561 if ( $check_class && $ignore_class == $call['class'] )
3562 continue; // Filter out calls
3564 $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
3566 if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
3567 $caller[] = "{$call['function']}('{$call['args'][0]}')";
3568 } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
3569 $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
3571 $caller[] = $call['function'];
3576 return join( ', ', array_reverse( $caller ) );
3582 * Retrieve ids that are not already present in the cache
3586 * @param array $object_ids ID list
3587 * @param string $cache_key The cache bucket to check against
3591 function _get_non_cached_ids( $object_ids, $cache_key ) {
3593 foreach ( $object_ids as $id ) {
3595 if ( !wp_cache_get( $id, $cache_key ) ) {
3604 * Test if the current device has the capability to upload files.
3609 * @return bool true|false
3611 function _device_can_upload() {
3612 if ( ! wp_is_mobile() )
3615 $ua = $_SERVER['HTTP_USER_AGENT'];
3617 if ( strpos($ua, 'iPhone') !== false
3618 || strpos($ua, 'iPad') !== false
3619 || strpos($ua, 'iPod') !== false ) {
3620 return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );