8 require( ABSPATH . WPINC . '/option.php' );
11 * Convert 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 true.
24 * @return string|int|bool Formatted date string or Unix timestamp. False if $date is empty.
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.
49 * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
51 * If $gmt is set to either '1' or 'true', then both types will use GMT time.
52 * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
56 * @param string $type Type of time to retrieve. Accepts 'mysql', 'timestamp', or PHP date
57 * format string (e.g. 'Y-m-d').
58 * @param int|bool $gmt Optional. Whether to use GMT timezone. Default false.
59 * @return int|string Integer if $type is 'timestamp', string otherwise.
61 function current_time( $type, $gmt = 0 ) {
64 return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
66 return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
68 return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
73 * Retrieve the date in localized format, based on timestamp.
75 * If the locale specifies the locale month and weekday, then the locale will
76 * take over the format for the date. If it isn't, then the date format string
77 * will be used instead.
81 * @global WP_Locale $wp_locale
83 * @param string $dateformatstring Format to display the date.
84 * @param bool|int $unixtimestamp Optional. Unix timestamp. Default false.
85 * @param bool $gmt Optional. Whether to use GMT timezone. Default false.
87 * @return string The date, translated if locale specifies it.
89 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
94 $i = current_time( 'timestamp', $gmt );
98 * Store original value for language with untypical grammars.
99 * See https://core.trac.wordpress.org/ticket/9396
101 $req_format = $dateformatstring;
103 if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
104 $datemonth = $wp_locale->get_month( date( 'm', $i ) );
105 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
106 $dateweekday = $wp_locale->get_weekday( date( 'w', $i ) );
107 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
108 $datemeridiem = $wp_locale->get_meridiem( date( 'a', $i ) );
109 $datemeridiem_capital = $wp_locale->get_meridiem( date( 'A', $i ) );
110 $dateformatstring = ' '.$dateformatstring;
111 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
112 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
113 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
114 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
115 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
116 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
118 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
120 $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
121 $timezone_formats_re = implode( '|', $timezone_formats );
122 if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
123 $timezone_string = get_option( 'timezone_string' );
124 if ( $timezone_string ) {
125 $timezone_object = timezone_open( $timezone_string );
126 $date_object = date_create( null, $timezone_object );
127 foreach ( $timezone_formats as $timezone_format ) {
128 if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
129 $formatted = date_format( $date_object, $timezone_format );
130 $dateformatstring = ' '.$dateformatstring;
131 $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
132 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
137 $j = @date( $dateformatstring, $i );
140 * Filters the date formatted based on the locale.
144 * @param string $j Formatted date string.
145 * @param string $req_format Format to display the date.
146 * @param int $i Unix timestamp.
147 * @param bool $gmt Whether to convert to GMT for time. Default false.
149 $j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
154 * Determines if the date should be declined.
156 * If the locale specifies that month names require a genitive case in certain
157 * formats (like 'j F Y'), the month name will be replaced with a correct form.
161 * @param string $date Formatted date string.
162 * @return string The date, declined if locale specifies it.
164 function wp_maybe_decline_date( $date ) {
167 // i18n functions are not available in SHORTINIT mode
168 if ( ! function_exists( '_x' ) ) {
172 /* translators: If months in your language require a genitive case,
173 * translate this to 'on'. Do not translate into your own language.
175 if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
176 // Match a format like 'j F Y' or 'j. F'
177 if ( @preg_match( '#^\d{1,2}\.? [^\d ]+#u', $date ) ) {
178 $months = $wp_locale->month;
179 $months_genitive = $wp_locale->month_genitive;
181 foreach ( $months as $key => $month ) {
182 $months[ $key ] = '# ' . $month . '( |$)#u';
185 foreach ( $months_genitive as $key => $month ) {
186 $months_genitive[ $key ] = ' ' . $month . '$1';
189 $date = preg_replace( $months, $months_genitive, $date );
193 // Used for locale-specific rules
194 $locale = get_locale();
196 if ( 'ca' === $locale ) {
197 // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..."
198 $date = preg_replace( '# de ([ao])#i', " d'\\1", $date );
205 * Convert float number to format based on the locale.
209 * @global WP_Locale $wp_locale
211 * @param float $number The number to convert based on locale.
212 * @param int $decimals Optional. Precision of the number of decimal places. Default 0.
213 * @return string Converted number in string format.
215 function number_format_i18n( $number, $decimals = 0 ) {
218 if ( isset( $wp_locale ) ) {
219 $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
221 $formatted = number_format( $number, absint( $decimals ) );
225 * Filters the number formatted based on the locale.
229 * @param string $formatted Converted number in string format.
231 return apply_filters( 'number_format_i18n', $formatted );
235 * Convert number of bytes largest unit bytes will fit into.
237 * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts
238 * number of bytes to human readable number by taking the number of that unit
239 * that the bytes will go into it. Supports TB value.
241 * Please note that integers in PHP are limited to 32 bits, unless they are on
242 * 64 bit architecture, then they have 64 bit size. If you need to place the
243 * larger size then what PHP integer type will hold, then use a string. It will
244 * be converted to a double, which should always have 64 bit length.
246 * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
250 * @param int|string $bytes Number of bytes. Note max integer size for integers.
251 * @param int $decimals Optional. Precision of number of decimal places. Default 0.
252 * @return string|false False on failure. Number string on success.
254 function size_format( $bytes, $decimals = 0 ) {
263 if ( 0 === $bytes ) {
264 return number_format_i18n( 0, $decimals ) . ' B';
267 foreach ( $quant as $unit => $mag ) {
268 if ( doubleval( $bytes ) >= $mag ) {
269 return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
277 * Get the week start and end from the datetime or date string from MySQL.
281 * @param string $mysqlstring Date or datetime field type from MySQL.
282 * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
283 * @return array Keys are 'start' and 'end'.
285 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
286 // MySQL string year.
287 $my = substr( $mysqlstring, 0, 4 );
289 // MySQL string month.
290 $mm = substr( $mysqlstring, 8, 2 );
293 $md = substr( $mysqlstring, 5, 2 );
295 // The timestamp for MySQL string day.
296 $day = mktime( 0, 0, 0, $md, $mm, $my );
298 // The day of the week from the timestamp.
299 $weekday = date( 'w', $day );
301 if ( !is_numeric($start_of_week) )
302 $start_of_week = get_option( 'start_of_week' );
304 if ( $weekday < $start_of_week )
307 // The most recent week start day on or before $day.
308 $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
310 // $start + 1 week - 1 second.
311 $end = $start + WEEK_IN_SECONDS - 1;
312 return compact( 'start', 'end' );
316 * Unserialize value only if it was serialized.
320 * @param string $original Maybe unserialized original, if is needed.
321 * @return mixed Unserialized data can be any type.
323 function maybe_unserialize( $original ) {
324 if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
325 return @unserialize( $original );
330 * Check value to find if it was serialized.
332 * If $data is not an string, then returned value will always be false.
333 * Serialized data is always a string.
337 * @param string $data Value to check to see if was serialized.
338 * @param bool $strict Optional. Whether to be strict about the end of the string. Default true.
339 * @return bool False if not serialized and true if it was.
341 function is_serialized( $data, $strict = true ) {
342 // if it isn't a string, it isn't serialized.
343 if ( ! is_string( $data ) ) {
346 $data = trim( $data );
347 if ( 'N;' == $data ) {
350 if ( strlen( $data ) < 4 ) {
353 if ( ':' !== $data[1] ) {
357 $lastc = substr( $data, -1 );
358 if ( ';' !== $lastc && '}' !== $lastc ) {
362 $semicolon = strpos( $data, ';' );
363 $brace = strpos( $data, '}' );
364 // Either ; or } must exist.
365 if ( false === $semicolon && false === $brace )
367 // But neither must be in the first X characters.
368 if ( false !== $semicolon && $semicolon < 3 )
370 if ( false !== $brace && $brace < 4 )
377 if ( '"' !== substr( $data, -2, 1 ) ) {
380 } elseif ( false === strpos( $data, '"' ) ) {
383 // or else fall through
386 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
390 $end = $strict ? '$' : '';
391 return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
397 * Check whether serialized data is of string type.
401 * @param string $data Serialized data.
402 * @return bool False if not a serialized string, true if it is.
404 function is_serialized_string( $data ) {
405 // if it isn't a string, it isn't a serialized string.
406 if ( ! is_string( $data ) ) {
409 $data = trim( $data );
410 if ( strlen( $data ) < 4 ) {
412 } elseif ( ':' !== $data[1] ) {
414 } elseif ( ';' !== substr( $data, -1 ) ) {
416 } elseif ( $data[0] !== 's' ) {
418 } elseif ( '"' !== substr( $data, -2, 1 ) ) {
426 * Serialize data, if needed.
430 * @param string|array|object $data Data that might be serialized.
431 * @return mixed A scalar data
433 function maybe_serialize( $data ) {
434 if ( is_array( $data ) || is_object( $data ) )
435 return serialize( $data );
437 // Double serialization is required for backward compatibility.
438 // See https://core.trac.wordpress.org/ticket/12930
439 // Also the world will end. See WP 3.6.1.
440 if ( is_serialized( $data, false ) )
441 return serialize( $data );
447 * Retrieve post title from XMLRPC XML.
449 * If the title element is not part of the XML, then the default post title from
450 * the $post_default_title will be used instead.
454 * @global string $post_default_title Default XML-RPC post title.
456 * @param string $content XMLRPC XML Request content
457 * @return string Post title
459 function xmlrpc_getposttitle( $content ) {
460 global $post_default_title;
461 if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
462 $post_title = $matchtitle[1];
464 $post_title = $post_default_title;
470 * Retrieve the post category or categories from XMLRPC XML.
472 * If the category element is not found, then the default post category will be
473 * used. The return type then would be what $post_default_category. If the
474 * category is found, then it will always be an array.
478 * @global string $post_default_category Default XML-RPC post category.
480 * @param string $content XMLRPC XML Request content
481 * @return string|array List of categories or category name.
483 function xmlrpc_getpostcategory( $content ) {
484 global $post_default_category;
485 if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
486 $post_category = trim( $matchcat[1], ',' );
487 $post_category = explode( ',', $post_category );
489 $post_category = $post_default_category;
491 return $post_category;
495 * XMLRPC XML content without title and category elements.
499 * @param string $content XML-RPC XML Request content.
500 * @return string XMLRPC XML Request content without title and category elements.
502 function xmlrpc_removepostdata( $content ) {
503 $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
504 $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
505 $content = trim( $content );
510 * Use RegEx to extract URLs from arbitrary content.
514 * @param string $content Content to extract URLs from.
515 * @return array URLs found in passed string.
517 function wp_extract_urls( $content ) {
520 . "(?:([\w-]+:)?//?)"
526 . "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
535 $post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
537 return array_values( $post_links );
541 * Check content for video and audio links to add as enclosures.
543 * Will not add enclosures that have already been added and will
544 * remove enclosures that are no longer in the post. This is called as
545 * pingbacks and trackbacks.
549 * @global wpdb $wpdb WordPress database abstraction object.
551 * @param string $content Post Content.
552 * @param int $post_ID Post ID.
554 function do_enclose( $content, $post_ID ) {
557 //TODO: Tidy this ghetto code up and make the debug code optional
558 include_once( ABSPATH . WPINC . '/class-IXR.php' );
560 $post_links = array();
562 $pung = get_enclosed( $post_ID );
564 $post_links_temp = wp_extract_urls( $content );
566 foreach ( $pung as $link_test ) {
567 if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
568 $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, $wpdb->esc_like( $link_test ) . '%') );
569 foreach ( $mids as $mid )
570 delete_metadata_by_mid( 'post', $mid );
574 foreach ( (array) $post_links_temp as $link_test ) {
575 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
576 $test = @parse_url( $link_test );
577 if ( false === $test )
579 if ( isset( $test['query'] ) )
580 $post_links[] = $link_test;
581 elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
582 $post_links[] = $link_test;
587 * Filters the list of enclosure links before querying the database.
589 * Allows for the addition and/or removal of potential enclosures to save
590 * to postmeta before checking the database for existing enclosures.
594 * @param array $post_links An array of enclosure links.
595 * @param int $post_ID Post ID.
597 $post_links = apply_filters( 'enclosure_links', $post_links, $post_ID );
599 foreach ( (array) $post_links as $url ) {
600 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, $wpdb->esc_like( $url ) . '%' ) ) ) {
602 if ( $headers = wp_get_http_headers( $url) ) {
603 $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
604 $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
605 $allowed_types = array( 'video', 'audio' );
607 // Check to see if we can figure out the mime type from
609 $url_parts = @parse_url( $url );
610 if ( false !== $url_parts ) {
611 $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
612 if ( !empty( $extension ) ) {
613 foreach ( wp_get_mime_types() as $exts => $mime ) {
614 if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
622 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
623 add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
631 * Retrieve HTTP Headers from URL.
635 * @param string $url URL to retrieve HTTP headers from.
636 * @param bool $deprecated Not Used.
637 * @return bool|string False on failure, headers on success.
639 function wp_get_http_headers( $url, $deprecated = false ) {
640 if ( !empty( $deprecated ) )
641 _deprecated_argument( __FUNCTION__, '2.7.0' );
643 $response = wp_safe_remote_head( $url );
645 if ( is_wp_error( $response ) )
648 return wp_remote_retrieve_headers( $response );
652 * Whether the publish date of the current post in the loop is different from the
653 * publish date of the previous post in the loop.
657 * @global string $currentday The day of the current post in the loop.
658 * @global string $previousday The day of the previous post in the loop.
660 * @return int 1 when new day, 0 if not a new day.
662 function is_new_day() {
663 global $currentday, $previousday;
664 if ( $currentday != $previousday )
671 * Build URL query based on an associative and, or indexed array.
673 * This is a convenient function for easily building url queries. It sets the
674 * separator to '&' and uses _http_build_query() function.
678 * @see _http_build_query() Used to build the query
679 * @link https://secure.php.net/manual/en/function.http-build-query.php for more on what
680 * http_build_query() does.
682 * @param array $data URL-encode key/value pairs.
683 * @return string URL-encoded string.
685 function build_query( $data ) {
686 return _http_build_query( $data, null, '&', '', false );
690 * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
695 * @see https://secure.php.net/manual/en/function.http-build-query.php
697 * @param array|object $data An array or object of data. Converted to array.
698 * @param string $prefix Optional. Numeric index. If set, start parameter numbering with it.
700 * @param string $sep Optional. Argument separator; defaults to 'arg_separator.output'.
702 * @param string $key Optional. Used to prefix key name. Default empty.
703 * @param bool $urlencode Optional. Whether to use urlencode() in the result. Default true.
705 * @return string The query string.
707 function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
710 foreach ( (array) $data as $k => $v ) {
713 if ( is_int($k) && $prefix != null )
716 $k = $key . '%5B' . $k . '%5D';
719 elseif ( $v === false )
722 if ( is_array($v) || is_object($v) )
723 array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
724 elseif ( $urlencode )
725 array_push($ret, $k.'='.urlencode($v));
727 array_push($ret, $k.'='.$v);
731 $sep = ini_get('arg_separator.output');
733 return implode($sep, $ret);
737 * Retrieves a modified URL query string.
739 * You can rebuild the URL and append query variables to the URL query by using this function.
740 * There are two ways to use this function; either a single key and value, or an associative array.
742 * Using a single key and value:
744 * add_query_arg( 'key', 'value', 'http://example.com' );
746 * Using an associative array:
748 * add_query_arg( array(
749 * 'key1' => 'value1',
750 * 'key2' => 'value2',
751 * ), 'http://example.com' );
753 * Omitting the URL from either use results in the current URL being used
754 * (the value of `$_SERVER['REQUEST_URI']`).
756 * Values are expected to be encoded appropriately with urlencode() or rawurlencode().
758 * Setting any query variable's value to boolean false removes the key (see remove_query_arg()).
760 * Important: The return value of add_query_arg() is not escaped by default. Output should be
761 * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting
766 * @param string|array $key Either a query variable key, or an associative array of query variables.
767 * @param string $value Optional. Either a query variable value, or a URL to act upon.
768 * @param string $url Optional. A URL to act upon.
769 * @return string New URL query string (unescaped).
771 function add_query_arg() {
772 $args = func_get_args();
773 if ( is_array( $args[0] ) ) {
774 if ( count( $args ) < 2 || false === $args[1] )
775 $uri = $_SERVER['REQUEST_URI'];
779 if ( count( $args ) < 3 || false === $args[2] )
780 $uri = $_SERVER['REQUEST_URI'];
785 if ( $frag = strstr( $uri, '#' ) )
786 $uri = substr( $uri, 0, -strlen( $frag ) );
790 if ( 0 === stripos( $uri, 'http://' ) ) {
791 $protocol = 'http://';
792 $uri = substr( $uri, 7 );
793 } elseif ( 0 === stripos( $uri, 'https://' ) ) {
794 $protocol = 'https://';
795 $uri = substr( $uri, 8 );
800 if ( strpos( $uri, '?' ) !== false ) {
801 list( $base, $query ) = explode( '?', $uri, 2 );
803 } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
811 wp_parse_str( $query, $qs );
812 $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
813 if ( is_array( $args[0] ) ) {
814 foreach ( $args[0] as $k => $v ) {
818 $qs[ $args[0] ] = $args[1];
821 foreach ( $qs as $k => $v ) {
826 $ret = build_query( $qs );
827 $ret = trim( $ret, '?' );
828 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
829 $ret = $protocol . $base . $ret . $frag;
830 $ret = rtrim( $ret, '?' );
835 * Removes an item or items from a query string.
839 * @param string|array $key Query key or keys to remove.
840 * @param bool|string $query Optional. When false uses the current URL. Default false.
841 * @return string New URL query string.
843 function remove_query_arg( $key, $query = false ) {
844 if ( is_array( $key ) ) { // removing multiple keys
845 foreach ( $key as $k )
846 $query = add_query_arg( $k, false, $query );
849 return add_query_arg( $key, false, $query );
853 * Returns an array of single-use query variable names that can be removed from a URL.
857 * @return array An array of parameters to remove from the URL.
859 function wp_removable_query_args() {
860 $removable_query_args = array(
869 'hotkeys_highlight_first',
870 'hotkeys_highlight_last',
883 'wp-post-new-reload',
887 * Filters the list of query variables to remove.
891 * @param array $removable_query_args An array of query variables to remove from a URL.
893 return apply_filters( 'removable_query_args', $removable_query_args );
897 * Walks the array while sanitizing the contents.
901 * @param array $array Array to walk while sanitizing contents.
902 * @return array Sanitized $array.
904 function add_magic_quotes( $array ) {
905 foreach ( (array) $array as $k => $v ) {
906 if ( is_array( $v ) ) {
907 $array[$k] = add_magic_quotes( $v );
909 $array[$k] = addslashes( $v );
916 * HTTP request for URI to retrieve content.
920 * @see wp_safe_remote_get()
922 * @param string $uri URI/URL of web page to retrieve.
923 * @return false|string HTTP content. False on failure.
925 function wp_remote_fopen( $uri ) {
926 $parsed_url = @parse_url( $uri );
928 if ( !$parsed_url || !is_array( $parsed_url ) )
932 $options['timeout'] = 10;
934 $response = wp_safe_remote_get( $uri, $options );
936 if ( is_wp_error( $response ) )
939 return wp_remote_retrieve_body( $response );
943 * Set up the WordPress query.
947 * @global WP $wp_locale
948 * @global WP_Query $wp_query
949 * @global WP_Query $wp_the_query
951 * @param string|array $query_vars Default WP_Query arguments.
953 function wp( $query_vars = '' ) {
954 global $wp, $wp_query, $wp_the_query;
955 $wp->main( $query_vars );
957 if ( !isset($wp_the_query) )
958 $wp_the_query = $wp_query;
962 * Retrieve the description for the HTTP status.
966 * @global array $wp_header_to_desc
968 * @param int $code HTTP status code.
969 * @return string Empty string if not found, or description if found.
971 function get_status_header_desc( $code ) {
972 global $wp_header_to_desc;
974 $code = absint( $code );
976 if ( !isset( $wp_header_to_desc ) ) {
977 $wp_header_to_desc = array(
979 101 => 'Switching Protocols',
985 203 => 'Non-Authoritative Information',
987 205 => 'Reset Content',
988 206 => 'Partial Content',
989 207 => 'Multi-Status',
992 300 => 'Multiple Choices',
993 301 => 'Moved Permanently',
996 304 => 'Not Modified',
999 307 => 'Temporary Redirect',
1000 308 => 'Permanent Redirect',
1002 400 => 'Bad Request',
1003 401 => 'Unauthorized',
1004 402 => 'Payment Required',
1007 405 => 'Method Not Allowed',
1008 406 => 'Not Acceptable',
1009 407 => 'Proxy Authentication Required',
1010 408 => 'Request Timeout',
1013 411 => 'Length Required',
1014 412 => 'Precondition Failed',
1015 413 => 'Request Entity Too Large',
1016 414 => 'Request-URI Too Long',
1017 415 => 'Unsupported Media Type',
1018 416 => 'Requested Range Not Satisfiable',
1019 417 => 'Expectation Failed',
1020 418 => 'I\'m a teapot',
1021 421 => 'Misdirected Request',
1022 422 => 'Unprocessable Entity',
1024 424 => 'Failed Dependency',
1025 426 => 'Upgrade Required',
1026 428 => 'Precondition Required',
1027 429 => 'Too Many Requests',
1028 431 => 'Request Header Fields Too Large',
1029 451 => 'Unavailable For Legal Reasons',
1031 500 => 'Internal Server Error',
1032 501 => 'Not Implemented',
1033 502 => 'Bad Gateway',
1034 503 => 'Service Unavailable',
1035 504 => 'Gateway Timeout',
1036 505 => 'HTTP Version Not Supported',
1037 506 => 'Variant Also Negotiates',
1038 507 => 'Insufficient Storage',
1039 510 => 'Not Extended',
1040 511 => 'Network Authentication Required',
1044 if ( isset( $wp_header_to_desc[$code] ) )
1045 return $wp_header_to_desc[$code];
1051 * Set HTTP status header.
1054 * @since 4.4.0 Added the `$description` parameter.
1056 * @see get_status_header_desc()
1058 * @param int $code HTTP status code.
1059 * @param string $description Optional. A custom description for the HTTP status.
1061 function status_header( $code, $description = '' ) {
1062 if ( ! $description ) {
1063 $description = get_status_header_desc( $code );
1066 if ( empty( $description ) ) {
1070 $protocol = wp_get_server_protocol();
1071 $status_header = "$protocol $code $description";
1072 if ( function_exists( 'apply_filters' ) )
1075 * Filters an HTTP status header.
1079 * @param string $status_header HTTP status header.
1080 * @param int $code HTTP status code.
1081 * @param string $description Description for the status code.
1082 * @param string $protocol Server protocol.
1084 $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
1086 @header( $status_header, true, $code );
1090 * Get the header information to prevent caching.
1092 * The several different headers cover the different ways cache prevention
1093 * is handled by different browsers
1097 * @return array The associative array of header names and field values.
1099 function wp_get_nocache_headers() {
1101 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
1102 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
1105 if ( function_exists('apply_filters') ) {
1107 * Filters the cache-controlling headers.
1111 * @see wp_get_nocache_headers()
1113 * @param array $headers {
1114 * Header names and field values.
1116 * @type string $Expires Expires header.
1117 * @type string $Cache-Control Cache-Control header.
1120 $headers = (array) apply_filters( 'nocache_headers', $headers );
1122 $headers['Last-Modified'] = false;
1127 * Set the headers to prevent caching for the different browsers.
1129 * Different browsers support different nocache headers, so several
1130 * headers must be sent so that all of them get the point that no
1131 * caching should occur.
1135 * @see wp_get_nocache_headers()
1137 function nocache_headers() {
1138 $headers = wp_get_nocache_headers();
1140 unset( $headers['Last-Modified'] );
1142 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
1143 if ( function_exists( 'header_remove' ) ) {
1144 @header_remove( 'Last-Modified' );
1146 // In PHP 5.2, send an empty Last-Modified header, but only as a
1147 // last resort to override a header already sent. #WP23021
1148 foreach ( headers_list() as $header ) {
1149 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
1150 $headers['Last-Modified'] = '';
1156 foreach ( $headers as $name => $field_value )
1157 @header("{$name}: {$field_value}");
1161 * Set the headers for caching for 10 days with JavaScript content type.
1165 function cache_javascript_headers() {
1166 $expiresOffset = 10 * DAY_IN_SECONDS;
1168 header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
1169 header( "Vary: Accept-Encoding" ); // Handle proxies
1170 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
1174 * Retrieve the number of database queries during the WordPress execution.
1178 * @global wpdb $wpdb WordPress database abstraction object.
1180 * @return int Number of database queries.
1182 function get_num_queries() {
1184 return $wpdb->num_queries;
1188 * Whether input is yes or no.
1190 * Must be 'y' to be true.
1194 * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
1195 * @return bool True if yes, false on anything else.
1197 function bool_from_yn( $yn ) {
1198 return ( strtolower( $yn ) == 'y' );
1202 * Load the feed template from the use of an action hook.
1204 * If the feed action does not have a hook, then the function will die with a
1205 * message telling the visitor that the feed is not valid.
1207 * It is better to only have one hook for each feed.
1211 * @global WP_Query $wp_query Used to tell if the use a comment feed.
1213 function do_feed() {
1216 // Determine if we are looking at the main comment feed
1217 $is_main_comments_feed = ( $wp_query->is_comment_feed() && ! $wp_query->is_singular() );
1220 * Check the queried object for the existence of posts if it is not a feed for an archive,
1221 * search result, or main comments. By checking for the absense of posts we can prevent rendering the feed
1222 * templates at invalid endpoints. e.g.) /wp-content/plugins/feed/
1224 if ( ! $wp_query->have_posts() && ! ( $wp_query->is_archive() || $wp_query->is_search() || $is_main_comments_feed ) ) {
1225 wp_die( __( 'ERROR: This is not a valid feed.' ), '', array( 'response' => 404 ) );
1228 $feed = get_query_var( 'feed' );
1230 // Remove the pad, if present.
1231 $feed = preg_replace( '/^_+/', '', $feed );
1233 if ( $feed == '' || $feed == 'feed' )
1234 $feed = get_default_feed();
1236 if ( ! has_action( "do_feed_{$feed}" ) ) {
1237 wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
1241 * Fires once the given feed is loaded.
1243 * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
1244 * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
1247 * @since 4.4.0 The `$feed` parameter was added.
1249 * @param bool $is_comment_feed Whether the feed is a comment feed.
1250 * @param string $feed The feed name.
1252 do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
1256 * Load the RDF RSS 0.91 Feed template.
1260 * @see load_template()
1262 function do_feed_rdf() {
1263 load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1267 * Load the RSS 1.0 Feed Template.
1271 * @see load_template()
1273 function do_feed_rss() {
1274 load_template( ABSPATH . WPINC . '/feed-rss.php' );
1278 * Load either the RSS2 comment feed or the RSS2 posts feed.
1282 * @see load_template()
1284 * @param bool $for_comments True for the comment feed, false for normal feed.
1286 function do_feed_rss2( $for_comments ) {
1287 if ( $for_comments )
1288 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1290 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1294 * Load either Atom comment feed or Atom posts feed.
1298 * @see load_template()
1300 * @param bool $for_comments True for the comment feed, false for normal feed.
1302 function do_feed_atom( $for_comments ) {
1304 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1306 load_template( ABSPATH . WPINC . '/feed-atom.php' );
1310 * Display the robots.txt file content.
1312 * The echo content should be with usage of the permalinks or for creating the
1317 function do_robots() {
1318 header( 'Content-Type: text/plain; charset=utf-8' );
1321 * Fires when displaying the robots.txt file.
1325 do_action( 'do_robotstxt' );
1327 $output = "User-agent: *\n";
1328 $public = get_option( 'blog_public' );
1329 if ( '0' == $public ) {
1330 $output .= "Disallow: /\n";
1332 $site_url = parse_url( site_url() );
1333 $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1334 $output .= "Disallow: $path/wp-admin/\n";
1335 $output .= "Allow: $path/wp-admin/admin-ajax.php\n";
1339 * Filters the robots.txt output.
1343 * @param string $output Robots.txt output.
1344 * @param bool $public Whether the site is considered "public".
1346 echo apply_filters( 'robots_txt', $output, $public );
1350 * Test whether WordPress is already installed.
1352 * The cache will be checked first. If you have a cache plugin, which saves
1353 * the cache values, then this will work. If you use the default WordPress
1354 * cache, and the database goes away, then you might have problems.
1356 * Checks for the 'siteurl' option for whether WordPress is installed.
1360 * @global wpdb $wpdb WordPress database abstraction object.
1362 * @return bool Whether the site is already installed.
1364 function is_blog_installed() {
1368 * Check cache first. If options table goes away and we have true
1371 if ( wp_cache_get( 'is_blog_installed' ) )
1374 $suppress = $wpdb->suppress_errors();
1375 if ( ! wp_installing() ) {
1376 $alloptions = wp_load_alloptions();
1378 // If siteurl is not set to autoload, check it specifically
1379 if ( !isset( $alloptions['siteurl'] ) )
1380 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1382 $installed = $alloptions['siteurl'];
1383 $wpdb->suppress_errors( $suppress );
1385 $installed = !empty( $installed );
1386 wp_cache_set( 'is_blog_installed', $installed );
1391 // If visiting repair.php, return true and let it take over.
1392 if ( defined( 'WP_REPAIRING' ) )
1395 $suppress = $wpdb->suppress_errors();
1398 * Loop over the WP tables. If none exist, then scratch install is allowed.
1399 * If one or more exist, suggest table repair since we got here because the
1400 * options table could not be accessed.
1402 $wp_tables = $wpdb->tables();
1403 foreach ( $wp_tables as $table ) {
1404 // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1405 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1407 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1410 if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
1413 // One or more tables exist. We are insane.
1415 wp_load_translations_early();
1417 // Die with a DB error.
1418 $wpdb->error = sprintf(
1419 /* translators: %s: database repair URL */
1420 __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
1421 'maint/repair.php?referrer=is_blog_installed'
1427 $wpdb->suppress_errors( $suppress );
1429 wp_cache_set( 'is_blog_installed', false );
1435 * Retrieve URL with nonce added to URL query.
1439 * @param string $actionurl URL to add nonce action.
1440 * @param int|string $action Optional. Nonce action name. Default -1.
1441 * @param string $name Optional. Nonce name. Default '_wpnonce'.
1442 * @return string Escaped URL with nonce action added.
1444 function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
1445 $actionurl = str_replace( '&', '&', $actionurl );
1446 return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
1450 * Retrieve or display nonce hidden field for forms.
1452 * The nonce field is used to validate that the contents of the form came from
1453 * the location on the current site and not somewhere else. The nonce does not
1454 * offer absolute protection, but should protect against most cases. It is very
1455 * important to use nonce field in forms.
1457 * The $action and $name are optional, but if you want to have better security,
1458 * it is strongly suggested to set those two parameters. It is easier to just
1459 * call the function without any parameters, because validation of the nonce
1460 * doesn't require any parameters, but since crackers know what the default is
1461 * it won't be difficult for them to find a way around your nonce and cause
1464 * The input name will be whatever $name value you gave. The input value will be
1465 * the nonce creation value.
1469 * @param int|string $action Optional. Action name. Default -1.
1470 * @param string $name Optional. Nonce name. Default '_wpnonce'.
1471 * @param bool $referer Optional. Whether to set the referer field for validation. Default true.
1472 * @param bool $echo Optional. Whether to display or return hidden form field. Default true.
1473 * @return string Nonce field HTML markup.
1475 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1476 $name = esc_attr( $name );
1477 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1480 $nonce_field .= wp_referer_field( false );
1485 return $nonce_field;
1489 * Retrieve or display referer hidden field for forms.
1491 * The referer link is the current Request URI from the server super global. The
1492 * input name is '_wp_http_referer', in case you wanted to check manually.
1496 * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
1497 * @return string Referer field HTML markup.
1499 function wp_referer_field( $echo = true ) {
1500 $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
1503 echo $referer_field;
1504 return $referer_field;
1508 * Retrieve or display original referer hidden field for forms.
1510 * The input name is '_wp_original_http_referer' and will be either the same
1511 * value of wp_referer_field(), if that was posted already or it will be the
1512 * current page, if it doesn't exist.
1516 * @param bool $echo Optional. Whether to echo the original http referer. Default true.
1517 * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
1518 * Default 'current'.
1519 * @return string Original referer field.
1521 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1522 if ( ! $ref = wp_get_original_referer() ) {
1523 $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
1525 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
1527 echo $orig_referer_field;
1528 return $orig_referer_field;
1532 * Retrieve referer from '_wp_http_referer' or HTTP referer.
1534 * If it's the same as the current request URL, will return false.
1538 * @return false|string False on failure. Referer URL on success.
1540 function wp_get_referer() {
1541 if ( ! function_exists( 'wp_validate_redirect' ) ) {
1545 $ref = wp_get_raw_referer();
1547 if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) && $ref !== home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) ) {
1548 return wp_validate_redirect( $ref, false );
1555 * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
1557 * Do not use for redirects, use wp_get_referer() instead.
1561 * @return string|false Referer URL on success, false on failure.
1563 function wp_get_raw_referer() {
1564 if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
1565 return wp_unslash( $_REQUEST['_wp_http_referer'] );
1566 } else if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
1567 return wp_unslash( $_SERVER['HTTP_REFERER'] );
1574 * Retrieve original referer that was posted, if it exists.
1578 * @return string|false False if no original referer or original referer if set.
1580 function wp_get_original_referer() {
1581 if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
1582 return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
1587 * Recursive directory creation based on full path.
1589 * Will attempt to set permissions on folders.
1593 * @param string $target Full path to attempt to create.
1594 * @return bool Whether the path was created. True if path already exists.
1596 function wp_mkdir_p( $target ) {
1599 // Strip the protocol.
1600 if ( wp_is_stream( $target ) ) {
1601 list( $wrapper, $target ) = explode( '://', $target, 2 );
1604 // From php.net/mkdir user contributed notes.
1605 $target = str_replace( '//', '/', $target );
1607 // Put the wrapper back on the target.
1608 if ( $wrapper !== null ) {
1609 $target = $wrapper . '://' . $target;
1613 * Safe mode fails with a trailing slash under certain PHP versions.
1614 * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1616 $target = rtrim($target, '/');
1617 if ( empty($target) )
1620 if ( file_exists( $target ) )
1621 return @is_dir( $target );
1623 // We need to find the permissions of the parent folder that exists and inherit that.
1624 $target_parent = dirname( $target );
1625 while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
1626 $target_parent = dirname( $target_parent );
1629 // Get the permission bits.
1630 if ( $stat = @stat( $target_parent ) ) {
1631 $dir_perms = $stat['mode'] & 0007777;
1636 if ( @mkdir( $target, $dir_perms, true ) ) {
1639 * If a umask is set that modifies $dir_perms, we'll have to re-set
1640 * the $dir_perms correctly with chmod()
1642 if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
1643 $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
1644 for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
1645 @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
1656 * Test if a give filesystem path is absolute.
1658 * For example, '/foo/bar', or 'c:\windows'.
1662 * @param string $path File path.
1663 * @return bool True if path is absolute, false is not absolute.
1665 function path_is_absolute( $path ) {
1667 * This is definitive if true but fails if $path does not exist or contains
1670 if ( realpath($path) == $path )
1673 if ( strlen($path) == 0 || $path[0] == '.' )
1676 // Windows allows absolute paths like this.
1677 if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1680 // A path starting with / or \ is absolute; anything else is relative.
1681 return ( $path[0] == '/' || $path[0] == '\\' );
1685 * Join two filesystem paths together.
1687 * For example, 'give me $path relative to $base'. If the $path is absolute,
1688 * then it the full path is returned.
1692 * @param string $base Base path.
1693 * @param string $path Path relative to $base.
1694 * @return string The path with the base or absolute path.
1696 function path_join( $base, $path ) {
1697 if ( path_is_absolute($path) )
1700 return rtrim($base, '/') . '/' . ltrim($path, '/');
1704 * Normalize a filesystem path.
1706 * On windows systems, replaces backslashes with forward slashes
1707 * and forces upper-case drive letters.
1708 * Allows for two leading slashes for Windows network shares, but
1709 * ensures that all other duplicate slashes are reduced to a single.
1712 * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
1713 * @since 4.5.0 Allows for Windows network shares.
1715 * @param string $path Path to normalize.
1716 * @return string Normalized path.
1718 function wp_normalize_path( $path ) {
1719 $path = str_replace( '\\', '/', $path );
1720 $path = preg_replace( '|(?<=.)/+|', '/', $path );
1721 if ( ':' === substr( $path, 1, 1 ) ) {
1722 $path = ucfirst( $path );
1728 * Determine a writable directory for temporary files.
1730 * Function's preference is the return value of sys_get_temp_dir(),
1731 * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
1732 * before finally defaulting to /tmp/
1734 * In the event that this function does not find a writable location,
1735 * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
1739 * @staticvar string $temp
1741 * @return string Writable temporary directory.
1743 function get_temp_dir() {
1745 if ( defined('WP_TEMP_DIR') )
1746 return trailingslashit(WP_TEMP_DIR);
1749 return trailingslashit( $temp );
1751 if ( function_exists('sys_get_temp_dir') ) {
1752 $temp = sys_get_temp_dir();
1753 if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
1754 return trailingslashit( $temp );
1757 $temp = ini_get('upload_tmp_dir');
1758 if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
1759 return trailingslashit( $temp );
1761 $temp = WP_CONTENT_DIR . '/';
1762 if ( is_dir( $temp ) && wp_is_writable( $temp ) )
1769 * Determine if a directory is writable.
1771 * This function is used to work around certain ACL issues in PHP primarily
1772 * affecting Windows Servers.
1776 * @see win_is_writable()
1778 * @param string $path Path to check for write-ability.
1779 * @return bool Whether the path is writable.
1781 function wp_is_writable( $path ) {
1782 if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
1783 return win_is_writable( $path );
1785 return @is_writable( $path );
1789 * Workaround for Windows bug in is_writable() function
1791 * PHP has issues with Windows ACL's for determine if a
1792 * directory is writable or not, this works around them by
1793 * checking the ability to open files rather than relying
1794 * upon PHP to interprate the OS ACL.
1798 * @see https://bugs.php.net/bug.php?id=27609
1799 * @see https://bugs.php.net/bug.php?id=30931
1801 * @param string $path Windows path to check for write-ability.
1802 * @return bool Whether the path is writable.
1804 function win_is_writable( $path ) {
1806 if ( $path[strlen( $path ) - 1] == '/' ) { // if it looks like a directory, check a random file within the directory
1807 return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
1808 } elseif ( is_dir( $path ) ) { // If it's a directory (and not a file) check a random file within the directory
1809 return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
1811 // check tmp file for read/write capabilities
1812 $should_delete_tmp_file = !file_exists( $path );
1813 $f = @fopen( $path, 'a' );
1817 if ( $should_delete_tmp_file )
1823 * Retrieves uploads directory information.
1825 * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
1826 * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
1827 * when not uploading files.
1831 * @see wp_upload_dir()
1833 * @return array See wp_upload_dir() for description.
1835 function wp_get_upload_dir() {
1836 return wp_upload_dir( null, false );
1840 * Get an array containing the current upload directory's path and url.
1842 * Checks the 'upload_path' option, which should be from the web root folder,
1843 * and if it isn't empty it will be used. If it is empty, then the path will be
1844 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
1845 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
1847 * The upload URL path is set either by the 'upload_url_path' option or by using
1848 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
1850 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
1851 * the administration settings panel), then the time will be used. The format
1852 * will be year first and then month.
1854 * If the path couldn't be created, then an error will be returned with the key
1855 * 'error' containing the error message. The error suggests that the parent
1856 * directory is not writable by the server.
1858 * On success, the returned array will have many indices:
1859 * 'path' - base directory and sub directory or full path to upload directory.
1860 * 'url' - base url and sub directory or absolute URL to upload directory.
1861 * 'subdir' - sub directory if uploads use year/month folders option is on.
1862 * 'basedir' - path without subdir.
1863 * 'baseurl' - URL path without subdir.
1864 * 'error' - false or error message.
1867 * @uses _wp_upload_dir()
1869 * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
1870 * @param bool $create_dir Optional. Whether to check and create the uploads directory.
1871 * Default true for backward compatibility.
1872 * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false.
1873 * @return array See above for description.
1875 function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
1876 static $cache = array(), $tested_paths = array();
1878 $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
1880 if ( $refresh_cache || empty( $cache[ $key ] ) ) {
1881 $cache[ $key ] = _wp_upload_dir( $time );
1885 * Filters the uploads directory data.
1889 * @param array $uploads Array of upload directory data with keys of 'path',
1890 * 'url', 'subdir, 'basedir', and 'error'.
1892 $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
1894 if ( $create_dir ) {
1895 $path = $uploads['path'];
1897 if ( array_key_exists( $path, $tested_paths ) ) {
1898 $uploads['error'] = $tested_paths[ $path ];
1900 if ( ! wp_mkdir_p( $path ) ) {
1901 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
1902 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
1904 $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
1907 $uploads['error'] = sprintf(
1908 /* translators: %s: directory path */
1909 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
1910 esc_html( $error_path )
1914 $tested_paths[ $path ] = $uploads['error'];
1922 * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
1926 * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
1927 * @return array See wp_upload_dir()
1929 function _wp_upload_dir( $time = null ) {
1930 $siteurl = get_option( 'siteurl' );
1931 $upload_path = trim( get_option( 'upload_path' ) );
1933 if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
1934 $dir = WP_CONTENT_DIR . '/uploads';
1935 } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
1936 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
1937 $dir = path_join( ABSPATH, $upload_path );
1939 $dir = $upload_path;
1942 if ( !$url = get_option( 'upload_url_path' ) ) {
1943 if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
1944 $url = WP_CONTENT_URL . '/uploads';
1946 $url = trailingslashit( $siteurl ) . $upload_path;
1950 * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
1951 * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
1953 if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
1954 $dir = ABSPATH . UPLOADS;
1955 $url = trailingslashit( $siteurl ) . UPLOADS;
1958 // If multisite (and if not the main site in a post-MU network)
1959 if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
1961 if ( ! get_site_option( 'ms_files_rewriting' ) ) {
1963 * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
1964 * straightforward: Append sites/%d if we're not on the main site (for post-MU
1965 * networks). (The extra directory prevents a four-digit ID from conflicting with
1966 * a year-based directory for the main site. But if a MU-era network has disabled
1967 * ms-files rewriting manually, they don't need the extra directory, as they never
1968 * had wp-content/uploads for the main site.)
1971 if ( defined( 'MULTISITE' ) )
1972 $ms_dir = '/sites/' . get_current_blog_id();
1974 $ms_dir = '/' . get_current_blog_id();
1979 } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
1981 * Handle the old-form ms-files.php rewriting if the network still has that enabled.
1982 * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
1983 * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
1985 * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
1986 * the original blog ID.
1988 * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
1989 * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
1990 * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
1991 * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
1994 if ( defined( 'BLOGUPLOADDIR' ) )
1995 $dir = untrailingslashit( BLOGUPLOADDIR );
1997 $dir = ABSPATH . UPLOADS;
1998 $url = trailingslashit( $siteurl ) . 'files';
2006 if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
2007 // Generate the yearly and monthly dirs
2009 $time = current_time( 'mysql' );
2010 $y = substr( $time, 0, 4 );
2011 $m = substr( $time, 5, 2 );
2021 'subdir' => $subdir,
2022 'basedir' => $basedir,
2023 'baseurl' => $baseurl,
2029 * Get a filename that is sanitized and unique for the given directory.
2031 * If the filename is not unique, then a number will be added to the filename
2032 * before the extension, and will continue adding numbers until the filename is
2035 * The callback is passed three parameters, the first one is the directory, the
2036 * second is the filename, and the third is the extension.
2040 * @param string $dir Directory.
2041 * @param string $filename File name.
2042 * @param callable $unique_filename_callback Callback. Default null.
2043 * @return string New filename, if given wasn't unique.
2045 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
2046 // Sanitize the file name before we begin processing.
2047 $filename = sanitize_file_name($filename);
2049 // Separate the filename into a name and extension.
2050 $ext = pathinfo( $filename, PATHINFO_EXTENSION );
2051 $name = pathinfo( $filename, PATHINFO_BASENAME );
2056 // Edge case: if file is named '.ext', treat as an empty name.
2057 if ( $name === $ext ) {
2062 * Increment the file number until we have a unique file to save in $dir.
2063 * Use callback if supplied.
2065 if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
2066 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
2070 // Change '.ext' to lower case.
2071 if ( $ext && strtolower($ext) != $ext ) {
2072 $ext2 = strtolower($ext);
2073 $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
2075 // Check for both lower and upper case extension or image sub-sizes may be overwritten.
2076 while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
2077 $new_number = $number + 1;
2078 $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-$new_number$ext", $filename );
2079 $filename2 = str_replace( array( "-$number$ext2", "$number$ext2" ), "-$new_number$ext2", $filename2 );
2080 $number = $new_number;
2084 * Filters the result when generating a unique file name.
2088 * @param string $filename Unique file name.
2089 * @param string $ext File extension, eg. ".png".
2090 * @param string $dir Directory path.
2091 * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
2093 return apply_filters( 'wp_unique_filename', $filename2, $ext, $dir, $unique_filename_callback );
2096 while ( file_exists( $dir . "/$filename" ) ) {
2097 if ( '' == "$number$ext" ) {
2098 $filename = "$filename-" . ++$number;
2100 $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-" . ++$number . $ext, $filename );
2105 /** This filter is documented in wp-includes/functions.php */
2106 return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
2110 * Create a file in the upload folder with given content.
2112 * If there is an error, then the key 'error' will exist with the error message.
2113 * If success, then the key 'file' will have the unique file path, the 'url' key
2114 * will have the link to the new file. and the 'error' key will be set to false.
2116 * This function will not move an uploaded file to the upload folder. It will
2117 * create a new file with the content in $bits parameter. If you move the upload
2118 * file, read the content of the uploaded file, and then you can give the
2119 * filename and content to this function, which will add it to the upload
2122 * The permissions will be set on the new file automatically by this function.
2126 * @param string $name Filename.
2127 * @param null|string $deprecated Never used. Set to null.
2128 * @param mixed $bits File content
2129 * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
2132 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
2133 if ( !empty( $deprecated ) )
2134 _deprecated_argument( __FUNCTION__, '2.0.0' );
2136 if ( empty( $name ) )
2137 return array( 'error' => __( 'Empty filename' ) );
2139 $wp_filetype = wp_check_filetype( $name );
2140 if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
2141 return array( 'error' => __( 'Invalid file type' ) );
2143 $upload = wp_upload_dir( $time );
2145 if ( $upload['error'] !== false )
2149 * Filters whether to treat the upload bits as an error.
2151 * Passing a non-array to the filter will effectively short-circuit preparing
2152 * the upload bits, returning that value instead.
2156 * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
2158 $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
2159 if ( !is_array( $upload_bits_error ) ) {
2160 $upload[ 'error' ] = $upload_bits_error;
2164 $filename = wp_unique_filename( $upload['path'], $name );
2166 $new_file = $upload['path'] . "/$filename";
2167 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
2168 if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
2169 $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
2171 $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
2174 /* translators: %s: directory path */
2175 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
2178 return array( 'error' => $message );
2181 $ifp = @ fopen( $new_file, 'wb' );
2183 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
2185 @fwrite( $ifp, $bits );
2189 // Set correct file permissions
2190 $stat = @ stat( dirname( $new_file ) );
2191 $perms = $stat['mode'] & 0007777;
2192 $perms = $perms & 0000666;
2193 @ chmod( $new_file, $perms );
2197 $url = $upload['url'] . "/$filename";
2199 /** This filter is documented in wp-admin/includes/file.php */
2200 return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $wp_filetype['type'], 'error' => false ), 'sideload' );
2204 * Retrieve the file type based on the extension name.
2208 * @param string $ext The extension to search.
2209 * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
2211 function wp_ext2type( $ext ) {
2212 $ext = strtolower( $ext );
2214 $ext2type = wp_get_ext_types();
2215 foreach ( $ext2type as $type => $exts )
2216 if ( in_array( $ext, $exts ) )
2221 * Retrieve the file type from the file name.
2223 * You can optionally define the mime array, if needed.
2227 * @param string $filename File name or path.
2228 * @param array $mimes Optional. Key is the file extension with value as the mime type.
2229 * @return array Values with extension first and mime type.
2231 function wp_check_filetype( $filename, $mimes = null ) {
2232 if ( empty($mimes) )
2233 $mimes = get_allowed_mime_types();
2237 foreach ( $mimes as $ext_preg => $mime_match ) {
2238 $ext_preg = '!\.(' . $ext_preg . ')$!i';
2239 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
2240 $type = $mime_match;
2241 $ext = $ext_matches[1];
2246 return compact( 'ext', 'type' );
2250 * Attempt to determine the real file type of a file.
2252 * If unable to, the file name extension will be used to determine type.
2254 * If it's determined that the extension does not match the file's real type,
2255 * then the "proper_filename" value will be set with a proper filename and extension.
2257 * Currently this function only supports validating images known to getimagesize().
2261 * @param string $file Full path to the file.
2262 * @param string $filename The name of the file (may differ from $file due to $file being
2263 * in a tmp directory).
2264 * @param array $mimes Optional. Key is the file extension with value as the mime type.
2265 * @return array Values for the extension, MIME, and either a corrected filename or false
2266 * if original $filename is valid.
2268 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
2269 $proper_filename = false;
2271 // Do basic extension validation and MIME mapping
2272 $wp_filetype = wp_check_filetype( $filename, $mimes );
2273 $ext = $wp_filetype['ext'];
2274 $type = $wp_filetype['type'];
2276 // We can't do any further validation without a file to work with
2277 if ( ! file_exists( $file ) ) {
2278 return compact( 'ext', 'type', 'proper_filename' );
2281 // We're able to validate images using GD
2282 if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
2284 // Attempt to figure out what type of image it actually is
2285 $imgstats = @getimagesize( $file );
2287 // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
2288 if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
2290 * Filters the list mapping image mime types to their respective extensions.
2294 * @param array $mime_to_ext Array of image mime types and their matching extensions.
2296 $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
2297 'image/jpeg' => 'jpg',
2298 'image/png' => 'png',
2299 'image/gif' => 'gif',
2300 'image/bmp' => 'bmp',
2301 'image/tiff' => 'tif',
2304 // Replace whatever is after the last period in the filename with the correct extension
2305 if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
2306 $filename_parts = explode( '.', $filename );
2307 array_pop( $filename_parts );
2308 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
2309 $new_filename = implode( '.', $filename_parts );
2311 if ( $new_filename != $filename ) {
2312 $proper_filename = $new_filename; // Mark that it changed
2314 // Redefine the extension / MIME
2315 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
2316 $ext = $wp_filetype['ext'];
2317 $type = $wp_filetype['type'];
2323 * Filters the "real" file type of the given file.
2327 * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
2328 * 'proper_filename' keys.
2329 * @param string $file Full path to the file.
2330 * @param string $filename The name of the file (may differ from $file due to
2331 * $file being in a tmp directory).
2332 * @param array $mimes Key is the file extension with value as the mime type.
2334 return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
2338 * Retrieve list of mime types and file extensions.
2341 * @since 4.2.0 Support was added for GIMP (xcf) files.
2343 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
2345 function wp_get_mime_types() {
2347 * Filters the list of mime types and file extensions.
2349 * This filter should be used to add, not remove, mime types. To remove
2350 * mime types, use the {@see 'upload_mimes'} filter.
2354 * @param array $wp_get_mime_types Mime types keyed by the file extension regex
2355 * corresponding to those types.
2357 return apply_filters( 'mime_types', array(
2359 'jpg|jpeg|jpe' => 'image/jpeg',
2360 'gif' => 'image/gif',
2361 'png' => 'image/png',
2362 'bmp' => 'image/bmp',
2363 'tiff|tif' => 'image/tiff',
2364 'ico' => 'image/x-icon',
2366 'asf|asx' => 'video/x-ms-asf',
2367 'wmv' => 'video/x-ms-wmv',
2368 'wmx' => 'video/x-ms-wmx',
2369 'wm' => 'video/x-ms-wm',
2370 'avi' => 'video/avi',
2371 'divx' => 'video/divx',
2372 'flv' => 'video/x-flv',
2373 'mov|qt' => 'video/quicktime',
2374 'mpeg|mpg|mpe' => 'video/mpeg',
2375 'mp4|m4v' => 'video/mp4',
2376 'ogv' => 'video/ogg',
2377 'webm' => 'video/webm',
2378 'mkv' => 'video/x-matroska',
2379 '3gp|3gpp' => 'video/3gpp', // Can also be audio
2380 '3g2|3gp2' => 'video/3gpp2', // Can also be audio
2382 'txt|asc|c|cc|h|srt' => 'text/plain',
2383 'csv' => 'text/csv',
2384 'tsv' => 'text/tab-separated-values',
2385 'ics' => 'text/calendar',
2386 'rtx' => 'text/richtext',
2387 'css' => 'text/css',
2388 'htm|html' => 'text/html',
2389 'vtt' => 'text/vtt',
2390 'dfxp' => 'application/ttaf+xml',
2392 'mp3|m4a|m4b' => 'audio/mpeg',
2393 'ra|ram' => 'audio/x-realaudio',
2394 'wav' => 'audio/wav',
2395 'ogg|oga' => 'audio/ogg',
2396 'mid|midi' => 'audio/midi',
2397 'wma' => 'audio/x-ms-wma',
2398 'wax' => 'audio/x-ms-wax',
2399 'mka' => 'audio/x-matroska',
2400 // Misc application formats.
2401 'rtf' => 'application/rtf',
2402 'js' => 'application/javascript',
2403 'pdf' => 'application/pdf',
2404 'swf' => 'application/x-shockwave-flash',
2405 'class' => 'application/java',
2406 'tar' => 'application/x-tar',
2407 'zip' => 'application/zip',
2408 'gz|gzip' => 'application/x-gzip',
2409 'rar' => 'application/rar',
2410 '7z' => 'application/x-7z-compressed',
2411 'exe' => 'application/x-msdownload',
2412 'psd' => 'application/octet-stream',
2413 'xcf' => 'application/octet-stream',
2414 // MS Office formats.
2415 'doc' => 'application/msword',
2416 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
2417 'wri' => 'application/vnd.ms-write',
2418 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
2419 'mdb' => 'application/vnd.ms-access',
2420 'mpp' => 'application/vnd.ms-project',
2421 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
2422 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
2423 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
2424 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
2425 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
2426 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
2427 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
2428 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
2429 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
2430 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
2431 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
2432 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
2433 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
2434 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
2435 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
2436 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
2437 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
2438 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
2439 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
2440 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
2441 'oxps' => 'application/oxps',
2442 'xps' => 'application/vnd.ms-xpsdocument',
2443 // OpenOffice formats.
2444 'odt' => 'application/vnd.oasis.opendocument.text',
2445 'odp' => 'application/vnd.oasis.opendocument.presentation',
2446 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
2447 'odg' => 'application/vnd.oasis.opendocument.graphics',
2448 'odc' => 'application/vnd.oasis.opendocument.chart',
2449 'odb' => 'application/vnd.oasis.opendocument.database',
2450 'odf' => 'application/vnd.oasis.opendocument.formula',
2451 // WordPerfect formats.
2452 'wp|wpd' => 'application/wordperfect',
2454 'key' => 'application/vnd.apple.keynote',
2455 'numbers' => 'application/vnd.apple.numbers',
2456 'pages' => 'application/vnd.apple.pages',
2461 * Retrieves the list of common file extensions and their types.
2465 * @return array Array of file extensions types keyed by the type of file.
2467 function wp_get_ext_types() {
2470 * Filters file type based on the extension name.
2474 * @see wp_ext2type()
2476 * @param array $ext2type Multi-dimensional array with extensions for a default set
2479 return apply_filters( 'ext2type', array(
2480 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
2481 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
2482 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
2483 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
2484 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
2485 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
2486 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
2487 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
2488 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
2493 * Retrieve list of allowed mime types and file extensions.
2497 * @param int|WP_User $user Optional. User to check. Defaults to current user.
2498 * @return array Array of mime types keyed by the file extension regex corresponding
2501 function get_allowed_mime_types( $user = null ) {
2502 $t = wp_get_mime_types();
2504 unset( $t['swf'], $t['exe'] );
2505 if ( function_exists( 'current_user_can' ) )
2506 $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
2508 if ( empty( $unfiltered ) )
2509 unset( $t['htm|html'] );
2512 * Filters list of allowed mime types and file extensions.
2516 * @param array $t Mime types keyed by the file extension regex corresponding to
2517 * those types. 'swf' and 'exe' removed from full list. 'htm|html' also
2518 * removed depending on '$user' capabilities.
2519 * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
2521 return apply_filters( 'upload_mimes', $t, $user );
2525 * Display "Are You Sure" message to confirm the action being taken.
2527 * If the action has the nonce explain message, then it will be displayed
2528 * along with the "Are you sure?" message.
2532 * @param string $action The nonce action.
2534 function wp_nonce_ays( $action ) {
2535 if ( 'log-out' == $action ) {
2537 /* translators: %s: site name */
2538 __( 'You are attempting to log out of %s' ),
2539 get_bloginfo( 'name' )
2542 $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
2544 /* translators: %s: logout URL */
2545 __( 'Do you really want to <a href="%s">log out</a>?' ),
2546 wp_logout_url( $redirect_to )
2549 $html = __( 'Are you sure you want to do this?' );
2550 if ( wp_get_referer() ) {
2552 $html .= sprintf( '<a href="%s">%s</a>',
2553 esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
2554 __( 'Please try again.' )
2559 wp_die( $html, __( 'WordPress Failure Notice' ), 403 );
2563 * Kill WordPress execution and display HTML message with error message.
2565 * This function complements the `die()` PHP function. The difference is that
2566 * HTML will be displayed to the user. It is recommended to use this function
2567 * only when the execution should not continue any further. It is not recommended
2568 * to call this function very often, and try to handle as many errors as possible
2569 * silently or more gracefully.
2571 * As a shorthand, the desired HTTP response code may be passed as an integer to
2572 * the `$title` parameter (the default title would apply) or the `$args` parameter.
2575 * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
2576 * an integer to be used as the response code.
2578 * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,
2579 * and not an Ajax or XML-RPC request, the error's messages are used.
2581 * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
2582 * error data with the key 'title' may be used to specify the title.
2583 * If `$title` is an integer, then it is treated as the response
2584 * code. Default empty.
2585 * @param string|array|int $args {
2586 * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
2587 * as the response code. Default empty array.
2589 * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
2590 * @type bool $back_link Whether to include a link to go back. Default false.
2591 * @type string $text_direction The text direction. This is only useful internally, when WordPress
2592 * is still loading and the site's locale is not set up yet. Accepts 'rtl'.
2593 * Default is the value of is_rtl().
2596 function wp_die( $message = '', $title = '', $args = array() ) {
2598 if ( is_int( $args ) ) {
2599 $args = array( 'response' => $args );
2600 } elseif ( is_int( $title ) ) {
2601 $args = array( 'response' => $title );
2605 if ( wp_doing_ajax() ) {
2607 * Filters the callback for killing WordPress execution for Ajax requests.
2611 * @param callable $function Callback function name.
2613 $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
2614 } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
2616 * Filters the callback for killing WordPress execution for XML-RPC requests.
2620 * @param callable $function Callback function name.
2622 $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
2625 * Filters the callback for killing WordPress execution for all non-Ajax, non-XML-RPC requests.
2629 * @param callable $function Callback function name.
2631 $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
2634 call_user_func( $function, $message, $title, $args );
2638 * Kills WordPress execution and display HTML message with error message.
2640 * This is the default handler for wp_die if you want a custom one for your
2641 * site then you can overload using the {@see 'wp_die_handler'} filter in wp_die().
2646 * @param string|WP_Error $message Error message or WP_Error object.
2647 * @param string $title Optional. Error title. Default empty.
2648 * @param string|array $args Optional. Arguments to control behavior. Default empty array.
2650 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
2651 $defaults = array( 'response' => 500 );
2652 $r = wp_parse_args($args, $defaults);
2654 $have_gettext = function_exists('__');
2656 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
2657 if ( empty( $title ) ) {
2658 $error_data = $message->get_error_data();
2659 if ( is_array( $error_data ) && isset( $error_data['title'] ) )
2660 $title = $error_data['title'];
2662 $errors = $message->get_error_messages();
2663 switch ( count( $errors ) ) {
2668 $message = "<p>{$errors[0]}</p>";
2671 $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
2674 } elseif ( is_string( $message ) ) {
2675 $message = "<p>$message</p>";
2678 if ( isset( $r['back_link'] ) && $r['back_link'] ) {
2679 $back_text = $have_gettext? __('« Back') : '« Back';
2680 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
2683 if ( ! did_action( 'admin_head' ) ) :
2684 if ( !headers_sent() ) {
2685 status_header( $r['response'] );
2687 header( 'Content-Type: text/html; charset=utf-8' );
2690 if ( empty($title) )
2691 $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error';
2693 $text_direction = 'ltr';
2694 if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
2695 $text_direction = 'rtl';
2696 elseif ( function_exists( 'is_rtl' ) && is_rtl() )
2697 $text_direction = 'rtl';
2700 <!-- 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
2702 <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'"; ?>>
2704 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2705 <meta name="viewport" content="width=device-width">
2707 if ( function_exists( 'wp_no_robots' ) ) {
2711 <title><?php echo $title ?></title>
2712 <style type="text/css">
2714 background: #f1f1f1;
2719 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
2723 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13);
2724 box-shadow: 0 1px 3px rgba(0,0,0,0.13);
2727 border-bottom: 1px solid #dadada;
2733 padding-bottom: 7px;
2741 margin: 25px 0 20px;
2744 font-family: Consolas, Monaco, monospace;
2747 margin-bottom: 10px;
2761 0 0 2px 1px rgba(30, 140, 190, .8);
2764 0 0 2px 1px rgba(30, 140, 190, .8);
2768 background: #f7f7f7;
2769 border: 1px solid #ccc;
2771 display: inline-block;
2772 text-decoration: none;
2777 padding: 0 10px 1px;
2779 -webkit-border-radius: 3px;
2780 -webkit-appearance: none;
2782 white-space: nowrap;
2783 -webkit-box-sizing: border-box;
2784 -moz-box-sizing: border-box;
2785 box-sizing: border-box;
2787 -webkit-box-shadow: 0 1px 0 #ccc;
2788 box-shadow: 0 1px 0 #ccc;
2789 vertical-align: top;
2792 .button.button-large {
2795 padding: 0 12px 2px;
2800 background: #fafafa;
2806 border-color: #5b9dd9;
2807 -webkit-box-shadow: 0 0 3px rgba( 0, 115, 170, .8 );
2808 box-shadow: 0 0 3px rgba( 0, 115, 170, .8 );
2815 -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2816 box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
2817 -webkit-transform: translateY(1px);
2818 -ms-transform: translateY(1px);
2819 transform: translateY(1px);
2823 if ( 'rtl' == $text_direction ) {
2824 echo 'body { font-family: Tahoma, Arial; }';
2829 <body id="error-page">
2830 <?php endif; // ! did_action( 'admin_head' ) ?>
2831 <?php echo $message; ?>
2839 * Kill WordPress execution and display XML message with error message.
2841 * This is the handler for wp_die when processing XMLRPC requests.
2846 * @global wp_xmlrpc_server $wp_xmlrpc_server
2848 * @param string $message Error message.
2849 * @param string $title Optional. Error title. Default empty.
2850 * @param string|array $args Optional. Arguments to control behavior. Default empty array.
2852 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
2853 global $wp_xmlrpc_server;
2854 $defaults = array( 'response' => 500 );
2856 $r = wp_parse_args($args, $defaults);
2858 if ( $wp_xmlrpc_server ) {
2859 $error = new IXR_Error( $r['response'] , $message);
2860 $wp_xmlrpc_server->output( $error->getXml() );
2866 * Kill WordPress ajax execution.
2868 * This is the handler for wp_die when processing Ajax requests.
2873 * @param string $message Error message.
2874 * @param string $title Optional. Error title (unused). Default empty.
2875 * @param string|array $args Optional. Arguments to control behavior. Default empty array.
2877 function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
2881 $r = wp_parse_args( $args, $defaults );
2883 if ( ! headers_sent() && null !== $r['response'] ) {
2884 status_header( $r['response'] );
2887 if ( is_scalar( $message ) )
2888 die( (string) $message );
2893 * Kill WordPress execution.
2895 * This is the handler for wp_die when processing APP requests.
2900 * @param string $message Optional. Response to print. Default empty.
2902 function _scalar_wp_die_handler( $message = '' ) {
2903 if ( is_scalar( $message ) )
2904 die( (string) $message );
2909 * Encode a variable into JSON, with some sanity checks.
2913 * @param mixed $data Variable (usually an array or object) to encode as JSON.
2914 * @param int $options Optional. Options to be passed to json_encode(). Default 0.
2915 * @param int $depth Optional. Maximum depth to walk through $data. Must be
2916 * greater than 0. Default 512.
2917 * @return string|false The JSON encoded string, or false if it cannot be encoded.
2919 function wp_json_encode( $data, $options = 0, $depth = 512 ) {
2921 * json_encode() has had extra params added over the years.
2922 * $options was added in 5.3, and $depth in 5.5.
2923 * We need to make sure we call it with the correct arguments.
2925 if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
2926 $args = array( $data, $options, $depth );
2927 } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
2928 $args = array( $data, $options );
2930 $args = array( $data );
2933 // Prepare the data for JSON serialization.
2934 $args[0] = _wp_json_prepare_data( $data );
2936 $json = @call_user_func_array( 'json_encode', $args );
2938 // If json_encode() was successful, no need to do more sanity checking.
2939 // ... unless we're in an old version of PHP, and json_encode() returned
2940 // a string containing 'null'. Then we need to do more sanity checking.
2941 if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) {
2946 $args[0] = _wp_json_sanity_check( $data, $depth );
2947 } catch ( Exception $e ) {
2951 return call_user_func_array( 'json_encode', $args );
2955 * Perform sanity checks on data that shall be encoded to JSON.
2961 * @see wp_json_encode()
2963 * @param mixed $data Variable (usually an array or object) to encode as JSON.
2964 * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
2965 * @return mixed The sanitized data that shall be encoded to JSON.
2967 function _wp_json_sanity_check( $data, $depth ) {
2969 throw new Exception( 'Reached depth limit' );
2972 if ( is_array( $data ) ) {
2974 foreach ( $data as $id => $el ) {
2975 // Don't forget to sanitize the ID!
2976 if ( is_string( $id ) ) {
2977 $clean_id = _wp_json_convert_string( $id );
2982 // Check the element type, so that we're only recursing if we really have to.
2983 if ( is_array( $el ) || is_object( $el ) ) {
2984 $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
2985 } elseif ( is_string( $el ) ) {
2986 $output[ $clean_id ] = _wp_json_convert_string( $el );
2988 $output[ $clean_id ] = $el;
2991 } elseif ( is_object( $data ) ) {
2992 $output = new stdClass;
2993 foreach ( $data as $id => $el ) {
2994 if ( is_string( $id ) ) {
2995 $clean_id = _wp_json_convert_string( $id );
3000 if ( is_array( $el ) || is_object( $el ) ) {
3001 $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
3002 } elseif ( is_string( $el ) ) {
3003 $output->$clean_id = _wp_json_convert_string( $el );
3005 $output->$clean_id = $el;
3008 } elseif ( is_string( $data ) ) {
3009 return _wp_json_convert_string( $data );
3018 * Convert a string to UTF-8, so that it can be safely encoded to JSON.
3024 * @see _wp_json_sanity_check()
3026 * @staticvar bool $use_mb
3028 * @param string $string The string which is to be converted.
3029 * @return string The checked string.
3031 function _wp_json_convert_string( $string ) {
3032 static $use_mb = null;
3033 if ( is_null( $use_mb ) ) {
3034 $use_mb = function_exists( 'mb_convert_encoding' );
3038 $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
3040 return mb_convert_encoding( $string, 'UTF-8', $encoding );
3042 return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
3045 return wp_check_invalid_utf8( $string, true );
3050 * Prepares response data to be serialized to JSON.
3052 * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
3058 * @param mixed $data Native representation.
3059 * @return bool|int|float|null|string|array Data ready for `json_encode()`.
3061 function _wp_json_prepare_data( $data ) {
3062 if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
3066 switch ( gettype( $data ) ) {
3072 // These values can be passed through.
3076 // Arrays must be mapped in case they also return objects.
3077 return array_map( '_wp_json_prepare_data', $data );
3080 // If this is an incomplete object (__PHP_Incomplete_Class), bail.
3081 if ( ! is_object( $data ) ) {
3085 if ( $data instanceof JsonSerializable ) {
3086 $data = $data->jsonSerialize();
3088 $data = get_object_vars( $data );
3091 // Now, pass the array (or whatever was returned from jsonSerialize through).
3092 return _wp_json_prepare_data( $data );
3100 * Send a JSON response back to an Ajax request.
3103 * @since 4.7.0 The `$status_code` parameter was added.
3105 * @param mixed $response Variable (usually an array or object) to encode as JSON,
3106 * then print and die.
3107 * @param int $status_code The HTTP status code to output.
3109 function wp_send_json( $response, $status_code = null ) {
3110 @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
3111 if ( null !== $status_code ) {
3112 status_header( $status_code );
3114 echo wp_json_encode( $response );
3116 if ( wp_doing_ajax() ) {
3117 wp_die( '', '', array(
3126 * Send a JSON response back to an Ajax request, indicating success.
3129 * @since 4.7.0 The `$status_code` parameter was added.
3131 * @param mixed $data Data to encode as JSON, then print and die.
3132 * @param int $status_code The HTTP status code to output.
3134 function wp_send_json_success( $data = null, $status_code = null ) {
3135 $response = array( 'success' => true );
3137 if ( isset( $data ) )
3138 $response['data'] = $data;
3140 wp_send_json( $response, $status_code );
3144 * Send a JSON response back to an Ajax request, indicating failure.
3146 * If the `$data` parameter is a WP_Error object, the errors
3147 * within the object are processed and output as an array of error
3148 * codes and corresponding messages. All other types are output
3149 * without further processing.
3152 * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
3153 * @since 4.7.0 The `$status_code` parameter was added.
3155 * @param mixed $data Data to encode as JSON, then print and die.
3156 * @param int $status_code The HTTP status code to output.
3158 function wp_send_json_error( $data = null, $status_code = null ) {
3159 $response = array( 'success' => false );
3161 if ( isset( $data ) ) {
3162 if ( is_wp_error( $data ) ) {
3164 foreach ( $data->errors as $code => $messages ) {
3165 foreach ( $messages as $message ) {
3166 $result[] = array( 'code' => $code, 'message' => $message );
3170 $response['data'] = $result;
3172 $response['data'] = $data;
3176 wp_send_json( $response, $status_code );
3180 * Checks that a JSONP callback is a valid JavaScript callback.
3182 * Only allows alphanumeric characters and the dot character in callback
3183 * function names. This helps to mitigate XSS attacks caused by directly
3184 * outputting user input.
3188 * @param string $callback Supplied JSONP callback function.
3189 * @return bool True if valid callback, otherwise false.
3191 function wp_check_jsonp_callback( $callback ) {
3192 if ( ! is_string( $callback ) ) {
3196 preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
3198 return 0 === $illegal_char_count;
3202 * Retrieve the WordPress home page URL.
3204 * If the constant named 'WP_HOME' exists, then it will be used and returned
3205 * by the function. This can be used to counter the redirection on your local
3206 * development environment.
3213 * @param string $url URL for the home location.
3214 * @return string Homepage location.
3216 function _config_wp_home( $url = '' ) {
3217 if ( defined( 'WP_HOME' ) )
3218 return untrailingslashit( WP_HOME );
3223 * Retrieve the WordPress site URL.
3225 * If the constant named 'WP_SITEURL' is defined, then the value in that
3226 * constant will always be returned. This can be used for debugging a site
3227 * on your localhost while not having to change the database to your URL.
3234 * @param string $url URL to set the WordPress site location.
3235 * @return string The WordPress Site URL.
3237 function _config_wp_siteurl( $url = '' ) {
3238 if ( defined( 'WP_SITEURL' ) )
3239 return untrailingslashit( WP_SITEURL );
3244 * Delete the fresh site option.
3249 function _delete_option_fresh_site() {
3250 update_option( 'fresh_site', 0 );
3254 * Set the localized direction for MCE plugin.
3256 * Will only set the direction to 'rtl', if the WordPress locale has
3257 * the text direction set to 'rtl'.
3259 * Fills in the 'directionality' setting, enables the 'directionality'
3260 * plugin, and adds the 'ltr' button to 'toolbar1', formerly
3261 * 'theme_advanced_buttons1' array keys. These keys are then returned
3262 * in the $mce_init (TinyMCE settings) array.
3267 * @param array $mce_init MCE settings array.
3268 * @return array Direction set for 'rtl', if needed by locale.
3270 function _mce_set_direction( $mce_init ) {
3272 $mce_init['directionality'] = 'rtl';
3273 $mce_init['rtl_ui'] = true;
3275 if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
3276 $mce_init['plugins'] .= ',directionality';
3279 if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
3280 $mce_init['toolbar1'] .= ',ltr';
3289 * Convert smiley code to the icon graphic file equivalent.
3291 * You can turn off smilies, by going to the write setting screen and unchecking
3292 * the box, or by setting 'use_smilies' option to false or removing the option.
3294 * Plugins may override the default smiley list by setting the $wpsmiliestrans
3295 * to an array, with the key the code the blogger types in and the value the
3298 * The $wp_smiliessearch global is for the regular expression and is set each
3299 * time the function is called.
3301 * The full list of smilies can be found in the function and won't be listed in
3302 * the description. Probably should create a Codex page for it, so that it is
3305 * @global array $wpsmiliestrans
3306 * @global array $wp_smiliessearch
3310 function smilies_init() {
3311 global $wpsmiliestrans, $wp_smiliessearch;
3313 // don't bother setting up smilies if they are disabled
3314 if ( !get_option( 'use_smilies' ) )
3317 if ( !isset( $wpsmiliestrans ) ) {
3318 $wpsmiliestrans = array(
3319 ':mrgreen:' => 'mrgreen.png',
3320 ':neutral:' => "\xf0\x9f\x98\x90",
3321 ':twisted:' => "\xf0\x9f\x98\x88",
3322 ':arrow:' => "\xe2\x9e\xa1",
3323 ':shock:' => "\xf0\x9f\x98\xaf",
3324 ':smile:' => "\xf0\x9f\x99\x82",
3325 ':???:' => "\xf0\x9f\x98\x95",
3326 ':cool:' => "\xf0\x9f\x98\x8e",
3327 ':evil:' => "\xf0\x9f\x91\xbf",
3328 ':grin:' => "\xf0\x9f\x98\x80",
3329 ':idea:' => "\xf0\x9f\x92\xa1",
3330 ':oops:' => "\xf0\x9f\x98\xb3",
3331 ':razz:' => "\xf0\x9f\x98\x9b",
3332 ':roll:' => "\xf0\x9f\x99\x84",
3333 ':wink:' => "\xf0\x9f\x98\x89",
3334 ':cry:' => "\xf0\x9f\x98\xa5",
3335 ':eek:' => "\xf0\x9f\x98\xae",
3336 ':lol:' => "\xf0\x9f\x98\x86",
3337 ':mad:' => "\xf0\x9f\x98\xa1",
3338 ':sad:' => "\xf0\x9f\x99\x81",
3339 '8-)' => "\xf0\x9f\x98\x8e",
3340 '8-O' => "\xf0\x9f\x98\xaf",
3341 ':-(' => "\xf0\x9f\x99\x81",
3342 ':-)' => "\xf0\x9f\x99\x82",
3343 ':-?' => "\xf0\x9f\x98\x95",
3344 ':-D' => "\xf0\x9f\x98\x80",
3345 ':-P' => "\xf0\x9f\x98\x9b",
3346 ':-o' => "\xf0\x9f\x98\xae",
3347 ':-x' => "\xf0\x9f\x98\xa1",
3348 ':-|' => "\xf0\x9f\x98\x90",
3349 ';-)' => "\xf0\x9f\x98\x89",
3350 // This one transformation breaks regular text with frequency.
3351 // '8)' => "\xf0\x9f\x98\x8e",
3352 '8O' => "\xf0\x9f\x98\xaf",
3353 ':(' => "\xf0\x9f\x99\x81",
3354 ':)' => "\xf0\x9f\x99\x82",
3355 ':?' => "\xf0\x9f\x98\x95",
3356 ':D' => "\xf0\x9f\x98\x80",
3357 ':P' => "\xf0\x9f\x98\x9b",
3358 ':o' => "\xf0\x9f\x98\xae",
3359 ':x' => "\xf0\x9f\x98\xa1",
3360 ':|' => "\xf0\x9f\x98\x90",
3361 ';)' => "\xf0\x9f\x98\x89",
3362 ':!:' => "\xe2\x9d\x97",
3363 ':?:' => "\xe2\x9d\x93",
3368 * Filters all the smilies.
3370 * This filter must be added before `smilies_init` is run, as
3371 * it is normally only run once to setup the smilies regex.
3375 * @param array $wpsmiliestrans List of the smilies.
3377 $wpsmiliestrans = apply_filters('smilies', $wpsmiliestrans);
3379 if (count($wpsmiliestrans) == 0) {
3384 * NOTE: we sort the smilies in reverse key order. This is to make sure
3385 * we match the longest possible smilie (:???: vs :?) as the regular
3386 * expression used below is first-match
3388 krsort($wpsmiliestrans);
3390 $spaces = wp_spaces_regexp();
3392 // Begin first "subpattern"
3393 $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
3396 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
3397 $firstchar = substr($smiley, 0, 1);
3398 $rest = substr($smiley, 1);
3401 if ($firstchar != $subchar) {
3402 if ($subchar != '') {
3403 $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern"
3404 $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
3406 $subchar = $firstchar;
3407 $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
3409 $wp_smiliessearch .= '|';
3411 $wp_smiliessearch .= preg_quote($rest, '/');
3414 $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
3419 * Merge user defined arguments into defaults array.
3421 * This function is used throughout WordPress to allow for both string or array
3422 * to be merged into another array.
3425 * @since 2.3.0 `$args` can now also be an object.
3427 * @param string|array|object $args Value to merge with $defaults.
3428 * @param array $defaults Optional. Array that serves as the defaults. Default empty.
3429 * @return array Merged user defined values with defaults.
3431 function wp_parse_args( $args, $defaults = '' ) {
3432 if ( is_object( $args ) )
3433 $r = get_object_vars( $args );
3434 elseif ( is_array( $args ) )
3437 wp_parse_str( $args, $r );
3439 if ( is_array( $defaults ) )
3440 return array_merge( $defaults, $r );
3445 * Clean up an array, comma- or space-separated list of IDs.
3449 * @param array|string $list List of ids.
3450 * @return array Sanitized array of IDs.
3452 function wp_parse_id_list( $list ) {
3453 if ( !is_array($list) )
3454 $list = preg_split('/[\s,]+/', $list);
3456 return array_unique(array_map('absint', $list));
3460 * Clean up an array, comma- or space-separated list of slugs.
3464 * @param array|string $list List of slugs.
3465 * @return array Sanitized array of slugs.
3467 function wp_parse_slug_list( $list ) {
3468 if ( ! is_array( $list ) ) {
3469 $list = preg_split( '/[\s,]+/', $list );
3472 foreach ( $list as $key => $value ) {
3473 $list[ $key ] = sanitize_title( $value );
3476 return array_unique( $list );
3480 * Extract a slice of an array, given a list of keys.
3484 * @param array $array The original array.
3485 * @param array $keys The list of keys.
3486 * @return array The array slice.
3488 function wp_array_slice_assoc( $array, $keys ) {
3490 foreach ( $keys as $key )
3491 if ( isset( $array[ $key ] ) )
3492 $slice[ $key ] = $array[ $key ];
3498 * Determines if the variable is a numeric-indexed array.
3502 * @param mixed $data Variable to check.
3503 * @return bool Whether the variable is a list.
3505 function wp_is_numeric_array( $data ) {
3506 if ( ! is_array( $data ) ) {
3510 $keys = array_keys( $data );
3511 $string_keys = array_filter( $keys, 'is_string' );
3512 return count( $string_keys ) === 0;
3516 * Filters a list of objects, based on a set of key => value arguments.
3519 * @since 4.7.0 Uses WP_List_Util class.
3521 * @param array $list An array of objects to filter
3522 * @param array $args Optional. An array of key => value arguments to match
3523 * against each object. Default empty array.
3524 * @param string $operator Optional. The logical operation to perform. 'or' means
3525 * only one element from the array needs to match; 'and'
3526 * means all elements must match; 'not' means no elements may
3527 * match. Default 'and'.
3528 * @param bool|string $field A field from the object to place instead of the entire object.
3530 * @return array A list of objects or object fields.
3532 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
3533 if ( ! is_array( $list ) ) {
3537 $util = new WP_List_Util( $list );
3539 $util->filter( $args, $operator );
3542 $util->pluck( $field );
3545 return $util->get_output();
3549 * Filters a list of objects, based on a set of key => value arguments.
3552 * @since 4.7.0 Uses WP_List_Util class.
3554 * @param array $list An array of objects to filter.
3555 * @param array $args Optional. An array of key => value arguments to match
3556 * against each object. Default empty array.
3557 * @param string $operator Optional. The logical operation to perform. 'AND' means
3558 * all elements from the array must match. 'OR' means only
3559 * one element needs to match. 'NOT' means no elements may
3560 * match. Default 'AND'.
3561 * @return array Array of found values.
3563 function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
3564 if ( ! is_array( $list ) ) {
3568 $util = new WP_List_Util( $list );
3569 return $util->filter( $args, $operator );
3573 * Pluck a certain field out of each object in a list.
3575 * This has the same functionality and prototype of
3576 * array_column() (PHP 5.5) but also supports objects.
3579 * @since 4.0.0 $index_key parameter added.
3580 * @since 4.7.0 Uses WP_List_Util class.
3582 * @param array $list List of objects or arrays
3583 * @param int|string $field Field from the object to place instead of the entire object
3584 * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
3586 * @return array Array of found values. If `$index_key` is set, an array of found values with keys
3587 * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
3588 * `$list` will be preserved in the results.
3590 function wp_list_pluck( $list, $field, $index_key = null ) {
3591 $util = new WP_List_Util( $list );
3592 return $util->pluck( $field, $index_key );
3596 * Sorts a list of objects, based on one or more orderby arguments.
3600 * @param array $list An array of objects to filter.
3601 * @param string|array $orderby Optional. Either the field name to order by or an array
3602 * of multiple orderby fields as $orderby => $order.
3603 * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
3605 * @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
3606 * @return array The sorted array.
3608 function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
3609 if ( ! is_array( $list ) ) {
3613 $util = new WP_List_Util( $list );
3614 return $util->sort( $orderby, $order, $preserve_keys );
3618 * Determines if Widgets library should be loaded.
3620 * Checks to make sure that the widgets library hasn't already been loaded.
3621 * If it hasn't, then it will load the widgets library and run an action hook.
3625 function wp_maybe_load_widgets() {
3627 * Filters whether to load the Widgets library.
3629 * Passing a falsey value to the filter will effectively short-circuit
3630 * the Widgets library from loading.
3634 * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
3637 if ( ! apply_filters( 'load_default_widgets', true ) ) {
3641 require_once( ABSPATH . WPINC . '/default-widgets.php' );
3643 add_action( '_admin_menu', 'wp_widgets_add_menu' );
3647 * Append the Widgets menu to the themes main menu.
3651 * @global array $submenu
3653 function wp_widgets_add_menu() {
3656 if ( ! current_theme_supports( 'widgets' ) )
3659 $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
3660 ksort( $submenu['themes.php'], SORT_NUMERIC );
3664 * Flush all output buffers for PHP 5.2.
3666 * Make sure all output buffers are flushed before our singletons are destroyed.
3670 function wp_ob_end_flush_all() {
3671 $levels = ob_get_level();
3672 for ($i=0; $i<$levels; $i++)
3677 * Load custom DB error or display WordPress DB error.
3679 * If a file exists in the wp-content directory named db-error.php, then it will
3680 * be loaded instead of displaying the WordPress DB error. If it is not found,
3681 * then the WordPress DB error will be displayed instead.
3683 * The WordPress DB error sets the HTTP status header to 500 to try to prevent
3684 * search engines from caching the message. Custom DB messages should do the
3687 * This function was backported to WordPress 2.3.2, but originally was added
3688 * in WordPress 2.5.0.
3692 * @global wpdb $wpdb WordPress database abstraction object.
3694 function dead_db() {
3697 wp_load_translations_early();
3699 // Load custom DB error template, if present.
3700 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
3701 require_once( WP_CONTENT_DIR . '/db-error.php' );
3705 // If installing or in the admin, provide the verbose message.
3706 if ( wp_installing() || defined( 'WP_ADMIN' ) )
3707 wp_die($wpdb->error);
3709 // Otherwise, be terse.
3710 status_header( 500 );
3712 header( 'Content-Type: text/html; charset=utf-8' );
3715 <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
3717 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3718 <title><?php _e( 'Database Error' ); ?></title>