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' ) * HOUR_IN_SECONDS ) ) );
65 return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
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 - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
218 $end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
219 return compact( 'start', 'end' );
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 ( wp_get_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 $args = func_get_args();
641 if ( is_array( $args[0] ) ) {
642 if ( count( $args ) < 2 || false === $args[1] )
643 $uri = $_SERVER['REQUEST_URI'];
647 if ( count( $args ) < 3 || false === $args[2] )
648 $uri = $_SERVER['REQUEST_URI'];
653 if ( $frag = strstr( $uri, '#' ) )
654 $uri = substr( $uri, 0, -strlen( $frag ) );
658 if ( 0 === stripos( 'http://', $uri ) ) {
659 $protocol = 'http://';
660 $uri = substr( $uri, 7 );
661 } elseif ( 0 === stripos( 'https://', $uri ) ) {
662 $protocol = 'https://';
663 $uri = substr( $uri, 8 );
668 if ( strpos( $uri, '?' ) !== false ) {
669 $parts = explode( '?', $uri, 2 );
670 if ( 1 == count( $parts ) ) {
674 $base = $parts[0] . '?';
677 } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
685 wp_parse_str( $query, $qs );
686 $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
687 if ( is_array( $args[0] ) ) {
689 $qs = array_merge( $qs, $kayvees );
691 $qs[ $args[0] ] = $args[1];
694 foreach ( $qs as $k => $v ) {
699 $ret = build_query( $qs );
700 $ret = trim( $ret, '?' );
701 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
702 $ret = $protocol . $base . $ret . $frag;
703 $ret = rtrim( $ret, '?' );
708 * Removes an item or list from the query string.
712 * @param string|array $key Query key or keys to remove.
713 * @param bool $query When false uses the $_SERVER value.
714 * @return string New URL query string.
716 function remove_query_arg( $key, $query=false ) {
717 if ( is_array( $key ) ) { // removing multiple keys
718 foreach ( $key as $k )
719 $query = add_query_arg( $k, false, $query );
722 return add_query_arg( $key, false, $query );
726 * Walks the array while sanitizing the contents.
730 * @param array $array Array to used to walk while sanitizing contents.
731 * @return array Sanitized $array.
733 function add_magic_quotes( $array ) {
734 foreach ( (array) $array as $k => $v ) {
735 if ( is_array( $v ) ) {
736 $array[$k] = add_magic_quotes( $v );
738 $array[$k] = addslashes( $v );
745 * HTTP request for URI to retrieve content.
748 * @uses wp_remote_get()
750 * @param string $uri URI/URL of web page to retrieve.
751 * @return bool|string HTTP content. False on failure.
753 function wp_remote_fopen( $uri ) {
754 $parsed_url = @parse_url( $uri );
756 if ( !$parsed_url || !is_array( $parsed_url ) )
760 $options['timeout'] = 10;
762 $response = wp_remote_get( $uri, $options );
764 if ( is_wp_error( $response ) )
767 return wp_remote_retrieve_body( $response );
771 * Set up the WordPress query.
775 * @param string $query_vars Default WP_Query arguments.
777 function wp( $query_vars = '' ) {
778 global $wp, $wp_query, $wp_the_query;
779 $wp->main( $query_vars );
781 if ( !isset($wp_the_query) )
782 $wp_the_query = $wp_query;
786 * Retrieve the description for the HTTP status.
790 * @param int $code HTTP status code.
791 * @return string Empty string if not found, or description if found.
793 function get_status_header_desc( $code ) {
794 global $wp_header_to_desc;
796 $code = absint( $code );
798 if ( !isset( $wp_header_to_desc ) ) {
799 $wp_header_to_desc = array(
801 101 => 'Switching Protocols',
807 203 => 'Non-Authoritative Information',
809 205 => 'Reset Content',
810 206 => 'Partial Content',
811 207 => 'Multi-Status',
814 300 => 'Multiple Choices',
815 301 => 'Moved Permanently',
818 304 => 'Not Modified',
821 307 => 'Temporary Redirect',
823 400 => 'Bad Request',
824 401 => 'Unauthorized',
825 402 => 'Payment Required',
828 405 => 'Method Not Allowed',
829 406 => 'Not Acceptable',
830 407 => 'Proxy Authentication Required',
831 408 => 'Request Timeout',
834 411 => 'Length Required',
835 412 => 'Precondition Failed',
836 413 => 'Request Entity Too Large',
837 414 => 'Request-URI Too Long',
838 415 => 'Unsupported Media Type',
839 416 => 'Requested Range Not Satisfiable',
840 417 => 'Expectation Failed',
841 422 => 'Unprocessable Entity',
843 424 => 'Failed Dependency',
844 426 => 'Upgrade Required',
846 500 => 'Internal Server Error',
847 501 => 'Not Implemented',
848 502 => 'Bad Gateway',
849 503 => 'Service Unavailable',
850 504 => 'Gateway Timeout',
851 505 => 'HTTP Version Not Supported',
852 506 => 'Variant Also Negotiates',
853 507 => 'Insufficient Storage',
854 510 => 'Not Extended'
858 if ( isset( $wp_header_to_desc[$code] ) )
859 return $wp_header_to_desc[$code];
865 * Set HTTP status header.
868 * @uses apply_filters() Calls 'status_header' on status header string, HTTP
869 * HTTP code, HTTP code description, and protocol string as separate
872 * @param int $header HTTP status code
875 function status_header( $header ) {
876 $text = get_status_header_desc( $header );
878 if ( empty( $text ) )
881 $protocol = $_SERVER["SERVER_PROTOCOL"];
882 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
883 $protocol = 'HTTP/1.0';
884 $status_header = "$protocol $header $text";
885 if ( function_exists( 'apply_filters' ) )
886 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
888 return @header( $status_header, true, $header );
892 * Gets the header information to prevent caching.
894 * The several different headers cover the different ways cache prevention is handled
895 * by different browsers
899 * @uses apply_filters()
900 * @return array The associative array of header names and field values.
902 function wp_get_nocache_headers() {
904 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
905 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
906 'Pragma' => 'no-cache',
909 if ( function_exists('apply_filters') ) {
910 $headers = (array) apply_filters('nocache_headers', $headers);
912 $headers['Last-Modified'] = false;
917 * Sets the headers to prevent caching for the different browsers.
919 * Different browsers support different nocache headers, so several headers must
920 * be sent so that all of them get the point that no caching should occur.
923 * @uses wp_get_nocache_headers()
925 function nocache_headers() {
926 $headers = wp_get_nocache_headers();
928 unset( $headers['Last-Modified'] );
930 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
931 if ( function_exists( 'header_remove' ) ) {
932 @header_remove( 'Last-Modified' );
934 // In PHP 5.2, send an empty Last-Modified header, but only as a
935 // last resort to override a header already sent. #WP23021
936 foreach ( headers_list() as $header ) {
937 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
938 $headers['Last-Modified'] = '';
944 foreach( $headers as $name => $field_value )
945 @header("{$name}: {$field_value}");
949 * Set the headers for caching for 10 days with JavaScript content type.
953 function cache_javascript_headers() {
954 $expiresOffset = 10 * DAY_IN_SECONDS;
955 header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
956 header( "Vary: Accept-Encoding" ); // Handle proxies
957 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
961 * Retrieve the number of database queries during the WordPress execution.
965 * @return int Number of database queries
967 function get_num_queries() {
969 return $wpdb->num_queries;
973 * Whether input is yes or no. Must be 'y' to be true.
977 * @param string $yn Character string containing either 'y' or 'n'
978 * @return bool True if yes, false on anything else
980 function bool_from_yn( $yn ) {
981 return ( strtolower( $yn ) == 'y' );
985 * Loads the feed template from the use of an action hook.
987 * If the feed action does not have a hook, then the function will die with a
988 * message telling the visitor that the feed is not valid.
990 * It is better to only have one hook for each feed.
993 * @uses $wp_query Used to tell if the use a comment feed.
994 * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
999 $feed = get_query_var( 'feed' );
1001 // Remove the pad, if present.
1002 $feed = preg_replace( '/^_+/', '', $feed );
1004 if ( $feed == '' || $feed == 'feed' )
1005 $feed = get_default_feed();
1007 $hook = 'do_feed_' . $feed;
1008 if ( !has_action($hook) ) {
1009 $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
1010 wp_die( $message, '', array( 'response' => 404 ) );
1013 do_action( $hook, $wp_query->is_comment_feed );
1017 * Load the RDF RSS 0.91 Feed template.
1021 function do_feed_rdf() {
1022 load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1026 * Load the RSS 1.0 Feed Template.
1030 function do_feed_rss() {
1031 load_template( ABSPATH . WPINC . '/feed-rss.php' );
1035 * Load either the RSS2 comment feed or the RSS2 posts feed.
1039 * @param bool $for_comments True for the comment feed, false for normal feed.
1041 function do_feed_rss2( $for_comments ) {
1042 if ( $for_comments )
1043 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1045 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1049 * Load either Atom comment feed or Atom posts feed.
1053 * @param bool $for_comments True for the comment feed, false for normal feed.
1055 function do_feed_atom( $for_comments ) {
1057 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1059 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1063 * Display the robots.txt file content.
1065 * The echo content should be with usage of the permalinks or for creating the
1069 * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
1071 function do_robots() {
1072 header( 'Content-Type: text/plain; charset=utf-8' );
1074 do_action( 'do_robotstxt' );
1076 $output = "User-agent: *\n";
1077 $public = get_option( 'blog_public' );
1078 if ( '0' == $public ) {
1079 $output .= "Disallow: /\n";
1081 $site_url = parse_url( site_url() );
1082 $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1083 $output .= "Disallow: $path/wp-admin/\n";
1084 $output .= "Disallow: $path/wp-includes/\n";
1087 echo apply_filters('robots_txt', $output, $public);
1091 * Test whether blog is already installed.
1093 * The cache will be checked first. If you have a cache plugin, which saves the
1094 * cache values, then this will work. If you use the default WordPress cache,
1095 * and the database goes away, then you might have problems.
1097 * Checks for the option siteurl for whether WordPress is installed.
1102 * @return bool Whether blog is already installed.
1104 function is_blog_installed() {
1107 // Check cache first. If options table goes away and we have true cached, oh well.
1108 if ( wp_cache_get( 'is_blog_installed' ) )
1111 $suppress = $wpdb->suppress_errors();
1112 if ( ! defined( 'WP_INSTALLING' ) ) {
1113 $alloptions = wp_load_alloptions();
1115 // If siteurl is not set to autoload, check it specifically
1116 if ( !isset( $alloptions['siteurl'] ) )
1117 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1119 $installed = $alloptions['siteurl'];
1120 $wpdb->suppress_errors( $suppress );
1122 $installed = !empty( $installed );
1123 wp_cache_set( 'is_blog_installed', $installed );
1128 // If visiting repair.php, return true and let it take over.
1129 if ( defined( 'WP_REPAIRING' ) )
1132 $suppress = $wpdb->suppress_errors();
1134 // Loop over the WP tables. If none exist, then scratch install is allowed.
1135 // If one or more exist, suggest table repair since we got here because the options
1136 // table could not be accessed.
1137 $wp_tables = $wpdb->tables();
1138 foreach ( $wp_tables as $table ) {
1139 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1140 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1142 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1145 if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
1148 // One or more tables exist. We are insane.
1150 wp_load_translations_early();
1152 // Die with a DB error.
1153 $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' );
1157 $wpdb->suppress_errors( $suppress );
1159 wp_cache_set( 'is_blog_installed', false );
1165 * Retrieve URL with nonce added to URL query.
1167 * @package WordPress
1168 * @subpackage Security
1171 * @param string $actionurl URL to add nonce action
1172 * @param string $action Optional. Nonce action name
1173 * @return string URL with nonce action added.
1175 function wp_nonce_url( $actionurl, $action = -1 ) {
1176 $actionurl = str_replace( '&', '&', $actionurl );
1177 return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
1181 * Retrieve or display nonce hidden field for forms.
1183 * The nonce field is used to validate that the contents of the form came from
1184 * the location on the current site and not somewhere else. The nonce does not
1185 * offer absolute protection, but should protect against most cases. It is very
1186 * important to use nonce field in forms.
1188 * The $action and $name are optional, but if you want to have better security,
1189 * it is strongly suggested to set those two parameters. It is easier to just
1190 * call the function without any parameters, because validation of the nonce
1191 * doesn't require any parameters, but since crackers know what the default is
1192 * it won't be difficult for them to find a way around your nonce and cause
1195 * The input name will be whatever $name value you gave. The input value will be
1196 * the nonce creation value.
1198 * @package WordPress
1199 * @subpackage Security
1202 * @param string $action Optional. Action name.
1203 * @param string $name Optional. Nonce name.
1204 * @param bool $referer Optional, default true. Whether to set the referer field for validation.
1205 * @param bool $echo Optional, default true. Whether to display or return hidden form field.
1206 * @return string Nonce field.
1208 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1209 $name = esc_attr( $name );
1210 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1213 $nonce_field .= wp_referer_field( false );
1218 return $nonce_field;
1222 * Retrieve or display referer hidden field for forms.
1224 * The referer link is the current Request URI from the server super global. The
1225 * input name is '_wp_http_referer', in case you wanted to check manually.
1227 * @package WordPress
1228 * @subpackage Security
1231 * @param bool $echo Whether to echo or return the referer field.
1232 * @return string Referer field.
1234 function wp_referer_field( $echo = true ) {
1235 $ref = esc_attr( $_SERVER['REQUEST_URI'] );
1236 $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
1239 echo $referer_field;
1240 return $referer_field;
1244 * Retrieve or display original referer hidden field for forms.
1246 * The input name is '_wp_original_http_referer' and will be either the same
1247 * value of {@link wp_referer_field()}, if that was posted already or it will
1248 * be the current page, if it doesn't exist.
1250 * @package WordPress
1251 * @subpackage Security
1254 * @param bool $echo Whether to echo the original http referer
1255 * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
1256 * @return string Original referer field.
1258 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1259 $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
1260 $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
1261 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
1263 echo $orig_referer_field;
1264 return $orig_referer_field;
1268 * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
1269 * as the current request URL, will return false.
1271 * @package WordPress
1272 * @subpackage Security
1275 * @return string|bool False on failure. Referer URL on success.
1277 function wp_get_referer() {
1279 if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
1280 $ref = $_REQUEST['_wp_http_referer'];
1281 else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
1282 $ref = $_SERVER['HTTP_REFERER'];
1284 if ( $ref && $ref !== $_SERVER['REQUEST_URI'] )
1290 * Retrieve original referer that was posted, if it exists.
1292 * @package WordPress
1293 * @subpackage Security
1296 * @return string|bool False if no original referer or original referer if set.
1298 function wp_get_original_referer() {
1299 if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
1300 return $_REQUEST['_wp_original_http_referer'];
1305 * Recursive directory creation based on full path.
1307 * Will attempt to set permissions on folders.
1311 * @param string $target Full path to attempt to create.
1312 * @return bool Whether the path was created. True if path already exists.
1314 function wp_mkdir_p( $target ) {
1317 // strip the protocol
1318 if( wp_is_stream( $target ) ) {
1319 list( $wrapper, $target ) = explode( '://', $target, 2 );
1322 // from php.net/mkdir user contributed notes
1323 $target = str_replace( '//', '/', $target );
1325 // put the wrapper back on the target
1326 if( $wrapper !== null ) {
1327 $target = $wrapper . '://' . $target;
1330 // safe mode fails with a trailing slash under certain PHP versions.
1331 $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1332 if ( empty($target) )
1335 if ( file_exists( $target ) )
1336 return @is_dir( $target );
1338 // Attempting to create the directory may clutter up our display.
1339 if ( @mkdir( $target ) ) {
1340 $stat = @stat( dirname( $target ) );
1341 $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
1342 @chmod( $target, $dir_perms );
1344 } elseif ( is_dir( dirname( $target ) ) ) {
1348 // If the above failed, attempt to create the parent node, then try again.
1349 if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
1350 return wp_mkdir_p( $target );
1356 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
1360 * @param string $path File path
1361 * @return bool True if path is absolute, false is not absolute.
1363 function path_is_absolute( $path ) {
1364 // this is definitive if true but fails if $path does not exist or contains a symbolic link
1365 if ( realpath($path) == $path )
1368 if ( strlen($path) == 0 || $path[0] == '.' )
1371 // windows allows absolute paths like this
1372 if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1375 // a path starting with / or \ is absolute; anything else is relative
1376 return ( $path[0] == '/' || $path[0] == '\\' );
1380 * Join two filesystem paths together (e.g. 'give me $path relative to $base').
1382 * If the $path is absolute, then it the full path is returned.
1386 * @param string $base
1387 * @param string $path
1388 * @return string The path with the base or absolute path.
1390 function path_join( $base, $path ) {
1391 if ( path_is_absolute($path) )
1394 return rtrim($base, '/') . '/' . ltrim($path, '/');
1398 * Determines a writable directory for temporary files.
1399 * Function's preference is the return value of <code>sys_get_temp_dir()</code>,
1400 * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
1401 * before finally defaulting to /tmp/
1403 * In the event that this function does not find a writable location,
1404 * It may be overridden by the <code>WP_TEMP_DIR</code> constant in
1405 * your <code>wp-config.php</code> file.
1409 * @return string Writable temporary directory
1411 function get_temp_dir() {
1413 if ( defined('WP_TEMP_DIR') )
1414 return trailingslashit(WP_TEMP_DIR);
1417 return trailingslashit( rtrim( $temp, '\\' ) );
1419 $is_win = ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) );
1421 if ( function_exists('sys_get_temp_dir') ) {
1422 $temp = sys_get_temp_dir();
1423 if ( @is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) ) {
1424 return trailingslashit( rtrim( $temp, '\\' ) );
1428 $temp = ini_get('upload_tmp_dir');
1429 if ( is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) )
1430 return trailingslashit( rtrim( $temp, '\\' ) );
1432 $temp = WP_CONTENT_DIR . '/';
1433 if ( is_dir( $temp ) && ( $is_win ? win_is_writable( $temp ) : @is_writable( $temp ) ) )
1441 * Workaround for Windows bug in is_writable() function
1445 * @param string $path
1448 function win_is_writable( $path ) {
1449 /* will work in despite of Windows ACLs bug
1450 * NOTE: use a trailing slash for folders!!!
1451 * see http://bugs.php.net/bug.php?id=27609
1452 * see http://bugs.php.net/bug.php?id=30931
1455 if ( $path[strlen( $path ) - 1] == '/' ) // recursively return a temporary file path
1456 return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
1457 else if ( is_dir( $path ) )
1458 return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
1459 // check tmp file for read/write capabilities
1460 $should_delete_tmp_file = !file_exists( $path );
1461 $f = @fopen( $path, 'a' );
1465 if ( $should_delete_tmp_file )
1471 * Get an array containing the current upload directory's path and url.
1473 * Checks the 'upload_path' option, which should be from the web root folder,
1474 * and if it isn't empty it will be used. If it is empty, then the path will be
1475 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
1476 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
1478 * The upload URL path is set either by the 'upload_url_path' option or by using
1479 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
1481 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
1482 * the administration settings panel), then the time will be used. The format
1483 * will be year first and then month.
1485 * If the path couldn't be created, then an error will be returned with the key
1486 * 'error' containing the error message. The error suggests that the parent
1487 * directory is not writable by the server.
1489 * On success, the returned array will have many indices:
1490 * 'path' - base directory and sub directory or full path to upload directory.
1491 * 'url' - base url and sub directory or absolute URL to upload directory.
1492 * 'subdir' - sub directory if uploads use year/month folders option is on.
1493 * 'basedir' - path without subdir.
1494 * 'baseurl' - URL path without subdir.
1495 * 'error' - set to false.
1498 * @uses apply_filters() Calls 'upload_dir' on returned array.
1500 * @param string $time Optional. Time formatted in 'yyyy/mm'.
1501 * @return array See above for description.
1503 function wp_upload_dir( $time = null ) {
1504 $siteurl = get_option( 'siteurl' );
1505 $upload_path = trim( get_option( 'upload_path' ) );
1507 if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
1508 $dir = WP_CONTENT_DIR . '/uploads';
1509 } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
1510 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
1511 $dir = path_join( ABSPATH, $upload_path );
1513 $dir = $upload_path;
1516 if ( !$url = get_option( 'upload_url_path' ) ) {
1517 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
1518 $url = WP_CONTENT_URL . '/uploads';
1520 $url = trailingslashit( $siteurl ) . $upload_path;
1523 // Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
1524 // We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
1525 if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
1526 $dir = ABSPATH . UPLOADS;
1527 $url = trailingslashit( $siteurl ) . UPLOADS;
1530 // If multisite (and if not the main site in a post-MU network)
1531 if ( is_multisite() && ! ( is_main_site() && defined( 'MULTISITE' ) ) ) {
1533 if ( ! get_site_option( 'ms_files_rewriting' ) ) {
1534 // If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
1535 // Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
1536 // prevents a four-digit ID from conflicting with a year-based directory for the main site.
1537 // But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
1538 // directory, as they never had wp-content/uploads for the main site.)
1540 if ( defined( 'MULTISITE' ) )
1541 $ms_dir = '/sites/' . get_current_blog_id();
1543 $ms_dir = '/' . get_current_blog_id();
1548 } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
1549 // Handle the old-form ms-files.php rewriting if the network still has that enabled.
1550 // When ms-files rewriting is enabled, then we only listen to UPLOADS when:
1551 // 1) we are not on the main site in a post-MU network,
1552 // as wp-content/uploads is used there, and
1553 // 2) we are not switched, as ms_upload_constants() hardcodes
1554 // these constants to reflect the original blog ID.
1556 // Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
1557 // (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
1558 // as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
1559 // rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
1561 if ( defined( 'BLOGUPLOADDIR' ) )
1562 $dir = untrailingslashit( BLOGUPLOADDIR );
1564 $dir = ABSPATH . UPLOADS;
1565 $url = trailingslashit( $siteurl ) . 'files';
1573 if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
1574 // Generate the yearly and monthly dirs
1576 $time = current_time( 'mysql' );
1577 $y = substr( $time, 0, 4 );
1578 $m = substr( $time, 5, 2 );
1585 $uploads = apply_filters( 'upload_dir',
1589 'subdir' => $subdir,
1590 'basedir' => $basedir,
1591 'baseurl' => $baseurl,
1595 // Make sure we have an uploads dir
1596 if ( ! wp_mkdir_p( $uploads['path'] ) ) {
1597 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
1598 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
1600 $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
1602 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
1603 $uploads['error'] = $message;
1610 * Get a filename that is sanitized and unique for the given directory.
1612 * If the filename is not unique, then a number will be added to the filename
1613 * before the extension, and will continue adding numbers until the filename is
1616 * The callback is passed three parameters, the first one is the directory, the
1617 * second is the filename, and the third is the extension.
1621 * @param string $dir
1622 * @param string $filename
1623 * @param mixed $unique_filename_callback Callback.
1624 * @return string New filename, if given wasn't unique.
1626 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
1627 // sanitize the file name before we begin processing
1628 $filename = sanitize_file_name($filename);
1630 // separate the filename into a name and extension
1631 $info = pathinfo($filename);
1632 $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
1633 $name = basename($filename, $ext);
1635 // edge case: if file is named '.ext', treat as an empty name
1636 if ( $name === $ext )
1639 // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
1640 if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
1641 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
1645 // change '.ext' to lower case
1646 if ( $ext && strtolower($ext) != $ext ) {
1647 $ext2 = strtolower($ext);
1648 $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
1650 // check for both lower and upper case extension or image sub-sizes may be overwritten
1651 while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
1652 $new_number = $number + 1;
1653 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
1654 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
1655 $number = $new_number;
1660 while ( file_exists( $dir . "/$filename" ) ) {
1661 if ( '' == "$number$ext" )
1662 $filename = $filename . ++$number . $ext;
1664 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
1672 * Create a file in the upload folder with given content.
1674 * If there is an error, then the key 'error' will exist with the error message.
1675 * If success, then the key 'file' will have the unique file path, the 'url' key
1676 * will have the link to the new file. and the 'error' key will be set to false.
1678 * This function will not move an uploaded file to the upload folder. It will
1679 * create a new file with the content in $bits parameter. If you move the upload
1680 * file, read the content of the uploaded file, and then you can give the
1681 * filename and content to this function, which will add it to the upload
1684 * The permissions will be set on the new file automatically by this function.
1688 * @param string $name
1689 * @param null $deprecated Never used. Set to null.
1690 * @param mixed $bits File content
1691 * @param string $time Optional. Time formatted in 'yyyy/mm'.
1694 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
1695 if ( !empty( $deprecated ) )
1696 _deprecated_argument( __FUNCTION__, '2.0' );
1698 if ( empty( $name ) )
1699 return array( 'error' => __( 'Empty filename' ) );
1701 $wp_filetype = wp_check_filetype( $name );
1702 if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
1703 return array( 'error' => __( 'Invalid file type' ) );
1705 $upload = wp_upload_dir( $time );
1707 if ( $upload['error'] !== false )
1710 $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
1711 if ( !is_array( $upload_bits_error ) ) {
1712 $upload[ 'error' ] = $upload_bits_error;
1716 $filename = wp_unique_filename( $upload['path'], $name );
1718 $new_file = $upload['path'] . "/$filename";
1719 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
1720 if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
1721 $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
1723 $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
1725 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
1726 return array( 'error' => $message );
1729 $ifp = @ fopen( $new_file, 'wb' );
1731 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
1733 @fwrite( $ifp, $bits );
1737 // Set correct file permissions
1738 $stat = @ stat( dirname( $new_file ) );
1739 $perms = $stat['mode'] & 0007777;
1740 $perms = $perms & 0000666;
1741 @ chmod( $new_file, $perms );
1745 $url = $upload['url'] . "/$filename";
1747 return array( 'file' => $new_file, 'url' => $url, 'error' => false );
1751 * Retrieve the file type based on the extension name.
1753 * @package WordPress
1755 * @uses apply_filters() Calls 'ext2type' hook on default supported types.
1757 * @param string $ext The extension to search.
1758 * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
1760 function wp_ext2type( $ext ) {
1761 $ext2type = apply_filters( 'ext2type', array(
1762 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
1763 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
1764 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
1765 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
1766 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
1767 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
1768 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
1769 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
1771 foreach ( $ext2type as $type => $exts )
1772 if ( in_array( $ext, $exts ) )
1777 * Retrieve the file type from the file name.
1779 * You can optionally define the mime array, if needed.
1783 * @param string $filename File name or path.
1784 * @param array $mimes Optional. Key is the file extension with value as the mime type.
1785 * @return array Values with extension first and mime type.
1787 function wp_check_filetype( $filename, $mimes = null ) {
1788 if ( empty($mimes) )
1789 $mimes = get_allowed_mime_types();
1793 foreach ( $mimes as $ext_preg => $mime_match ) {
1794 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1795 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
1796 $type = $mime_match;
1797 $ext = $ext_matches[1];
1802 return compact( 'ext', 'type' );
1806 * Attempt to determine the real file type of a file.
1807 * If unable to, the file name extension will be used to determine type.
1809 * If it's determined that the extension does not match the file's real type,
1810 * then the "proper_filename" value will be set with a proper filename and extension.
1812 * Currently this function only supports validating images known to getimagesize().
1816 * @param string $file Full path to the image.
1817 * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
1818 * @param array $mimes Optional. Key is the file extension with value as the mime type.
1819 * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
1821 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
1823 $proper_filename = false;
1825 // Do basic extension validation and MIME mapping
1826 $wp_filetype = wp_check_filetype( $filename, $mimes );
1827 extract( $wp_filetype );
1829 // We can't do any further validation without a file to work with
1830 if ( ! file_exists( $file ) )
1831 return compact( 'ext', 'type', 'proper_filename' );
1833 // We're able to validate images using GD
1834 if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
1836 // Attempt to figure out what type of image it actually is
1837 $imgstats = @getimagesize( $file );
1839 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
1840 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
1841 // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
1842 // You shouldn't need to use this filter, but it's here just in case
1843 $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
1844 'image/jpeg' => 'jpg',
1845 'image/png' => 'png',
1846 'image/gif' => 'gif',
1847 'image/bmp' => 'bmp',
1848 'image/tiff' => 'tif',
1851 // Replace whatever is after the last period in the filename with the correct extension
1852 if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
1853 $filename_parts = explode( '.', $filename );
1854 array_pop( $filename_parts );
1855 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
1856 $new_filename = implode( '.', $filename_parts );
1858 if ( $new_filename != $filename )
1859 $proper_filename = $new_filename; // Mark that it changed
1861 // Redefine the extension / MIME
1862 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
1863 extract( $wp_filetype );
1868 // Let plugins try and validate other types of files
1869 // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
1870 return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
1874 * Retrieve list of mime types and file extensions.
1878 * @uses apply_filters() Calls 'mime_types' on returned array. This filter should
1879 * be used to add types, not remove them. To remove types use the upload_mimes filter.
1881 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
1883 function wp_get_mime_types() {
1884 // Accepted MIME types are set here as PCRE unless provided.
1885 return apply_filters( 'mime_types', array(
1887 'jpg|jpeg|jpe' => 'image/jpeg',
1888 'gif' => 'image/gif',
1889 'png' => 'image/png',
1890 'bmp' => 'image/bmp',
1891 'tif|tiff' => 'image/tiff',
1892 'ico' => 'image/x-icon',
1894 'asf|asx|wax|wmv|wmx' => 'video/asf',
1895 'avi' => 'video/avi',
1896 'divx' => 'video/divx',
1897 'flv' => 'video/x-flv',
1898 'mov|qt' => 'video/quicktime',
1899 'mpeg|mpg|mpe' => 'video/mpeg',
1900 'mp4|m4v' => 'video/mp4',
1901 'ogv' => 'video/ogg',
1902 'mkv' => 'video/x-matroska',
1904 'txt|asc|c|cc|h' => 'text/plain',
1905 'csv' => 'text/csv',
1906 'tsv' => 'text/tab-separated-values',
1907 'ics' => 'text/calendar',
1908 'rtx' => 'text/richtext',
1909 'css' => 'text/css',
1910 'htm|html' => 'text/html',
1912 'mp3|m4a|m4b' => 'audio/mpeg',
1913 'ra|ram' => 'audio/x-realaudio',
1914 'wav' => 'audio/wav',
1915 'ogg|oga' => 'audio/ogg',
1916 'mid|midi' => 'audio/midi',
1917 'wma' => 'audio/wma',
1918 'mka' => 'audio/x-matroska',
1919 // Misc application formats
1920 'rtf' => 'application/rtf',
1921 'js' => 'application/javascript',
1922 'pdf' => 'application/pdf',
1923 'swf' => 'application/x-shockwave-flash',
1924 'class' => 'application/java',
1925 'tar' => 'application/x-tar',
1926 'zip' => 'application/zip',
1927 'gz|gzip' => 'application/x-gzip',
1928 'rar' => 'application/rar',
1929 '7z' => 'application/x-7z-compressed',
1930 'exe' => 'application/x-msdownload',
1931 // MS Office formats
1932 'doc' => 'application/msword',
1933 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
1934 'wri' => 'application/vnd.ms-write',
1935 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
1936 'mdb' => 'application/vnd.ms-access',
1937 'mpp' => 'application/vnd.ms-project',
1938 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1939 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
1940 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
1941 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
1942 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1943 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
1944 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
1945 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
1946 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
1947 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
1948 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
1949 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
1950 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
1951 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
1952 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
1953 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
1954 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
1955 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
1956 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
1957 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
1958 // OpenOffice formats
1959 'odt' => 'application/vnd.oasis.opendocument.text',
1960 'odp' => 'application/vnd.oasis.opendocument.presentation',
1961 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1962 'odg' => 'application/vnd.oasis.opendocument.graphics',
1963 'odc' => 'application/vnd.oasis.opendocument.chart',
1964 'odb' => 'application/vnd.oasis.opendocument.database',
1965 'odf' => 'application/vnd.oasis.opendocument.formula',
1966 // WordPerfect formats
1967 'wp|wpd' => 'application/wordperfect',
1971 * Retrieve list of allowed mime types and file extensions.
1975 * @uses apply_filters() Calls 'upload_mimes' on returned array
1976 * @uses wp_get_upload_mime_types() to fetch the list of mime types
1978 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
1980 function get_allowed_mime_types() {
1981 return apply_filters( 'upload_mimes', wp_get_mime_types() );
1985 * Display "Are You Sure" message to confirm the action being taken.
1987 * If the action has the nonce explain message, then it will be displayed along
1988 * with the "Are you sure?" message.
1990 * @package WordPress
1991 * @subpackage Security
1994 * @param string $action The nonce action.
1996 function wp_nonce_ays( $action ) {
1997 $title = __( 'WordPress Failure Notice' );
1998 if ( 'log-out' == $action ) {
1999 $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
2000 $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
2002 $html = __( 'Are you sure you want to do this?' );
2003 if ( wp_get_referer() )
2004 $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
2007 wp_die( $html, $title, array('response' => 403) );
2011 * Kill WordPress execution and display HTML message with error message.
2013 * This function complements the die() PHP function. The difference is that
2014 * HTML will be displayed to the user. It is recommended to use this function
2015 * only, when the execution should not continue any further. It is not
2016 * recommended to call this function very often and try to handle as many errors
2017 * as possible silently.
2021 * @param string $message Error message.
2022 * @param string $title Error title.
2023 * @param string|array $args Optional arguments to control behavior.
2025 function wp_die( $message = '', $title = '', $args = array() ) {
2026 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2027 $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
2028 elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2029 $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
2031 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
2033 call_user_func( $function, $message, $title, $args );
2037 * Kill WordPress execution and display HTML message with error message.
2039 * This is the default handler for wp_die if you want a custom one for your
2040 * site then you can overload using the wp_die_handler filter in wp_die
2045 * @param string $message Error message.
2046 * @param string $title Error title.
2047 * @param string|array $args Optional arguments to control behavior.
2049 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
2050 $defaults = array( 'response' => 500 );
2051 $r = wp_parse_args($args, $defaults);
2053 $have_gettext = function_exists('__');
2055 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
2056 if ( empty( $title ) ) {
2057 $error_data = $message->get_error_data();
2058 if ( is_array( $error_data ) && isset( $error_data['title'] ) )
2059 $title = $error_data['title'];
2061 $errors = $message->get_error_messages();
2062 switch ( count( $errors ) ) :
2067 $message = "<p>{$errors[0]}</p>";
2070 $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
2073 } elseif ( is_string( $message ) ) {
2074 $message = "<p>$message</p>";
2077 if ( isset( $r['back_link'] ) && $r['back_link'] ) {
2078 $back_text = $have_gettext? __('« Back') : '« Back';
2079 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
2082 if ( ! did_action( 'admin_head' ) ) :
2083 if ( !headers_sent() ) {
2084 status_header( $r['response'] );
2086 header( 'Content-Type: text/html; charset=utf-8' );
2089 if ( empty($title) )
2090 $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error';
2092 $text_direction = 'ltr';
2093 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
2094 $text_direction = 'rtl';
2095 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
2096 $text_direction = 'rtl';
2099 <!-- 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
2101 <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'"; ?>>
2103 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2104 <title><?php echo $title ?></title>
2105 <style type="text/css">
2107 background: #f9f9f9;
2112 font-family: sans-serif;
2115 -webkit-border-radius: 3px;
2117 border: 1px solid #dfdfdf;
2121 border-bottom: 1px solid #dadada;
2124 font: 24px Georgia, "Times New Roman", Times, serif;
2127 padding-bottom: 7px;
2135 margin: 25px 0 20px;
2138 font-family: Consolas, Monaco, monospace;
2141 margin-bottom: 10px;
2146 text-decoration: none;
2152 display: inline-block;
2153 text-decoration: none;
2158 padding: 0 10px 1px;
2161 border-style: solid;
2162 -webkit-border-radius: 3px;
2164 white-space: nowrap;
2165 -webkit-box-sizing: border-box;
2166 -moz-box-sizing: border-box;
2167 box-sizing: border-box;
2168 background: #f3f3f3;
2169 background-image: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#f4f4f4));
2170 background-image: -webkit-linear-gradient(top, #fefefe, #f4f4f4);
2171 background-image: -moz-linear-gradient(top, #fefefe, #f4f4f4);
2172 background-image: -o-linear-gradient(top, #fefefe, #f4f4f4);
2173 background-image: linear-gradient(to bottom, #fefefe, #f4f4f4);
2176 text-shadow: 0 1px 0 #fff;
2179 .button.button-large {
2187 background: #f3f3f3;
2188 background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f3f3f3));
2189 background-image: -webkit-linear-gradient(top, #fff, #f3f3f3);
2190 background-image: -moz-linear-gradient(top, #fff, #f3f3f3);
2191 background-image: -ms-linear-gradient(top, #fff, #f3f3f3);
2192 background-image: -o-linear-gradient(top, #fff, #f3f3f3);
2193 background-image: linear-gradient(to bottom, #fff, #f3f3f3);
2199 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2);
2200 box-shadow: 1px 1px 1px rgba(0,0,0,.2);
2206 background-image: -webkit-gradient(linear, left top, left bottom, from(#f4f4f4), to(#fefefe));
2207 background-image: -webkit-linear-gradient(top, #f4f4f4, #fefefe);
2208 background-image: -moz-linear-gradient(top, #f4f4f4, #fefefe);
2209 background-image: -ms-linear-gradient(top, #f4f4f4, #fefefe);
2210 background-image: -o-linear-gradient(top, #f4f4f4, #fefefe);
2211 background-image: linear-gradient(to bottom, #f4f4f4, #fefefe);
2214 text-shadow: 0 -1px 0 #fff;
2215 -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2216 box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2219 <?php if ( 'rtl' == $text_direction ) : ?>
2220 body { font-family: Tahoma, Arial; }
2224 <body id="error-page">
2225 <?php endif; // ! did_action( 'admin_head' ) ?>
2226 <?php echo $message; ?>
2234 * Kill WordPress execution and display XML message with error message.
2236 * This is the handler for wp_die when processing XMLRPC requests.
2241 * @param string $message Error message.
2242 * @param string $title Error title.
2243 * @param string|array $args Optional arguments to control behavior.
2245 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
2246 global $wp_xmlrpc_server;
2247 $defaults = array( 'response' => 500 );
2249 $r = wp_parse_args($args, $defaults);
2251 if ( $wp_xmlrpc_server ) {
2252 $error = new IXR_Error( $r['response'] , $message);
2253 $wp_xmlrpc_server->output( $error->getXml() );
2259 * Kill WordPress ajax execution.
2261 * This is the handler for wp_die when processing Ajax requests.
2266 * @param string $message Optional. Response to print.
2268 function _ajax_wp_die_handler( $message = '' ) {
2269 if ( is_scalar( $message ) )
2270 die( (string) $message );
2275 * Kill WordPress execution.
2277 * This is the handler for wp_die when processing APP requests.
2282 * @param string $message Optional. Response to print.
2284 function _scalar_wp_die_handler( $message = '' ) {
2285 if ( is_scalar( $message ) )
2286 die( (string) $message );
2291 * Send a JSON response back to an Ajax request.
2295 * @param mixed $response Variable (usually an array or object) to encode as JSON, then print and die.
2297 function wp_send_json( $response ) {
2298 @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
2299 echo json_encode( $response );
2300 if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2307 * Send a JSON response back to an Ajax request, indicating success.
2311 * @param mixed $data Data to encode as JSON, then print and die.
2313 function wp_send_json_success( $data = null ) {
2314 $response = array( 'success' => true );
2316 if ( isset( $data ) )
2317 $response['data'] = $data;
2319 wp_send_json( $response );
2323 * Send a JSON response back to an Ajax request, indicating failure.
2327 * @param mixed $data Data to encode as JSON, then print and die.
2329 function wp_send_json_error( $data = null ) {
2330 $response = array( 'success' => false );
2332 if ( isset( $data ) )
2333 $response['data'] = $data;
2335 wp_send_json( $response );
2339 * Retrieve the WordPress home page URL.
2341 * If the constant named 'WP_HOME' exists, then it will be used and returned by
2342 * the function. This can be used to counter the redirection on your local
2343 * development environment.
2346 * @package WordPress
2349 * @param string $url URL for the home location
2350 * @return string Homepage location.
2352 function _config_wp_home( $url = '' ) {
2353 if ( defined( 'WP_HOME' ) )
2354 return untrailingslashit( WP_HOME );
2359 * Retrieve the WordPress site URL.
2361 * If the constant named 'WP_SITEURL' is defined, then the value in that
2362 * constant will always be returned. This can be used for debugging a site on
2363 * your localhost while not having to change the database to your URL.
2366 * @package WordPress
2369 * @param string $url URL to set the WordPress site location.
2370 * @return string The WordPress Site URL
2372 function _config_wp_siteurl( $url = '' ) {
2373 if ( defined( 'WP_SITEURL' ) )
2374 return untrailingslashit( WP_SITEURL );
2379 * Set the localized direction for MCE plugin.
2381 * Will only set the direction to 'rtl', if the WordPress locale has the text
2382 * direction set to 'rtl'.
2384 * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
2385 * keys. These keys are then returned in the $input array.
2388 * @package WordPress
2392 * @param array $input MCE plugin array.
2393 * @return array Direction set for 'rtl', if needed by locale.
2395 function _mce_set_direction( $input ) {
2397 $input['directionality'] = 'rtl';
2398 $input['plugins'] .= ',directionality';
2399 $input['theme_advanced_buttons1'] .= ',ltr';
2406 * Convert smiley code to the icon graphic file equivalent.
2408 * You can turn off smilies, by going to the write setting screen and unchecking
2409 * the box, or by setting 'use_smilies' option to false or removing the option.
2411 * Plugins may override the default smiley list by setting the $wpsmiliestrans
2412 * to an array, with the key the code the blogger types in and the value the
2415 * The $wp_smiliessearch global is for the regular expression and is set each
2416 * time the function is called.
2418 * The full list of smilies can be found in the function and won't be listed in
2419 * the description. Probably should create a Codex page for it, so that it is
2422 * @global array $wpsmiliestrans
2423 * @global array $wp_smiliessearch
2426 function smilies_init() {
2427 global $wpsmiliestrans, $wp_smiliessearch;
2429 // don't bother setting up smilies if they are disabled
2430 if ( !get_option( 'use_smilies' ) )
2433 if ( !isset( $wpsmiliestrans ) ) {
2434 $wpsmiliestrans = array(
2435 ':mrgreen:' => 'icon_mrgreen.gif',
2436 ':neutral:' => 'icon_neutral.gif',
2437 ':twisted:' => 'icon_twisted.gif',
2438 ':arrow:' => 'icon_arrow.gif',
2439 ':shock:' => 'icon_eek.gif',
2440 ':smile:' => 'icon_smile.gif',
2441 ':???:' => 'icon_confused.gif',
2442 ':cool:' => 'icon_cool.gif',
2443 ':evil:' => 'icon_evil.gif',
2444 ':grin:' => 'icon_biggrin.gif',
2445 ':idea:' => 'icon_idea.gif',
2446 ':oops:' => 'icon_redface.gif',
2447 ':razz:' => 'icon_razz.gif',
2448 ':roll:' => 'icon_rolleyes.gif',
2449 ':wink:' => 'icon_wink.gif',
2450 ':cry:' => 'icon_cry.gif',
2451 ':eek:' => 'icon_surprised.gif',
2452 ':lol:' => 'icon_lol.gif',
2453 ':mad:' => 'icon_mad.gif',
2454 ':sad:' => 'icon_sad.gif',
2455 '8-)' => 'icon_cool.gif',
2456 '8-O' => 'icon_eek.gif',
2457 ':-(' => 'icon_sad.gif',
2458 ':-)' => 'icon_smile.gif',
2459 ':-?' => 'icon_confused.gif',
2460 ':-D' => 'icon_biggrin.gif',
2461 ':-P' => 'icon_razz.gif',
2462 ':-o' => 'icon_surprised.gif',
2463 ':-x' => 'icon_mad.gif',
2464 ':-|' => 'icon_neutral.gif',
2465 ';-)' => 'icon_wink.gif',
2466 // This one transformation breaks regular text with frequency.
2467 // '8)' => 'icon_cool.gif',
2468 '8O' => 'icon_eek.gif',
2469 ':(' => 'icon_sad.gif',
2470 ':)' => 'icon_smile.gif',
2471 ':?' => 'icon_confused.gif',
2472 ':D' => 'icon_biggrin.gif',
2473 ':P' => 'icon_razz.gif',
2474 ':o' => 'icon_surprised.gif',
2475 ':x' => 'icon_mad.gif',
2476 ':|' => 'icon_neutral.gif',
2477 ';)' => 'icon_wink.gif',
2478 ':!:' => 'icon_exclaim.gif',
2479 ':?:' => 'icon_question.gif',
2483 if (count($wpsmiliestrans) == 0) {
2488 * NOTE: we sort the smilies in reverse key order. This is to make sure
2489 * we match the longest possible smilie (:???: vs :?) as the regular
2490 * expression used below is first-match
2492 krsort($wpsmiliestrans);
2494 $wp_smiliessearch = '/(?:\s|^)';
2497 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
2498 $firstchar = substr($smiley, 0, 1);
2499 $rest = substr($smiley, 1);
2502 if ($firstchar != $subchar) {
2503 if ($subchar != '') {
2504 $wp_smiliessearch .= ')|(?:\s|^)';
2506 $subchar = $firstchar;
2507 $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
2509 $wp_smiliessearch .= '|';
2511 $wp_smiliessearch .= preg_quote($rest, '/');
2514 $wp_smiliessearch .= ')(?:\s|$)/m';
2518 * Merge user defined arguments into defaults array.
2520 * This function is used throughout WordPress to allow for both string or array
2521 * to be merged into another array.
2525 * @param string|array $args Value to merge with $defaults
2526 * @param array $defaults Array that serves as the defaults.
2527 * @return array Merged user defined values with defaults.
2529 function wp_parse_args( $args, $defaults = '' ) {
2530 if ( is_object( $args ) )
2531 $r = get_object_vars( $args );
2532 elseif ( is_array( $args ) )
2535 wp_parse_str( $args, $r );
2537 if ( is_array( $defaults ) )
2538 return array_merge( $defaults, $r );
2543 * Clean up an array, comma- or space-separated list of IDs.
2547 * @param array|string $list
2548 * @return array Sanitized array of IDs
2550 function wp_parse_id_list( $list ) {
2551 if ( !is_array($list) )
2552 $list = preg_split('/[\s,]+/', $list);
2554 return array_unique(array_map('absint', $list));
2558 * Extract a slice of an array, given a list of keys.
2562 * @param array $array The original array
2563 * @param array $keys The list of keys
2564 * @return array The array slice
2566 function wp_array_slice_assoc( $array, $keys ) {
2568 foreach ( $keys as $key )
2569 if ( isset( $array[ $key ] ) )
2570 $slice[ $key ] = $array[ $key ];
2576 * Filters a list of objects, based on a set of key => value arguments.
2580 * @param array $list An array of objects to filter
2581 * @param array $args An array of key => value arguments to match against each object
2582 * @param string $operator The logical operation to perform. 'or' means only one element
2583 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
2584 * @param bool|string $field A field from the object to place instead of the entire object
2585 * @return array A list of objects or object fields
2587 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
2588 if ( ! is_array( $list ) )
2591 $list = wp_list_filter( $list, $args, $operator );
2594 $list = wp_list_pluck( $list, $field );
2600 * Filters a list of objects, based on a set of key => value arguments.
2604 * @param array $list An array of objects to filter
2605 * @param array $args An array of key => value arguments to match against each object
2606 * @param string $operator The logical operation to perform:
2607 * 'AND' means all elements from the array must match;
2608 * 'OR' means only one element needs to match;
2609 * 'NOT' means no elements may match.
2610 * The default is 'AND'.
2613 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
2614 if ( ! is_array( $list ) )
2617 if ( empty( $args ) )
2620 $operator = strtoupper( $operator );
2621 $count = count( $args );
2622 $filtered = array();
2624 foreach ( $list as $key => $obj ) {
2625 $to_match = (array) $obj;
2628 foreach ( $args as $m_key => $m_value ) {
2629 if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
2633 if ( ( 'AND' == $operator && $matched == $count )
2634 || ( 'OR' == $operator && $matched > 0 )
2635 || ( 'NOT' == $operator && 0 == $matched ) ) {
2636 $filtered[$key] = $obj;
2644 * Pluck a certain field out of each object in a list.
2648 * @param array $list A list of objects or arrays
2649 * @param int|string $field A field from the object to place instead of the entire object
2652 function wp_list_pluck( $list, $field ) {
2653 foreach ( $list as $key => $value ) {
2654 if ( is_object( $value ) )
2655 $list[ $key ] = $value->$field;
2657 $list[ $key ] = $value[ $field ];
2664 * Determines if Widgets library should be loaded.
2666 * Checks to make sure that the widgets library hasn't already been loaded. If
2667 * it hasn't, then it will load the widgets library and run an action hook.
2670 * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
2672 function wp_maybe_load_widgets() {
2673 if ( ! apply_filters('load_default_widgets', true) )
2675 require_once( ABSPATH . WPINC . '/default-widgets.php' );
2676 add_action( '_admin_menu', 'wp_widgets_add_menu' );
2680 * Append the Widgets menu to the themes main menu.
2683 * @uses $submenu The administration submenu list.
2685 function wp_widgets_add_menu() {
2688 if ( ! current_theme_supports( 'widgets' ) )
2691 $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
2692 ksort( $submenu['themes.php'], SORT_NUMERIC );
2696 * Flush all output buffers for PHP 5.2.
2698 * Make sure all output buffers are flushed before our singletons our destroyed.
2702 function wp_ob_end_flush_all() {
2703 $levels = ob_get_level();
2704 for ($i=0; $i<$levels; $i++)
2709 * Load custom DB error or display WordPress DB error.
2711 * If a file exists in the wp-content directory named db-error.php, then it will
2712 * be loaded instead of displaying the WordPress DB error. If it is not found,
2713 * then the WordPress DB error will be displayed instead.
2715 * The WordPress DB error sets the HTTP status header to 500 to try to prevent
2716 * search engines from caching the message. Custom DB messages should do the
2719 * This function was backported to the the WordPress 2.3.2, but originally was
2720 * added in WordPress 2.5.0.
2725 function dead_db() {
2728 // Load custom DB error template, if present.
2729 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
2730 require_once( WP_CONTENT_DIR . '/db-error.php' );
2734 // If installing or in the admin, provide the verbose message.
2735 if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
2736 wp_die($wpdb->error);
2738 // Otherwise, be terse.
2739 status_header( 500 );
2741 header( 'Content-Type: text/html; charset=utf-8' );
2743 wp_load_translations_early();
2746 <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
2748 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2749 <title><?php _e( 'Database Error' ); ?></title>
2753 <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
2761 * Converts value to nonnegative integer.
2765 * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
2766 * @return int An nonnegative integer
2768 function absint( $maybeint ) {
2769 return abs( intval( $maybeint ) );
2773 * Determines if the blog can be accessed over SSL.
2775 * Determines if blog can be accessed over SSL by using cURL to access the site
2776 * using the https in the siteurl. Requires cURL extension to work correctly.
2780 * @param string $url
2781 * @return bool Whether SSL access is available
2783 function url_is_accessable_via_ssl($url)
2785 if ( in_array( 'curl', get_loaded_extensions() ) ) {
2786 $ssl = set_url_scheme( $url, 'https' );
2789 curl_setopt($ch, CURLOPT_URL, $ssl);
2790 curl_setopt($ch, CURLOPT_FAILONERROR, true);
2791 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2792 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
2793 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
2797 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2800 if ($status == 200 || $status == 401) {
2808 * Marks a function as deprecated and informs when it has been used.
2810 * There is a hook deprecated_function_run that will be called that can be used
2811 * to get the backtrace up to what file and function called the deprecated
2814 * The current behavior is to trigger a user error if WP_DEBUG is true.
2816 * This function is to be used in every function that is deprecated.
2818 * @package WordPress
2823 * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
2824 * and the version the function was deprecated in.
2825 * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
2826 * trigger or false to not trigger error.
2828 * @param string $function The function that was called
2829 * @param string $version The version of WordPress that deprecated the function
2830 * @param string $replacement Optional. The function that should have been called
2832 function _deprecated_function( $function, $version, $replacement = null ) {
2834 do_action( 'deprecated_function_run', $function, $replacement, $version );
2836 // Allow plugin to filter the output error trigger
2837 if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
2838 if ( ! is_null($replacement) )
2839 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
2841 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
2846 * Marks a file as deprecated and informs when it has been used.
2848 * There is a hook deprecated_file_included that will be called that can be used
2849 * to get the backtrace up to what file and function included the deprecated
2852 * The current behavior is to trigger a user error if WP_DEBUG is true.
2854 * This function is to be used in every file that is deprecated.
2856 * @package WordPress
2861 * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
2862 * the version in which the file was deprecated, and any message regarding the change.
2863 * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
2864 * trigger or false to not trigger error.
2866 * @param string $file The file that was included
2867 * @param string $version The version of WordPress that deprecated the file
2868 * @param string $replacement Optional. The file that should have been included based on ABSPATH
2869 * @param string $message Optional. A message regarding the change
2871 function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
2873 do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
2875 // Allow plugin to filter the output error trigger
2876 if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
2877 $message = empty( $message ) ? '' : ' ' . $message;
2878 if ( ! is_null( $replacement ) )
2879 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
2881 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
2885 * Marks a function argument as deprecated and informs when it has been used.
2887 * This function is to be used whenever a deprecated function argument is used.
2888 * Before this function is called, the argument must be checked for whether it was
2889 * used by comparing it to its default value or evaluating whether it is empty.
2892 * if ( !empty($deprecated) )
2893 * _deprecated_argument( __FUNCTION__, '3.0' );
2896 * There is a hook deprecated_argument_run that will be called that can be used
2897 * to get the backtrace up to what file and function used the deprecated
2900 * The current behavior is to trigger a user error if WP_DEBUG is true.
2902 * @package WordPress
2907 * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
2908 * and the version in which the argument was deprecated.
2909 * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
2910 * trigger or false to not trigger error.
2912 * @param string $function The function that was called
2913 * @param string $version The version of WordPress that deprecated the argument used
2914 * @param string $message Optional. A message regarding the change.
2916 function _deprecated_argument( $function, $version, $message = null ) {
2918 do_action( 'deprecated_argument_run', $function, $message, $version );
2920 // Allow plugin to filter the output error trigger
2921 if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
2922 if ( ! is_null( $message ) )
2923 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
2925 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 ) );
2930 * Marks something as being incorrectly called.
2932 * There is a hook doing_it_wrong_run that will be called that can be used
2933 * to get the backtrace up to what file and function called the deprecated
2936 * The current behavior is to trigger a user error if WP_DEBUG is true.
2938 * @package WordPress
2943 * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
2944 * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
2945 * trigger or false to not trigger error.
2947 * @param string $function The function that was called.
2948 * @param string $message A message explaining what has been done incorrectly.
2949 * @param string $version The version of WordPress where the message was added.
2951 function _doing_it_wrong( $function, $message, $version ) {
2953 do_action( 'doing_it_wrong_run', $function, $message, $version );
2955 // Allow plugin to filter the output error trigger
2956 if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
2957 $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
2958 $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
2959 trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
2964 * Is the server running earlier than 1.5.0 version of lighttpd?
2968 * @return bool Whether the server is running lighttpd < 1.5.0
2970 function is_lighttpd_before_150() {
2971 $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
2972 $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
2973 return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
2977 * Does the specified module exist in the Apache config?
2981 * @param string $mod e.g. mod_rewrite
2982 * @param bool $default The default return value if the module is not found
2985 function apache_mod_loaded($mod, $default = false) {
2991 if ( function_exists('apache_get_modules') ) {
2992 $mods = apache_get_modules();
2993 if ( in_array($mod, $mods) )
2995 } elseif ( function_exists('phpinfo') ) {
2998 $phpinfo = ob_get_clean();
2999 if ( false !== strpos($phpinfo, $mod) )
3006 * Check if IIS 7 supports pretty permalinks.
3012 function iis7_supports_permalinks() {
3015 $supports_permalinks = false;
3017 /* First we check if the DOMDocument class exists. If it does not exist,
3018 * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
3019 * hence we just bail out and tell user that pretty permalinks cannot be used.
3020 * This is not a big issue because PHP 4.X is going to be deprecated and for IIS it
3021 * is recommended to use PHP 5.X NTS.
3022 * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
3023 * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
3024 * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
3025 * via ISAPI then pretty permalinks will not work.
3027 $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
3030 return apply_filters('iis7_supports_permalinks', $supports_permalinks);
3034 * File validates against allowed set of defined rules.
3036 * A return value of '1' means that the $file contains either '..' or './'. A
3037 * return value of '2' means that the $file contains ':' after the first
3038 * character. A return value of '3' means that the file is not in the allowed
3043 * @param string $file File path.
3044 * @param array $allowed_files List of allowed files.
3045 * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
3047 function validate_file( $file, $allowed_files = '' ) {
3048 if ( false !== strpos( $file, '..' ) )
3051 if ( false !== strpos( $file, './' ) )
3054 if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
3057 if (':' == substr( $file, 1, 1 ) )
3064 * Determine if SSL is used.
3068 * @return bool True if SSL, false if not used.
3071 if ( isset($_SERVER['HTTPS']) ) {
3072 if ( 'on' == strtolower($_SERVER['HTTPS']) )
3074 if ( '1' == $_SERVER['HTTPS'] )
3076 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
3083 * Whether SSL login should be forced.
3087 * @param string|bool $force Optional.
3088 * @return bool True if forced, false if not forced.
3090 function force_ssl_login( $force = null ) {
3091 static $forced = false;
3093 if ( !is_null( $force ) ) {
3094 $old_forced = $forced;
3103 * Whether to force SSL used for the Administration Screens.
3107 * @param string|bool $force
3108 * @return bool True if forced, false if not forced.
3110 function force_ssl_admin( $force = null ) {
3111 static $forced = false;
3113 if ( !is_null( $force ) ) {
3114 $old_forced = $forced;
3123 * Guess the URL for the site.
3125 * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
3132 function wp_guess_url() {
3133 if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
3136 $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
3137 $url = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
3140 return rtrim($url, '/');
3144 * Temporarily suspend cache additions.
3146 * Stops more data being added to the cache, but still allows cache retrieval.
3147 * This is useful for actions, such as imports, when a lot of data would otherwise
3148 * be almost uselessly added to the cache.
3150 * Suspension lasts for a single page load at most. Remember to call this
3151 * function again if you wish to re-enable cache adds earlier.
3155 * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
3156 * @return bool The current suspend setting
3158 function wp_suspend_cache_addition( $suspend = null ) {
3159 static $_suspend = false;
3161 if ( is_bool( $suspend ) )
3162 $_suspend = $suspend;
3168 * Suspend cache invalidation.
3170 * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
3171 * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
3172 * cache when invalidation is suspended.
3176 * @param bool $suspend Whether to suspend or enable cache invalidation
3177 * @return bool The current suspend setting
3179 function wp_suspend_cache_invalidation($suspend = true) {
3180 global $_wp_suspend_cache_invalidation;
3182 $current_suspend = $_wp_suspend_cache_invalidation;
3183 $_wp_suspend_cache_invalidation = $suspend;
3184 return $current_suspend;
3192 * @package WordPress
3194 * @param int $blog_id optional blog id to test (default current blog)
3195 * @return bool True if not multisite or $blog_id is main site
3197 function is_main_site( $blog_id = '' ) {
3198 global $current_site;
3200 if ( ! is_multisite() )
3204 $blog_id = get_current_blog_id();
3206 return $blog_id == $current_site->blog_id;
3210 * Whether global terms are enabled.
3214 * @package WordPress
3216 * @return bool True if multisite and global terms enabled
3218 function global_terms_enabled() {
3219 if ( ! is_multisite() )
3222 static $global_terms = null;
3223 if ( is_null( $global_terms ) ) {
3224 $filter = apply_filters( 'global_terms_enabled', null );
3225 if ( ! is_null( $filter ) )
3226 $global_terms = (bool) $filter;
3228 $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
3230 return $global_terms;
3234 * gmt_offset modification for smart timezone handling.
3236 * Overrides the gmt_offset option if we have a timezone_string available.
3240 * @return float|bool
3242 function wp_timezone_override_offset() {
3243 if ( !$timezone_string = get_option( 'timezone_string' ) ) {
3247 $timezone_object = timezone_open( $timezone_string );
3248 $datetime_object = date_create();
3249 if ( false === $timezone_object || false === $datetime_object ) {
3252 return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
3256 * {@internal Missing Short Description}}
3260 * @param unknown_type $a
3261 * @param unknown_type $b
3264 function _wp_timezone_choice_usort_callback( $a, $b ) {
3265 // Don't use translated versions of Etc
3266 if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
3267 // Make the order of these more like the old dropdown
3268 if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3269 return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
3271 if ( 'UTC' === $a['city'] ) {
3272 if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
3277 if ( 'UTC' === $b['city'] ) {
3278 if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
3283 return strnatcasecmp( $a['city'], $b['city'] );
3285 if ( $a['t_continent'] == $b['t_continent'] ) {
3286 if ( $a['t_city'] == $b['t_city'] ) {
3287 return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
3289 return strnatcasecmp( $a['t_city'], $b['t_city'] );
3291 // Force Etc to the bottom of the list
3292 if ( 'Etc' === $a['continent'] ) {
3295 if ( 'Etc' === $b['continent'] ) {
3298 return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
3303 * Gives a nicely formatted list of timezone strings. // temporary! Not in final
3307 * @param string $selected_zone Selected Zone
3310 function wp_timezone_choice( $selected_zone ) {
3311 static $mo_loaded = false;
3313 $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
3315 // Load translations for continents and cities
3316 if ( !$mo_loaded ) {
3317 $locale = get_locale();
3318 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
3319 load_textdomain( 'continents-cities', $mofile );
3324 foreach ( timezone_identifiers_list() as $zone ) {
3325 $zone = explode( '/', $zone );
3326 if ( !in_array( $zone[0], $continents ) ) {
3330 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
3332 0 => ( isset( $zone[0] ) && $zone[0] ),
3333 1 => ( isset( $zone[1] ) && $zone[1] ),
3334 2 => ( isset( $zone[2] ) && $zone[2] ),
3336 $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
3337 $exists[4] = ( $exists[1] && $exists[3] );
3338 $exists[5] = ( $exists[2] && $exists[3] );
3341 'continent' => ( $exists[0] ? $zone[0] : '' ),
3342 'city' => ( $exists[1] ? $zone[1] : '' ),
3343 'subcity' => ( $exists[2] ? $zone[2] : '' ),
3344 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
3345 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
3346 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
3349 usort( $zonen, '_wp_timezone_choice_usort_callback' );
3351 $structure = array();
3353 if ( empty( $selected_zone ) ) {
3354 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
3357 foreach ( $zonen as $key => $zone ) {
3358 // Build value in an array to join later
3359 $value = array( $zone['continent'] );
3361 if ( empty( $zone['city'] ) ) {
3362 // It's at the continent level (generally won't happen)
3363 $display = $zone['t_continent'];
3365 // It's inside a continent group
3367 // Continent optgroup
3368 if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
3369 $label = $zone['t_continent'];
3370 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
3373 // Add the city to the value
3374 $value[] = $zone['city'];
3376 $display = $zone['t_city'];
3377 if ( !empty( $zone['subcity'] ) ) {
3378 // Add the subcity to the value
3379 $value[] = $zone['subcity'];
3380 $display .= ' - ' . $zone['t_subcity'];
3385 $value = join( '/', $value );
3387 if ( $value === $selected_zone ) {
3388 $selected = 'selected="selected" ';
3390 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
3392 // Close continent optgroup
3393 if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
3394 $structure[] = '</optgroup>';
3399 $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
3401 if ( 'UTC' === $selected_zone )
3402 $selected = 'selected="selected" ';
3403 $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
3404 $structure[] = '</optgroup>';
3406 // Do manual UTC offsets
3407 $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
3408 $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,
3409 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);
3410 foreach ( $offset_range as $offset ) {
3412 $offset_name = '+' . $offset;
3414 $offset_name = (string) $offset;
3416 $offset_value = $offset_name;
3417 $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
3418 $offset_name = 'UTC' . $offset_name;
3419 $offset_value = 'UTC' . $offset_value;
3421 if ( $offset_value === $selected_zone )
3422 $selected = 'selected="selected" ';
3423 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
3426 $structure[] = '</optgroup>';
3428 return join( "\n", $structure );
3432 * Strip close comment and close php tags from file headers used by WP.
3433 * See http://core.trac.wordpress.org/ticket/8497
3437 * @param string $str
3440 function _cleanup_header_comment($str) {
3441 return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
3445 * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
3449 function wp_scheduled_delete() {
3452 $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
3454 $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);
3456 foreach ( (array) $posts_to_delete as $post ) {
3457 $post_id = (int) $post['post_id'];
3461 $del_post = get_post($post_id);
3463 if ( !$del_post || 'trash' != $del_post->post_status ) {
3464 delete_post_meta($post_id, '_wp_trash_meta_status');
3465 delete_post_meta($post_id, '_wp_trash_meta_time');
3467 wp_delete_post($post_id);
3471 $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);
3473 foreach ( (array) $comments_to_delete as $comment ) {
3474 $comment_id = (int) $comment['comment_id'];
3478 $del_comment = get_comment($comment_id);
3480 if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
3481 delete_comment_meta($comment_id, '_wp_trash_meta_time');
3482 delete_comment_meta($comment_id, '_wp_trash_meta_status');
3484 wp_delete_comment($comment_id);
3490 * Retrieve metadata from a file.
3492 * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
3493 * Each piece of metadata must be on its own line. Fields can not span multiple
3494 * lines, the value will get cut at the end of the first line.
3496 * If the file data is not within that first 8kiB, then the author should correct
3497 * their plugin file and move the data headers to the top.
3499 * @see http://codex.wordpress.org/File_Header
3502 * @param string $file Path to the file
3503 * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
3504 * @param string $context If specified adds filter hook "extra_{$context}_headers"
3506 function get_file_data( $file, $default_headers, $context = '' ) {
3507 // We don't need to write to the file, so just open for reading.
3508 $fp = fopen( $file, 'r' );
3510 // Pull only the first 8kiB of the file in.
3511 $file_data = fread( $fp, 8192 );
3513 // PHP will close file handle, but we are good citizens.
3516 // Make sure we catch CR-only line endings.
3517 $file_data = str_replace( "\r", "\n", $file_data );
3519 if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
3520 $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
3521 $all_headers = array_merge( $extra_headers, (array) $default_headers );
3523 $all_headers = $default_headers;
3526 foreach ( $all_headers as $field => $regex ) {
3527 if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
3528 $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
3530 $all_headers[ $field ] = '';
3533 return $all_headers;
3537 * Used internally to tidy up the search terms.
3545 function _search_terms_tidy($t) {
3546 return trim($t, "\"'\n\r ");
3552 * Useful for returning true to filters easily.
3555 * @see __return_false()
3558 function __return_true() {
3565 * Useful for returning false to filters easily.
3568 * @see __return_true()
3569 * @return bool false
3571 function __return_false() {
3578 * Useful for returning 0 to filters easily.
3581 * @see __return_zero()
3584 function __return_zero() {
3589 * Returns an empty array.
3591 * Useful for returning an empty array to filters easily.
3594 * @see __return_zero()
3595 * @return array Empty array
3597 function __return_empty_array() {
3604 * Useful for returning null to filters easily.
3609 function __return_null() {
3614 * Send a HTTP header to disable content type sniffing in browsers which support it.
3616 * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
3617 * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
3622 function send_nosniff_header() {
3623 @header( 'X-Content-Type-Options: nosniff' );
3627 * Returns a MySQL expression for selecting the week number based on the start_of_week option.
3631 * @param string $column
3634 function _wp_mysql_week( $column ) {
3635 switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
3638 return "WEEK( $column, 0 )";
3640 return "WEEK( $column, 1 )";
3646 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
3651 * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
3656 * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
3657 * @param int $start The ID to start the loop check at
3658 * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
3659 * @param array $callback_args optional additional arguments to send to $callback
3660 * @return array IDs of all members of loop
3662 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
3663 $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
3665 if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
3668 return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
3672 * Uses the "The Tortoise and the Hare" algorithm to detect loops.
3674 * For every step of the algorithm, the hare takes two steps and the tortoise one.
3675 * If the hare ever laps the tortoise, there must be a loop.
3680 * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
3681 * @param int $start The ID to start the loop check at
3682 * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
3683 * @param array $callback_args optional additional arguments to send to $callback
3684 * @param bool $_return_loop Return loop members or just detect presence of loop?
3685 * Only set to true if you already know the given $start is part of a loop
3686 * (otherwise the returned array might include branches)
3687 * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
3689 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
3690 $tortoise = $hare = $evanescent_hare = $start;
3693 // Set evanescent_hare to one past hare
3694 // Increment hare two steps
3698 ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
3700 ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
3702 if ( $_return_loop )
3703 $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
3705 // tortoise got lapped - must be a loop
3706 if ( $tortoise == $evanescent_hare || $tortoise == $hare )
3707 return $_return_loop ? $return : $tortoise;
3709 // Increment tortoise by one step
3710 $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
3717 * Send a HTTP header to limit rendering of pages to same origin iframes.
3719 * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
3724 function send_frame_options_header() {
3725 @header( 'X-Frame-Options: SAMEORIGIN' );
3729 * Retrieve a list of protocols to allow in HTML attributes.
3735 * @return array Array of allowed protocols
3737 function wp_allowed_protocols() {
3740 if ( empty( $protocols ) ) {
3741 $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
3742 $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
3749 * Return a comma separated string of functions that have been called to get to the current point in code.
3751 * @link http://core.trac.wordpress.org/ticket/19589
3754 * @param string $ignore_class A class to ignore all function calls within - useful when you want to just give info about the callee
3755 * @param int $skip_frames A number of stack frames to skip - useful for unwinding back to the source of the issue
3756 * @param bool $pretty Whether or not you want a comma separated string or raw array returned
3757 * @return string|array Either a string containing a reversed comma separated trace or an array of individual calls.
3759 function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
3760 if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
3761 $trace = debug_backtrace( false );
3763 $trace = debug_backtrace();
3766 $check_class = ! is_null( $ignore_class );
3767 $skip_frames++; // skip this function
3769 foreach ( $trace as $call ) {
3770 if ( $skip_frames > 0 ) {
3772 } elseif ( isset( $call['class'] ) ) {
3773 if ( $check_class && $ignore_class == $call['class'] )
3774 continue; // Filter out calls
3776 $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
3778 if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
3779 $caller[] = "{$call['function']}('{$call['args'][0]}')";
3780 } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
3781 $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
3783 $caller[] = $call['function'];
3788 return join( ', ', array_reverse( $caller ) );
3794 * Retrieve ids that are not already present in the cache
3798 * @param array $object_ids ID list
3799 * @param string $cache_key The cache bucket to check against
3803 function _get_non_cached_ids( $object_ids, $cache_key ) {
3805 foreach ( $object_ids as $id ) {
3807 if ( !wp_cache_get( $id, $cache_key ) ) {
3816 * Test if the current device has the capability to upload files.
3821 * @return bool true|false
3823 function _device_can_upload() {
3824 if ( ! wp_is_mobile() )
3827 $ua = $_SERVER['HTTP_USER_AGENT'];
3829 if ( strpos($ua, 'iPhone') !== false
3830 || strpos($ua, 'iPad') !== false
3831 || strpos($ua, 'iPod') !== false ) {
3832 return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
3839 * Test if a given path is a stream URL
3841 * @param string $path The resource path or URL
3842 * @return bool True if the path is a stream URL
3844 function wp_is_stream( $path ) {
3845 $wrappers = stream_get_wrappers();
3846 $wrappers_re = '(' . join('|', $wrappers) . ')';
3848 return preg_match( "!^$wrappers_re://!", $path ) === 1;
3852 * Test if the supplied date is valid for the Gregorian calendar
3856 * @return bool true|false
3858 function wp_checkdate( $month, $day, $year, $source_date ) {
3859 return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );