(.+?)<\/title>/si', '', $content);
- $content = preg_replace('/(.+?)<\/category>/si', '', $content);
- $content = trim($content);
- return $content;
-}
+ wp_die( $html, __( 'WordPress Failure Notice' ), 403 );
+}
+
+/**
+ * Kill WordPress execution and display HTML message with error message.
+ *
+ * This function complements the `die()` PHP function. The difference is that
+ * HTML will be displayed to the user. It is recommended to use this function
+ * only when the execution should not continue any further. It is not recommended
+ * to call this function very often, and try to handle as many errors as possible
+ * silently or more gracefully.
+ *
+ * As a shorthand, the desired HTTP response code may be passed as an integer to
+ * the `$title` parameter (the default title would apply) or the `$args` parameter.
+ *
+ * @since 2.0.4
+ * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
+ * an integer to be used as the response code.
+ *
+ * @param string|WP_Error $message Optional. Error message. If this is a {@see WP_Error} object,
+ * the error's messages are used. Default empty.
+ * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
+ * error data with the key 'title' may be used to specify the title.
+ * If `$title` is an integer, then it is treated as the response
+ * code. Default empty.
+ * @param string|array|int $args {
+ * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
+ * as the response code. Default empty array.
+ *
+ * @type int $response The HTTP response code. Default 500.
+ * @type bool $back_link Whether to include a link to go back. Default false.
+ * @type string $text_direction The text direction. This is only useful internally, when WordPress
+ * is still loading and the site's locale is not set up yet. Accepts 'rtl'.
+ * Default is the value of {@see is_rtl()}.
+ * }
+ */
+function wp_die( $message = '', $title = '', $args = array() ) {
+
+ if ( is_int( $args ) ) {
+ $args = array( 'response' => $args );
+ } elseif ( is_int( $title ) ) {
+ $args = array( 'response' => $title );
+ $title = '';
+ }
-function debug_fopen($filename, $mode) {
- global $debug;
- if ( $debug == 1 ) {
- $fp = fopen($filename, $mode);
- return $fp;
+ if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
+ /**
+ * Filter callback for killing WordPress execution for AJAX requests.
+ *
+ * @since 3.4.0
+ *
+ * @param callable $function Callback function name.
+ */
+ $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
+ } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
+ /**
+ * Filter callback for killing WordPress execution for XML-RPC requests.
+ *
+ * @since 3.4.0
+ *
+ * @param callable $function Callback function name.
+ */
+ $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
} else {
- return false;
+ /**
+ * Filter callback for killing WordPress execution for all non-AJAX, non-XML-RPC requests.
+ *
+ * @since 3.0.0
+ *
+ * @param callable $function Callback function name.
+ */
+ $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
}
-}
-function debug_fwrite($fp, $string) {
- global $debug;
- if ( $debug == 1 ) {
- fwrite($fp, $string);
+ call_user_func( $function, $message, $title, $args );
+}
+
+/**
+ * Kill WordPress execution and display HTML message with error message.
+ *
+ * This is the default handler for wp_die if you want a custom one for your
+ * site then you can overload using the wp_die_handler filter in wp_die
+ *
+ * @since 3.0.0
+ * @access private
+ *
+ * @param string $message Error message.
+ * @param string $title Optional. Error title. Default empty.
+ * @param string|array $args Optional. Arguments to control behavior. Default empty array.
+ */
+function _default_wp_die_handler( $message, $title = '', $args = array() ) {
+ $defaults = array( 'response' => 500 );
+ $r = wp_parse_args($args, $defaults);
+
+ $have_gettext = function_exists('__');
+
+ if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
+ if ( empty( $title ) ) {
+ $error_data = $message->get_error_data();
+ if ( is_array( $error_data ) && isset( $error_data['title'] ) )
+ $title = $error_data['title'];
+ }
+ $errors = $message->get_error_messages();
+ switch ( count( $errors ) ) {
+ case 0 :
+ $message = '';
+ break;
+ case 1 :
+ $message = "
";
}
-}
-
-function spawn_pinger() {
- global $wpdb, $wp_version;
- $doping = false;
- if ( $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE TRIM(to_ping) != '' LIMIT 1") )
- $doping = true;
- if ( $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_pingme' OR meta_key = '_encloseme' LIMIT 1") )
- $doping = true;
-
- if ( substr(php_sapi_name(), 0, 3) == 'cgi' )
- return $doping;
-
- if ( $doping ) {
- $ping_url = get_settings('siteurl') .'/wp-admin/execute-pings.php';
- $parts = parse_url($ping_url);
- $argyle = @ fsockopen($parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01);
- if ( $argyle )
- fputs($argyle, "GET {$parts['path']}?time=".time()." HTTP/1.0\r\nHost: {$_SERVER['HTTP_HOST']}\r\nUser-Agent: WordPress/{$wp_version}\r\n\r\n");
- }
-}
-
-function do_enclose( $content, $post_ID ) {
- global $wp_version, $wpdb;
- include_once (ABSPATH . WPINC . '/class-IXR.php');
+ if ( ! did_action( 'admin_head' ) ) :
+ if ( !headers_sent() ) {
+ status_header( $r['response'] );
+ nocache_headers();
+ header( 'Content-Type: text/html; charset=utf-8' );
+ }
- $log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
- $post_links = array();
- debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
+ if ( empty($title) )
+ $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error';
- $pung = get_enclosed( $post_ID );
+ $text_direction = 'ltr';
+ if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
+ $text_direction = 'rtl';
+ elseif ( function_exists( 'is_rtl' ) && is_rtl() )
+ $text_direction = 'rtl';
+?>
+
+
+>
+
+
+
+
+
+
+
+
+
+
+
+ 5 )
- return false;
-
- $parts = parse_url( $url );
- $file = $parts['path'] . ($parts['query'] ? '?'.$parts['query'] : '');
- $host = $parts['host'];
- if ( !isset( $parts['port'] ) )
- $parts['port'] = 80;
-
- $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
-
- $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
- if ( !$fp )
- return false;
-
- $response = '';
- fputs( $fp, $head );
- while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
- $response .= fgets( $fp, 2048 );
- fclose( $fp );
- preg_match_all('/(.*?): (.*)\r/', $response, $matches);
- $count = count($matches[1]);
- for ( $i = 0; $i < $count; $i++) {
- $key = strtolower($matches[1][$i]);
- $headers["$key"] = $matches[2][$i];
+/**
+ * Kill WordPress execution and display XML message with error message.
+ *
+ * This is the handler for wp_die when processing XMLRPC requests.
+ *
+ * @since 3.2.0
+ * @access private
+ *
+ * @global wp_xmlrpc_server $wp_xmlrpc_server
+ *
+ * @param string $message Error message.
+ * @param string $title Optional. Error title. Default empty.
+ * @param string|array $args Optional. Arguments to control behavior. Default empty array.
+ */
+function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
+ global $wp_xmlrpc_server;
+ $defaults = array( 'response' => 500 );
+
+ $r = wp_parse_args($args, $defaults);
+
+ if ( $wp_xmlrpc_server ) {
+ $error = new IXR_Error( $r['response'] , $message);
+ $wp_xmlrpc_server->output( $error->getXml() );
}
-
- preg_match('/.*([0-9]{3}).*/', $response, $return);
- $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
-
- $code = $headers['response'];
- if ( ('302' == $code || '301' == $code) && isset($headers['location']) )
- return wp_get_http_headers( $headers['location'], ++$red );
-
- return $headers;
+ die();
}
-// Deprecated. Use the new post loop.
-function start_wp() {
- global $wp_query, $post;
-
- // Since the old style loop is being used, advance the query iterator here.
- $wp_query->next_post();
-
- setup_postdata($post);
+/**
+ * Kill WordPress ajax execution.
+ *
+ * This is the handler for wp_die when processing Ajax requests.
+ *
+ * @since 3.4.0
+ * @access private
+ *
+ * @param string $message Optional. Response to print. Default empty.
+ */
+function _ajax_wp_die_handler( $message = '' ) {
+ if ( is_scalar( $message ) )
+ die( (string) $message );
+ die( '0' );
+}
+
+/**
+ * Kill WordPress execution.
+ *
+ * This is the handler for wp_die when processing APP requests.
+ *
+ * @since 3.4.0
+ * @access private
+ *
+ * @param string $message Optional. Response to print. Default empty.
+ */
+function _scalar_wp_die_handler( $message = '' ) {
+ if ( is_scalar( $message ) )
+ die( (string) $message );
+ die();
}
-// Setup global post data.
-function setup_postdata($post) {
- global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
- global $pagenow;
-
- $id = $post->ID;
-
- $authordata = get_userdata($post->post_author);
-
- $day = mysql2date('d.m.y', $post->post_date);
- $currentmonth = mysql2date('m', $post->post_date);
- $numpages = 1;
- $page = get_query_var('page');
- if ( !$page )
- $page = 1;
- if ( is_single() || is_page() )
- $more = 1;
- $content = $post->post_content;
- if ( preg_match('//', $content) ) {
- if ( $page > 1 )
- $more = 1;
- $multipage = 1;
- $content = str_replace("\n\n", '', $content);
- $content = str_replace("\n", '', $content);
- $content = str_replace("\n", '', $content);
- $pages = explode('', $content);
- $numpages = count($pages);
+/**
+ * Encode a variable into JSON, with some sanity checks.
+ *
+ * @since 4.1.0
+ *
+ * @param mixed $data Variable (usually an array or object) to encode as JSON.
+ * @param int $options Optional. Options to be passed to json_encode(). Default 0.
+ * @param int $depth Optional. Maximum depth to walk through $data. Must be
+ * greater than 0. Default 512.
+ * @return string|false The JSON encoded string, or false if it cannot be encoded.
+ */
+function wp_json_encode( $data, $options = 0, $depth = 512 ) {
+ /*
+ * json_encode() has had extra params added over the years.
+ * $options was added in 5.3, and $depth in 5.5.
+ * We need to make sure we call it with the correct arguments.
+ */
+ if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
+ $args = array( $data, $options, $depth );
+ } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
+ $args = array( $data, $options );
} else {
- $pages[0] = $post->post_content;
- $multipage = 0;
+ $args = array( $data );
}
- return true;
-}
-// Setup global user vars. Used by set_current_user() for back compat.
-function setup_userdata($user_id = '') {
- global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
+ // Prepare the data for JSON serialization.
+ $data = _wp_json_prepare_data( $data );
- if ( '' == $user_id )
- $user = wp_get_current_user();
- else
- $user = new WP_User($user_id);
+ $json = @call_user_func_array( 'json_encode', $args );
- if ( 0 == $user->ID )
- return;
-
- $userdata = $user->data;
- $user_login = $user->user_login;
- $user_level = $user->user_level;
- $user_ID = $user->ID;
- $user_email = $user->user_email;
- $user_url = $user->user_url;
- $user_pass_md5 = md5($user->user_pass);
- $user_identity = $user->display_name;
-}
-
-function is_new_day() {
- global $day, $previousday;
- if ( $day != $previousday ) {
- return(1);
- } else {
- return(0);
+ // If json_encode() was successful, no need to do more sanity checking.
+ // ... unless we're in an old version of PHP, and json_encode() returned
+ // a string containing 'null'. Then we need to do more sanity checking.
+ if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) {
+ return $json;
}
-}
-
-// Filters: these are the core of WP's plugin architecture
-function merge_filters($tag) {
- global $wp_filter;
- if ( isset($wp_filter['all']) ) {
- foreach ($wp_filter['all'] as $priority => $functions) {
- if ( isset($wp_filter[$tag][$priority]) )
- $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
- else
- $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
- $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
- }
+ try {
+ $args[0] = _wp_json_sanity_check( $data, $depth );
+ } catch ( Exception $e ) {
+ return false;
}
- if ( isset($wp_filter[$tag]) )
- uksort( $wp_filter[$tag], "strnatcasecmp" );
-}
-
-function apply_filters($tag, $string) {
- global $wp_filter;
-
- $args = array_slice(func_get_args(), 2);
-
- merge_filters($tag);
-
- if ( !isset($wp_filter[$tag]) ) {
- return $string;
+ return call_user_func_array( 'json_encode', $args );
+}
+
+/**
+ * Perform sanity checks on data that shall be encoded to JSON.
+ *
+ * @ignore
+ * @since 4.1.0
+ * @access private
+ *
+ * @see wp_json_encode()
+ *
+ * @param mixed $data Variable (usually an array or object) to encode as JSON.
+ * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
+ * @return mixed The sanitized data that shall be encoded to JSON.
+ */
+function _wp_json_sanity_check( $data, $depth ) {
+ if ( $depth < 0 ) {
+ throw new Exception( 'Reached depth limit' );
}
- foreach ($wp_filter[$tag] as $priority => $functions) {
- if ( !is_null($functions) ) {
- foreach($functions as $function) {
-
- $all_args = array_merge(array($string), $args);
- $function_name = $function['function'];
- $accepted_args = $function['accepted_args'];
- if ( $accepted_args == 1 )
- $the_args = array($string);
- elseif ( $accepted_args > 1 )
- $the_args = array_slice($all_args, 0, $accepted_args);
- elseif ( $accepted_args == 0 )
- $the_args = NULL;
- else
- $the_args = $all_args;
-
- $string = call_user_func_array($function_name, $the_args);
+ if ( is_array( $data ) ) {
+ $output = array();
+ foreach ( $data as $id => $el ) {
+ // Don't forget to sanitize the ID!
+ if ( is_string( $id ) ) {
+ $clean_id = _wp_json_convert_string( $id );
+ } else {
+ $clean_id = $id;
}
- }
- }
- return $string;
-}
-
-function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
- global $wp_filter;
- // check that we don't already have the same filter at the same priority
- if ( isset($wp_filter[$tag]["$priority"]) ) {
- foreach($wp_filter[$tag]["$priority"] as $filter) {
- // uncomment if we want to match function AND accepted_args
- // if ( $filter == array($function, $accepted_args) ) {
- if ( $filter['function'] == $function_to_add ) {
- return true;
+ // Check the element type, so that we're only recursing if we really have to.
+ if ( is_array( $el ) || is_object( $el ) ) {
+ $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
+ } elseif ( is_string( $el ) ) {
+ $output[ $clean_id ] = _wp_json_convert_string( $el );
+ } else {
+ $output[ $clean_id ] = $el;
}
}
- }
-
- // So the format is wp_filter['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
- $wp_filter[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
- return true;
-}
-
-function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
- global $wp_filter;
+ } elseif ( is_object( $data ) ) {
+ $output = new stdClass;
+ foreach ( $data as $id => $el ) {
+ if ( is_string( $id ) ) {
+ $clean_id = _wp_json_convert_string( $id );
+ } else {
+ $clean_id = $id;
+ }
- // rebuild the list of filters
- if ( isset($wp_filter[$tag]["$priority"]) ) {
- $new_function_list = array();
- foreach($wp_filter[$tag]["$priority"] as $filter) {
- if ( $filter['function'] != $function_to_remove ) {
- $new_function_list[] = $filter;
+ if ( is_array( $el ) || is_object( $el ) ) {
+ $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
+ } elseif ( is_string( $el ) ) {
+ $output->$clean_id = _wp_json_convert_string( $el );
+ } else {
+ $output->$clean_id = $el;
}
}
- $wp_filter[$tag]["$priority"] = $new_function_list;
+ } elseif ( is_string( $data ) ) {
+ return _wp_json_convert_string( $data );
+ } else {
+ return $data;
}
- return true;
-}
-// The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
-
-function do_action($tag, $arg = '') {
- global $wp_filter;
- $extra_args = array_slice(func_get_args(), 2);
- if ( is_array($arg) )
- $args = array_merge($arg, $extra_args);
- else
- $args = array_merge(array($arg), $extra_args);
-
- merge_filters($tag);
-
- if ( !isset($wp_filter[$tag]) ) {
- return;
+ return $output;
+}
+
+/**
+ * Convert a string to UTF-8, so that it can be safely encoded to JSON.
+ *
+ * @ignore
+ * @since 4.1.0
+ * @access private
+ *
+ * @see _wp_json_sanity_check()
+ *
+ * @staticvar bool $use_mb
+ *
+ * @param string $string The string which is to be converted.
+ * @return string The checked string.
+ */
+function _wp_json_convert_string( $string ) {
+ static $use_mb = null;
+ if ( is_null( $use_mb ) ) {
+ $use_mb = function_exists( 'mb_convert_encoding' );
}
- foreach ($wp_filter[$tag] as $priority => $functions) {
- if ( !is_null($functions) ) {
- foreach($functions as $function) {
-
- $function_name = $function['function'];
- $accepted_args = $function['accepted_args'];
-
- if ( $accepted_args == 1 ) {
- if ( is_array($arg) )
- $the_args = $arg;
- else
- $the_args = array($arg);
- } elseif ( $accepted_args > 1 ) {
- $the_args = array_slice($args, 0, $accepted_args);
- } elseif ( $accepted_args == 0 ) {
- $the_args = NULL;
- } else {
- $the_args = $args;
- }
- $string = call_user_func_array($function_name, $the_args);
- }
+ if ( $use_mb ) {
+ $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
+ if ( $encoding ) {
+ return mb_convert_encoding( $string, 'UTF-8', $encoding );
+ } else {
+ return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
}
+ } else {
+ return wp_check_invalid_utf8( $string, true );
}
}
-function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
- add_filter($tag, $function_to_add, $priority, $accepted_args);
-}
-
-function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
- remove_filter($tag, $function_to_remove, $priority, $accepted_args);
-}
-
-function get_page_uri($page_id) {
- $page = get_page($page_id);
- $uri = urldecode($page->post_name);
-
- // A page cannot be it's own parent.
- if ( $page->post_parent == $page->ID )
- return $uri;
-
- while ($page->post_parent != 0) {
- $page = get_page($page->post_parent);
- $uri = urldecode($page->post_name) . "/" . $uri;
+/**
+ * Prepares response data to be serialized to JSON.
+ *
+ * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
+ *
+ * @ignore
+ * @since 4.4.0
+ * @access private
+ *
+ * @param mixed $data Native representation.
+ * @return bool|int|float|null|string|array Data ready for `json_encode()`.
+ */
+function _wp_json_prepare_data( $data ) {
+ if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
+ return $data;
}
- return $uri;
-}
-
-function get_posts($args) {
- global $wpdb;
- parse_str($args, $r);
- if ( !isset($r['numberposts']) )
- $r['numberposts'] = 5;
- if ( !isset($r['offset']) )
- $r['offset'] = 0;
- if ( !isset($r['category']) )
- $r['category'] = '';
- if ( !isset($r['orderby']) )
- $r['orderby'] = 'post_date';
- if ( !isset($r['order']) )
- $r['order'] = 'DESC';
-
- $now = current_time('mysql');
-
- $posts = $wpdb->get_results(
- "SELECT DISTINCT * FROM $wpdb->posts " .
- ( empty( $r['category'] ) ? "" : ", $wpdb->post2cat " ) .
- " WHERE post_date <= '$now' AND (post_status = 'publish') ".
- ( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $r['category']. " " ) .
- " GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . " LIMIT " . $r['offset'] . ',' . $r['numberposts'] );
-
- update_post_caches($posts);
-
- return $posts;
-}
-
-function &query_posts($query) {
- global $wp_query;
- return $wp_query->query($query);
-}
-
-function update_post_cache(&$posts) {
- global $post_cache;
-
- if ( !$posts )
- return;
-
- for ($i = 0; $i < count($posts); $i++) {
- $post_cache[$posts[$i]->ID] = &$posts[$i];
- }
-}
-
-function clean_post_cache($id) {
- global $post_cache;
-
- if ( isset( $post_cache[$id] ) )
- unset( $post_cache[$id] );
-}
+ switch ( gettype( $data ) ) {
+ case 'boolean':
+ case 'integer':
+ case 'double':
+ case 'string':
+ case 'NULL':
+ // These values can be passed through.
+ return $data;
+
+ case 'array':
+ // Arrays must be mapped in case they also return objects.
+ return array_map( '_wp_json_prepare_data', $data );
+
+ case 'object':
+ // If this is an incomplete object (__PHP_Incomplete_Class), bail.
+ if ( ! is_object( $data ) ) {
+ return null;
+ }
-function update_page_cache(&$pages) {
- global $page_cache;
+ if ( $data instanceof JsonSerializable ) {
+ $data = $data->jsonSerialize();
+ } else {
+ $data = get_object_vars( $data );
+ }
- if ( !$pages )
- return;
+ // Now, pass the array (or whatever was returned from jsonSerialize through).
+ return _wp_json_prepare_data( $data );
- for ($i = 0; $i < count($pages); $i++) {
- $page_cache[$pages[$i]->ID] = &$pages[$i];
- wp_cache_add($pages[$i]->ID, $pages[$i], 'pages');
+ default:
+ return null;
}
}
+/**
+ * Send a JSON response back to an Ajax request.
+ *
+ * @since 3.5.0
+ *
+ * @param mixed $response Variable (usually an array or object) to encode as JSON,
+ * then print and die.
+ */
+function wp_send_json( $response ) {
+ @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
+ echo wp_json_encode( $response );
+ if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
+ wp_die();
+ else
+ die;
+}
+
+/**
+ * Send a JSON response back to an Ajax request, indicating success.
+ *
+ * @since 3.5.0
+ *
+ * @param mixed $data Data to encode as JSON, then print and die.
+ */
+function wp_send_json_success( $data = null ) {
+ $response = array( 'success' => true );
+
+ if ( isset( $data ) )
+ $response['data'] = $data;
+
+ wp_send_json( $response );
+}
+
+/**
+ * Send a JSON response back to an Ajax request, indicating failure.
+ *
+ * If the `$data` parameter is a {@see WP_Error} object, the errors
+ * within the object are processed and output as an array of error
+ * codes and corresponding messages. All other types are output
+ * without further processing.
+ *
+ * @since 3.5.0
+ * @since 4.1.0 The `$data` parameter is now processed if a {@see WP_Error}
+ * object is passed in.
+ *
+ * @param mixed $data Data to encode as JSON, then print and die.
+ */
+function wp_send_json_error( $data = null ) {
+ $response = array( 'success' => false );
+
+ if ( isset( $data ) ) {
+ if ( is_wp_error( $data ) ) {
+ $result = array();
+ foreach ( $data->errors as $code => $messages ) {
+ foreach ( $messages as $message ) {
+ $result[] = array( 'code' => $code, 'message' => $message );
+ }
+ }
-function clean_page_cache($id) {
- global $page_cache;
-
- if ( isset( $page_cache[$id] ) )
- unset( $page_cache[$id] );
-}
-
-function update_post_category_cache($post_ids) {
- global $wpdb, $category_cache;
-
- if ( empty($post_ids) )
- return;
-
- if ( is_array($post_ids) )
- $post_ids = implode(',', $post_ids);
-
- $dogs = $wpdb->get_results("SELECT post_id, category_id FROM $wpdb->post2cat WHERE post_id IN ($post_ids)");
-
- if ( empty($dogs) )
- return;
-
- foreach ($dogs as $catt)
- $category_cache[$catt->post_id][$catt->category_id] = &get_category($catt->category_id);
-}
-
-function update_post_caches(&$posts) {
- global $post_cache, $category_cache, $comment_count_cache, $post_meta_cache;
- global $wpdb;
-
- // No point in doing all this work if we didn't match any posts.
- if ( !$posts )
- return;
-
- // Get the categories for all the posts
- for ($i = 0; $i < count($posts); $i++) {
- $post_id_array[] = $posts[$i]->ID;
- $post_cache[$posts[$i]->ID] = &$posts[$i];
- $comment_count_cache[$posts[$i]->ID] = $posts[$i]->comment_count;
- }
-
- $post_id_list = implode(',', $post_id_array);
-
- update_post_category_cache($post_id_list);
-
- // Get post-meta info
- if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN($post_id_list) ORDER BY post_id, meta_key", ARRAY_A) ) {
- // Change from flat structure to hierarchical:
- $post_meta_cache = array();
- foreach ($meta_list as $metarow) {
- $mpid = (int) $metarow['post_id'];
- $mkey = $metarow['meta_key'];
- $mval = $metarow['meta_value'];
-
- // Force subkeys to be array type:
- if ( !isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]) )
- $post_meta_cache[$mpid] = array();
- if ( !isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]) )
- $post_meta_cache[$mpid]["$mkey"] = array();
-
- // Add a value to the current pid/key:
- $post_meta_cache[$mpid][$mkey][] = $mval;
+ $response['data'] = $result;
+ } else {
+ $response['data'] = $data;
}
}
-}
-
-function update_category_cache() {
- return true;
-}
-
-function wp_head() {
- do_action('wp_head');
-}
-
-function wp_footer() {
- do_action('wp_footer');
-}
-
-function is_single ($post = '') {
- global $wp_query;
-
- if ( !$wp_query->is_single )
- return false;
-
- if ( empty( $post) )
- return true;
-
- $post_obj = $wp_query->get_queried_object();
-
- if ( $post == $post_obj->ID )
- return true;
- elseif ( $post == $post_obj->post_title )
- return true;
- elseif ( $post == $post_obj->post_name )
- return true;
-
- return false;
-}
-
-function is_page ($page = '') {
- global $wp_query;
-
- if ( !$wp_query->is_page )
- return false;
-
- if ( empty($page) )
- return true;
-
- $page_obj = $wp_query->get_queried_object();
-
- if ( $page == $page_obj->ID )
- return true;
- elseif ( $page == $page_obj->post_title )
- return true;
- else if ( $page == $page_obj->post_name )
- return true;
-
- return false;
-}
-
-function is_attachment () {
- global $wp_query;
-
- return $wp_query->is_attachment;
-}
-
-function is_preview() {
- global $wp_query;
-
- return $wp_query->is_preview;
-}
-
-function is_archive () {
- global $wp_query;
-
- return $wp_query->is_archive;
-}
-
-function is_date () {
- global $wp_query;
-
- return $wp_query->is_date;
-}
-
-function is_year () {
- global $wp_query;
-
- return $wp_query->is_year;
-}
-
-function is_month () {
- global $wp_query;
-
- return $wp_query->is_month;
-}
-
-function is_day () {
- global $wp_query;
-
- return $wp_query->is_day;
-}
-
-function is_time () {
- global $wp_query;
-
- return $wp_query->is_time;
-}
-
-function is_author ($author = '') {
- global $wp_query;
-
- if ( !$wp_query->is_author )
- return false;
-
- if ( empty($author) )
- return true;
-
- $author_obj = $wp_query->get_queried_object();
-
- if ( $author == $author_obj->ID )
- return true;
- elseif ( $author == $author_obj->nickname )
- return true;
- elseif ( $author == $author_obj->user_nicename )
- return true;
- return false;
-}
-
-function is_category ($category = '') {
- global $wp_query;
-
- if ( !$wp_query->is_category )
- return false;
-
- if ( empty($category) )
- return true;
-
- $cat_obj = $wp_query->get_queried_object();
-
- if ( $category == $cat_obj->cat_ID )
- return true;
- else if ( $category == $cat_obj->cat_name )
- return true;
- elseif ( $category == $cat_obj->category_nicename )
- return true;
-
- return false;
-}
-
-function is_search () {
- global $wp_query;
-
- return $wp_query->is_search;
-}
-
-function is_feed () {
- global $wp_query;
-
- return $wp_query->is_feed;
-}
-
-function is_trackback () {
- global $wp_query;
-
- return $wp_query->is_trackback;
-}
-
-function is_admin () {
- global $wp_query;
-
- return ( $wp_query->is_admin || strstr($_SERVER['REQUEST_URI'], 'wp-admin/') );
-}
-
-function is_home () {
- global $wp_query;
-
- return $wp_query->is_home;
-}
-
-function is_404 () {
- global $wp_query;
-
- return $wp_query->is_404;
-}
-
-function is_comments_popup () {
- global $wp_query;
-
- return $wp_query->is_comments_popup;
-}
-
-function is_paged () {
- global $wp_query;
-
- return $wp_query->is_paged;
-}
-
-function in_the_loop() {
- global $wp_query;
-
- return $wp_query->in_the_loop;
-}
-
-function get_query_var($var) {
- global $wp_query;
-
- return $wp_query->get($var);
-}
-
-function have_posts() {
- global $wp_query;
-
- return $wp_query->have_posts();
-}
-
-function rewind_posts() {
- global $wp_query;
-
- return $wp_query->rewind_posts();
-}
-
-function the_post() {
- global $wp_query;
-
- $wp_query->the_post();
-}
-
-function get_theme_root() {
- return apply_filters('theme_root', ABSPATH . "wp-content/themes");
-}
-
-function get_theme_root_uri() {
- return apply_filters('theme_root_uri', get_settings('siteurl') . "/wp-content/themes", get_settings('siteurl'));
-}
-
-function get_stylesheet() {
- return apply_filters('stylesheet', get_settings('stylesheet'));
-}
-
-function get_stylesheet_directory() {
- $stylesheet = get_stylesheet();
- $stylesheet_dir = get_theme_root() . "/$stylesheet";
- return apply_filters('stylesheet_directory', $stylesheet_dir, $stylesheet);
-}
-
-function get_stylesheet_directory_uri() {
- $stylesheet = rawurlencode( get_stylesheet() );
- $stylesheet_dir_uri = get_theme_root_uri() . "/$stylesheet";
- return apply_filters('stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet);
-}
-
-function get_stylesheet_uri() {
- $stylesheet_dir_uri = get_stylesheet_directory_uri();
- $stylesheet_uri = $stylesheet_dir_uri . "/style.css";
- return apply_filters('stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri);
-}
-
-function get_template() {
- $template = get_settings('template');
- if (!file_exists(get_theme_root() . "/$template")) { //works for dirs too
- update_option('template', 'default');
- update_option('stylesheet', 'default');
- }
- return apply_filters('template', get_settings('template'));
-}
-
-function get_template_directory() {
- $template = get_template();
- $template_dir = get_theme_root() . "/$template";
- return apply_filters('template_directory', $template_dir, $template);
-}
-
-function get_template_directory_uri() {
- $template = get_template();
- $template_dir_uri = get_theme_root_uri() . "/$template";
- return apply_filters('template_directory_uri', $template_dir_uri, $template);
-}
-
-function get_theme_data($theme_file) {
- $theme_data = implode('', file($theme_file));
- preg_match("|Theme Name:(.*)|i", $theme_data, $theme_name);
- preg_match("|Theme URI:(.*)|i", $theme_data, $theme_uri);
- preg_match("|Description:(.*)|i", $theme_data, $description);
- preg_match("|Author:(.*)|i", $theme_data, $author_name);
- preg_match("|Author URI:(.*)|i", $theme_data, $author_uri);
- preg_match("|Template:(.*)|i", $theme_data, $template);
- if ( preg_match("|Version:(.*)|i", $theme_data, $version) )
- $version = trim($version[1]);
- else
- $version ='';
- if ( preg_match("|Status:(.*)|i", $theme_data, $status) )
- $status = trim($status[1]);
- else
- $status = 'publish';
-
- $description = wptexturize(trim($description[1]));
-
- $name = $theme_name[1];
- $name = trim($name);
- $theme = $name;
+ wp_send_json( $response );
+}
+
+/**
+ * Retrieve the WordPress home page URL.
+ *
+ * If the constant named 'WP_HOME' exists, then it will be used and returned
+ * by the function. This can be used to counter the redirection on your local
+ * development environment.
+ *
+ * @since 2.2.0
+ * @access private
+ *
+ * @see WP_HOME
+ *
+ * @param string $url URL for the home location.
+ * @return string Homepage location.
+ */
+function _config_wp_home( $url = '' ) {
+ if ( defined( 'WP_HOME' ) )
+ return untrailingslashit( WP_HOME );
+ return $url;
+}
+
+/**
+ * Retrieve the WordPress site URL.
+ *
+ * If the constant named 'WP_SITEURL' is defined, then the value in that
+ * constant will always be returned. This can be used for debugging a site
+ * on your localhost while not having to change the database to your URL.
+ *
+ * @since 2.2.0
+ * @access private
+ *
+ * @see WP_SITEURL
+ *
+ * @param string $url URL to set the WordPress site location.
+ * @return string The WordPress Site URL.
+ */
+function _config_wp_siteurl( $url = '' ) {
+ if ( defined( 'WP_SITEURL' ) )
+ return untrailingslashit( WP_SITEURL );
+ return $url;
+}
+
+/**
+ * Set the localized direction for MCE plugin.
+ *
+ * Will only set the direction to 'rtl', if the WordPress locale has
+ * the text direction set to 'rtl'.
+ *
+ * Fills in the 'directionality' setting, enables the 'directionality'
+ * plugin, and adds the 'ltr' button to 'toolbar1', formerly
+ * 'theme_advanced_buttons1' array keys. These keys are then returned
+ * in the $input (TinyMCE settings) array.
+ *
+ * @since 2.1.0
+ * @access private
+ *
+ * @param array $input MCE settings array.
+ * @return array Direction set for 'rtl', if needed by locale.
+ */
+function _mce_set_direction( $input ) {
+ if ( is_rtl() ) {
+ $input['directionality'] = 'rtl';
+
+ if ( ! empty( $input['plugins'] ) && strpos( $input['plugins'], 'directionality' ) === false ) {
+ $input['plugins'] .= ',directionality';
+ }
- if ( '' == $author_uri[1] ) {
- $author = trim($author_name[1]);
- } else {
- $author = '' . trim($author_name[1]) . '';
+ if ( ! empty( $input['toolbar1'] ) && ! preg_match( '/\bltr\b/', $input['toolbar1'] ) ) {
+ $input['toolbar1'] .= ',ltr';
+ }
}
- return array('Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status);
-}
-
-function get_themes() {
- global $wp_themes;
- global $wp_broken_themes;
-
- if ( isset($wp_themes) )
- return $wp_themes;
-
- $themes = array();
- $wp_broken_themes = array();
- $theme_root = get_theme_root();
- $theme_loc = str_replace(ABSPATH, '', $theme_root);
+ return $input;
+}
+
+
+/**
+ * Convert smiley code to the icon graphic file equivalent.
+ *
+ * You can turn off smilies, by going to the write setting screen and unchecking
+ * the box, or by setting 'use_smilies' option to false or removing the option.
+ *
+ * Plugins may override the default smiley list by setting the $wpsmiliestrans
+ * to an array, with the key the code the blogger types in and the value the
+ * image file.
+ *
+ * The $wp_smiliessearch global is for the regular expression and is set each
+ * time the function is called.
+ *
+ * The full list of smilies can be found in the function and won't be listed in
+ * the description. Probably should create a Codex page for it, so that it is
+ * available.
+ *
+ * @global array $wpsmiliestrans
+ * @global array $wp_smiliessearch
+ *
+ * @since 2.2.0
+ */
+function smilies_init() {
+ global $wpsmiliestrans, $wp_smiliessearch;
+
+ // don't bother setting up smilies if they are disabled
+ if ( !get_option( 'use_smilies' ) )
+ return;
- // Files in wp-content/themes directory
- $themes_dir = @ dir($theme_root);
- if ( $themes_dir ) {
- while(($theme_dir = $themes_dir->read()) !== false) {
- if ( is_dir($theme_root . '/' . $theme_dir) && is_readable($theme_root . '/' . $theme_dir) ) {
- if ( $theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS' ) {
- continue;
- }
- $stylish_dir = @ dir($theme_root . '/' . $theme_dir);
- $found_stylesheet = false;
- while (($theme_file = $stylish_dir->read()) !== false) {
- if ( $theme_file == 'style.css' ) {
- $theme_files[] = $theme_dir . '/' . $theme_file;
- $found_stylesheet = true;
- break;
- }
- }
- if ( !$found_stylesheet ) {
- $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.'));
- }
- }
- }
+ if ( !isset( $wpsmiliestrans ) ) {
+ $wpsmiliestrans = array(
+ ':mrgreen:' => 'mrgreen.png',
+ ':neutral:' => "\xf0\x9f\x98\x90",
+ ':twisted:' => "\xf0\x9f\x98\x88",
+ ':arrow:' => "\xe2\x9e\xa1",
+ ':shock:' => "\xf0\x9f\x98\xaf",
+ ':smile:' => 'simple-smile.png',
+ ':???:' => "\xf0\x9f\x98\x95",
+ ':cool:' => "\xf0\x9f\x98\x8e",
+ ':evil:' => "\xf0\x9f\x91\xbf",
+ ':grin:' => "\xf0\x9f\x98\x80",
+ ':idea:' => "\xf0\x9f\x92\xa1",
+ ':oops:' => "\xf0\x9f\x98\xb3",
+ ':razz:' => "\xf0\x9f\x98\x9b",
+ ':roll:' => 'rolleyes.png',
+ ':wink:' => "\xf0\x9f\x98\x89",
+ ':cry:' => "\xf0\x9f\x98\xa5",
+ ':eek:' => "\xf0\x9f\x98\xae",
+ ':lol:' => "\xf0\x9f\x98\x86",
+ ':mad:' => "\xf0\x9f\x98\xa1",
+ ':sad:' => 'frownie.png',
+ '8-)' => "\xf0\x9f\x98\x8e",
+ '8-O' => "\xf0\x9f\x98\xaf",
+ ':-(' => 'frownie.png',
+ ':-)' => 'simple-smile.png',
+ ':-?' => "\xf0\x9f\x98\x95",
+ ':-D' => "\xf0\x9f\x98\x80",
+ ':-P' => "\xf0\x9f\x98\x9b",
+ ':-o' => "\xf0\x9f\x98\xae",
+ ':-x' => "\xf0\x9f\x98\xa1",
+ ':-|' => "\xf0\x9f\x98\x90",
+ ';-)' => "\xf0\x9f\x98\x89",
+ // This one transformation breaks regular text with frequency.
+ // '8)' => "\xf0\x9f\x98\x8e",
+ '8O' => "\xf0\x9f\x98\xaf",
+ ':(' => 'frownie.png',
+ ':)' => 'simple-smile.png',
+ ':?' => "\xf0\x9f\x98\x95",
+ ':D' => "\xf0\x9f\x98\x80",
+ ':P' => "\xf0\x9f\x98\x9b",
+ ':o' => "\xf0\x9f\x98\xae",
+ ':x' => "\xf0\x9f\x98\xa1",
+ ':|' => "\xf0\x9f\x98\x90",
+ ';)' => "\xf0\x9f\x98\x89",
+ ':!:' => "\xe2\x9d\x97",
+ ':?:' => "\xe2\x9d\x93",
+ );
}
- if ( !$themes_dir || !$theme_files ) {
- return $themes;
+ if (count($wpsmiliestrans) == 0) {
+ return;
}
- sort($theme_files);
-
- foreach($theme_files as $theme_file) {
- if ( ! is_readable("$theme_root/$theme_file") ) {
- $wp_broken_themes[$theme_file] = array('Name' => $theme_file, 'Title' => $theme_file, 'Description' => __('File not readable.'));
- continue;
- }
-
- $theme_data = get_theme_data("$theme_root/$theme_file");
+ /*
+ * NOTE: we sort the smilies in reverse key order. This is to make sure
+ * we match the longest possible smilie (:???: vs :?) as the regular
+ * expression used below is first-match
+ */
+ krsort($wpsmiliestrans);
- $name = $theme_data['Name'];
- $title = $theme_data['Title'];
- $description = wptexturize($theme_data['Description']);
- $version = $theme_data['Version'];
- $author = $theme_data['Author'];
- $template = $theme_data['Template'];
- $stylesheet = dirname($theme_file);
+ $spaces = wp_spaces_regexp();
- foreach (array('png', 'gif', 'jpg', 'jpeg') as $ext) {
- if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) {
- $screenshot = "screenshot.$ext";
- break;
- }
- }
+ // Begin first "subpattern"
+ $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
- if ( empty($name) ) {
- $name = dirname($theme_file);
- $title = $name;
- }
-
- if ( empty($template) ) {
- if ( file_exists(dirname("$theme_root/$theme_file/index.php")) ) {
- $template = dirname($theme_file);
- } else {
- continue;
+ $subchar = '';
+ foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
+ $firstchar = substr($smiley, 0, 1);
+ $rest = substr($smiley, 1);
+
+ // new subpattern?
+ if ($firstchar != $subchar) {
+ if ($subchar != '') {
+ $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern"
+ $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
}
+ $subchar = $firstchar;
+ $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
+ } else {
+ $wp_smiliessearch .= '|';
}
+ $wp_smiliessearch .= preg_quote($rest, '/');
+ }
- $template = trim($template);
+ $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
+
+}
+
+/**
+ * Merge user defined arguments into defaults array.
+ *
+ * This function is used throughout WordPress to allow for both string or array
+ * to be merged into another array.
+ *
+ * @since 2.2.0
+ *
+ * @param string|array $args Value to merge with $defaults
+ * @param array $defaults Optional. Array that serves as the defaults. Default empty.
+ * @return array Merged user defined values with defaults.
+ */
+function wp_parse_args( $args, $defaults = '' ) {
+ if ( is_object( $args ) )
+ $r = get_object_vars( $args );
+ elseif ( is_array( $args ) )
+ $r =& $args;
+ else
+ wp_parse_str( $args, $r );
- if ( !file_exists("$theme_root/$template/index.php") ) {
- $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
- continue;
- }
+ if ( is_array( $defaults ) )
+ return array_merge( $defaults, $r );
+ return $r;
+}
- $stylesheet_files = array();
- $stylesheet_dir = @ dir("$theme_root/$stylesheet");
- if ( $stylesheet_dir ) {
- while(($file = $stylesheet_dir->read()) !== false) {
- if ( !preg_match('|^\.+$|', $file) && preg_match('|\.css$|', $file) )
- $stylesheet_files[] = "$theme_loc/$stylesheet/$file";
- }
+/**
+ * Clean up an array, comma- or space-separated list of IDs.
+ *
+ * @since 3.0.0
+ *
+ * @param array|string $list List of ids.
+ * @return array Sanitized array of IDs.
+ */
+function wp_parse_id_list( $list ) {
+ if ( !is_array($list) )
+ $list = preg_split('/[\s,]+/', $list);
+
+ return array_unique(array_map('absint', $list));
+}
+
+/**
+ * Extract a slice of an array, given a list of keys.
+ *
+ * @since 3.1.0
+ *
+ * @param array $array The original array.
+ * @param array $keys The list of keys.
+ * @return array The array slice.
+ */
+function wp_array_slice_assoc( $array, $keys ) {
+ $slice = array();
+ foreach ( $keys as $key )
+ if ( isset( $array[ $key ] ) )
+ $slice[ $key ] = $array[ $key ];
+
+ return $slice;
+}
+
+/**
+ * Determines if the variable is a numeric-indexed array.
+ *
+ * @since 4.4.0
+ *
+ * @param mixed $data Variable to check.
+ * @return bool Whether the variable is a list.
+ */
+function wp_is_numeric_array( $data ) {
+ if ( ! is_array( $data ) ) {
+ return false;
+ }
+
+ $keys = array_keys( $data );
+ $string_keys = array_filter( $keys, 'is_string' );
+ return count( $string_keys ) === 0;
+}
+
+/**
+ * Filters a list of objects, based on a set of key => value arguments.
+ *
+ * @since 3.0.0
+ *
+ * @param array $list An array of objects to filter
+ * @param array $args Optional. An array of key => value arguments to match
+ * against each object. Default empty array.
+ * @param string $operator Optional. The logical operation to perform. 'or' means
+ * only one element from the array needs to match; 'and'
+ * means all elements must match. Default 'and'.
+ * @param bool|string $field A field from the object to place instead of the entire object.
+ * Default false.
+ * @return array A list of objects or object fields.
+ */
+function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
+ if ( ! is_array( $list ) )
+ return array();
+
+ $list = wp_list_filter( $list, $args, $operator );
+
+ if ( $field )
+ $list = wp_list_pluck( $list, $field );
+
+ return $list;
+}
+
+/**
+ * Filters a list of objects, based on a set of key => value arguments.
+ *
+ * @since 3.1.0
+ *
+ * @param array $list An array of objects to filter.
+ * @param array $args Optional. An array of key => value arguments to match
+ * against each object. Default empty array.
+ * @param string $operator Optional. The logical operation to perform. 'AND' means
+ * all elements from the array must match. 'OR' means only
+ * one element needs to match. 'NOT' means no elements may
+ * match. Default 'AND'.
+ * @return array Array of found values.
+ */
+function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
+ if ( ! is_array( $list ) )
+ return array();
+
+ if ( empty( $args ) )
+ return $list;
+
+ $operator = strtoupper( $operator );
+ $count = count( $args );
+ $filtered = array();
+
+ foreach ( $list as $key => $obj ) {
+ $to_match = (array) $obj;
+
+ $matched = 0;
+ foreach ( $args as $m_key => $m_value ) {
+ if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
+ $matched++;
}
- $template_files = array();
- $template_dir = @ dir("$theme_root/$template");
- if ( $template_dir ) {
- while(($file = $template_dir->read()) !== false) {
- if ( !preg_match('|^\.+$|', $file) && preg_match('|\.php$|', $file) )
- $template_files[] = "$theme_loc/$template/$file";
- }
+ if ( ( 'AND' == $operator && $matched == $count )
+ || ( 'OR' == $operator && $matched > 0 )
+ || ( 'NOT' == $operator && 0 == $matched ) ) {
+ $filtered[$key] = $obj;
}
+ }
- $template_dir = dirname($template_files[0]);
- $stylesheet_dir = dirname($stylesheet_files[0]);
-
- if ( empty($template_dir) )
- $template_dir = '/';
- if ( empty($stylesheet_dir) )
- $stylesheet_dir = '/';
-
- // Check for theme name collision. This occurs if a theme is copied to
- // a new theme directory and the theme header is not updated. Whichever
- // theme is first keeps the name. Subsequent themes get a suffix applied.
- // The Default and Classic themes always trump their pretenders.
- if ( isset($themes[$name]) ) {
- if ( ('WordPress Default' == $name || 'WordPress Classic' == $name) &&
- ('default' == $stylesheet || 'classic' == $stylesheet) ) {
- // If another theme has claimed to be one of our default themes, move
- // them aside.
- $suffix = $themes[$name]['Stylesheet'];
- $new_name = "$name/$suffix";
- $themes[$new_name] = $themes[$name];
- $themes[$new_name]['Name'] = $new_name;
+ return $filtered;
+}
+
+/**
+ * Pluck a certain field out of each object in a list.
+ *
+ * This has the same functionality and prototype of
+ * array_column() (PHP 5.5) but also supports objects.
+ *
+ * @since 3.1.0
+ * @since 4.0.0 $index_key parameter added.
+ *
+ * @param array $list List of objects or arrays
+ * @param int|string $field Field from the object to place instead of the entire object
+ * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
+ * Default null.
+ * @return array Array of found values. If `$index_key` is set, an array of found values with keys
+ * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
+ * `$list` will be preserved in the results.
+ */
+function wp_list_pluck( $list, $field, $index_key = null ) {
+ if ( ! $index_key ) {
+ /*
+ * This is simple. Could at some point wrap array_column()
+ * if we knew we had an array of arrays.
+ */
+ foreach ( $list as $key => $value ) {
+ if ( is_object( $value ) ) {
+ $list[ $key ] = $value->$field;
} else {
- $name = "$name/$stylesheet";
+ $list[ $key ] = $value[ $field ];
}
}
-
- $themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template, 'Stylesheet' => $stylesheet, 'Template Files' => $template_files, 'Stylesheet Files' => $stylesheet_files, 'Template Dir' => $template_dir, 'Stylesheet Dir' => $stylesheet_dir, 'Status' => $theme_data['Status'], 'Screenshot' => $screenshot);
+ return $list;
}
- // Resolve theme dependencies.
- $theme_names = array_keys($themes);
-
- foreach ($theme_names as $theme_name) {
- $themes[$theme_name]['Parent Theme'] = '';
- if ( $themes[$theme_name]['Stylesheet'] != $themes[$theme_name]['Template'] ) {
- foreach ($theme_names as $parent_theme_name) {
- if ( ($themes[$parent_theme_name]['Stylesheet'] == $themes[$parent_theme_name]['Template']) && ($themes[$parent_theme_name]['Template'] == $themes[$theme_name]['Template']) ) {
- $themes[$theme_name]['Parent Theme'] = $themes[$parent_theme_name]['Name'];
- break;
- }
+ /*
+ * When index_key is not set for a particular item, push the value
+ * to the end of the stack. This is how array_column() behaves.
+ */
+ $newlist = array();
+ foreach ( $list as $value ) {
+ if ( is_object( $value ) ) {
+ if ( isset( $value->$index_key ) ) {
+ $newlist[ $value->$index_key ] = $value->$field;
+ } else {
+ $newlist[] = $value->$field;
+ }
+ } else {
+ if ( isset( $value[ $index_key ] ) ) {
+ $newlist[ $value[ $index_key ] ] = $value[ $field ];
+ } else {
+ $newlist[] = $value[ $field ];
}
}
}
- $wp_themes = $themes;
+ return $newlist;
+}
+
+/**
+ * Determines if Widgets library should be loaded.
+ *
+ * Checks to make sure that the widgets library hasn't already been loaded.
+ * If it hasn't, then it will load the widgets library and run an action hook.
+ *
+ * @since 2.2.0
+ */
+function wp_maybe_load_widgets() {
+ /**
+ * Filter whether to load the Widgets library.
+ *
+ * Passing a falsey value to the filter will effectively short-circuit
+ * the Widgets library from loading.
+ *
+ * @since 2.8.0
+ *
+ * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
+ * Default true.
+ */
+ if ( ! apply_filters( 'load_default_widgets', true ) ) {
+ return;
+ }
+
+ require_once( ABSPATH . WPINC . '/default-widgets.php' );
- return $themes;
+ add_action( '_admin_menu', 'wp_widgets_add_menu' );
}
-function get_theme($theme) {
- $themes = get_themes();
+/**
+ * Append the Widgets menu to the themes main menu.
+ *
+ * @since 2.2.0
+ *
+ * @global array $submenu
+ */
+function wp_widgets_add_menu() {
+ global $submenu;
- if ( array_key_exists($theme, $themes) )
- return $themes[$theme];
+ if ( ! current_theme_supports( 'widgets' ) )
+ return;
- return NULL;
-}
+ $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
+ ksort( $submenu['themes.php'], SORT_NUMERIC );
+}
+
+/**
+ * Flush all output buffers for PHP 5.2.
+ *
+ * Make sure all output buffers are flushed before our singletons are destroyed.
+ *
+ * @since 2.2.0
+ */
+function wp_ob_end_flush_all() {
+ $levels = ob_get_level();
+ for ($i=0; $i<$levels; $i++)
+ ob_end_flush();
+}
+
+/**
+ * Load custom DB error or display WordPress DB error.
+ *
+ * If a file exists in the wp-content directory named db-error.php, then it will
+ * be loaded instead of displaying the WordPress DB error. If it is not found,
+ * then the WordPress DB error will be displayed instead.
+ *
+ * The WordPress DB error sets the HTTP status header to 500 to try to prevent
+ * search engines from caching the message. Custom DB messages should do the
+ * same.
+ *
+ * This function was backported to WordPress 2.3.2, but originally was added
+ * in WordPress 2.5.0.
+ *
+ * @since 2.3.2
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ */
+function dead_db() {
+ global $wpdb;
-function get_current_theme() {
- $themes = get_themes();
- $theme_names = array_keys($themes);
- $current_template = get_settings('template');
- $current_stylesheet = get_settings('stylesheet');
- $current_theme = 'WordPress Default';
+ wp_load_translations_early();
- if ( $themes ) {
- foreach ($theme_names as $theme_name) {
- if ( $themes[$theme_name]['Stylesheet'] == $current_stylesheet &&
- $themes[$theme_name]['Template'] == $current_template ) {
- $current_theme = $themes[$theme_name]['Name'];
- break;
- }
- }
+ // Load custom DB error template, if present.
+ if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
+ require_once( WP_CONTENT_DIR . '/db-error.php' );
+ die();
}
- return $current_theme;
-}
+ // If installing or in the admin, provide the verbose message.
+ if ( wp_installing() || defined( 'WP_ADMIN' ) )
+ wp_die($wpdb->error);
-function get_query_template($type) {
- $template = '';
- if ( file_exists(TEMPLATEPATH . "/{$type}.php") )
- $template = TEMPLATEPATH . "/{$type}.php";
+ // Otherwise, be terse.
+ status_header( 500 );
+ nocache_headers();
+ header( 'Content-Type: text/html; charset=utf-8' );
+?>
+
+>
+
+
+
- return apply_filters("{$type}_template", $template);
+
+
+
+
+
+deprecated since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
+ else
+ trigger_error( sprintf( __('%1$s is deprecated since version %2$s with no alternative available.'), $function, $version ) );
+ } else {
+ if ( ! is_null( $replacement ) )
+ trigger_error( sprintf( '%1$s is deprecated since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
+ else
+ trigger_error( sprintf( '%1$s is deprecated since version %2$s with no alternative available.', $function, $version ) );
+ }
+ }
}
-function get_archive_template() {
- return get_query_template('archive');
-}
+/**
+ * Marks a constructor as deprecated and informs when it has been used.
+ *
+ * Similar to _deprecated_function(), but with different strings. Used to
+ * remove PHP4 style constructors.
+ *
+ * The current behavior is to trigger a user error if `WP_DEBUG` is true.
+ *
+ * This function is to be used in every PHP4 style constructor method that is deprecated.
+ *
+ * @since 4.3.0
+ * @access private
+ *
+ * @param string $class The class containing the deprecated constructor.
+ * @param string $version The version of WordPress that deprecated the function.
+ */
+function _deprecated_constructor( $class, $version ) {
+
+ /**
+ * Fires when a deprecated constructor is called.
+ *
+ * @since 4.3.0
+ *
+ * @param string $class The class containing the deprecated constructor.
+ * @param string $version The version of WordPress that deprecated the function.
+ */
+ do_action( 'deprecated_constructor_run', $class, $version );
+
+ /**
+ * Filter whether to trigger an error for deprecated functions.
+ *
+ * `WP_DEBUG` must be true in addition to the filter evaluating to true.
+ *
+ * @since 4.3.0
+ *
+ * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
+ */
+ if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
+ if ( function_exists( '__' ) ) {
+ trigger_error( sprintf( __( 'The called constructor method for %1$s is deprecated since version %2$s! Use %3$s instead.' ), $class, $version, '
__construct()
' ) );
+ } else {
+ trigger_error( sprintf( 'The called constructor method for %1$s is deprecated since version %2$s! Use %3$s instead.', $class, $version, '
__construct()
' ) );
+ }
+ }
-function get_author_template() {
- return get_query_template('author');
}
-function get_category_template() {
- $template = '';
- if ( file_exists(TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php') )
- $template = TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php';
- else if ( file_exists(TEMPLATEPATH . "/category.php") )
- $template = TEMPLATEPATH . "/category.php";
-
- return apply_filters('category_template', $template);
+/**
+ * Mark a file as deprecated and inform when it has been used.
+ *
+ * There is a hook deprecated_file_included that will be called that can be used
+ * to get the backtrace up to what file and function included the deprecated
+ * file.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * This function is to be used in every file that is deprecated.
+ *
+ * @since 2.5.0
+ * @access private
+ *
+ * @param string $file The file that was included.
+ * @param string $version The version of WordPress that deprecated the file.
+ * @param string $replacement Optional. The file that should have been included based on ABSPATH.
+ * Default null.
+ * @param string $message Optional. A message regarding the change. Default empty.
+ */
+function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
+
+ /**
+ * Fires when a deprecated file is called.
+ *
+ * @since 2.5.0
+ *
+ * @param string $file The file that was called.
+ * @param string $replacement The file that should have been included based on ABSPATH.
+ * @param string $version The version of WordPress that deprecated the file.
+ * @param string $message A message regarding the change.
+ */
+ do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
+
+ /**
+ * Filter whether to trigger an error for deprecated files.
+ *
+ * @since 2.5.0
+ *
+ * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
+ */
+ if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
+ $message = empty( $message ) ? '' : ' ' . $message;
+ if ( function_exists( '__' ) ) {
+ if ( ! is_null( $replacement ) )
+ trigger_error( sprintf( __('%1$s is deprecated since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
+ else
+ trigger_error( sprintf( __('%1$s is deprecated since version %2$s with no alternative available.'), $file, $version ) . $message );
+ } else {
+ if ( ! is_null( $replacement ) )
+ trigger_error( sprintf( '%1$s is deprecated since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
+ else
+ trigger_error( sprintf( '%1$s is deprecated since version %2$s with no alternative available.', $file, $version ) . $message );
+ }
+ }
+}
+/**
+ * Mark a function argument as deprecated and inform when it has been used.
+ *
+ * This function is to be used whenever a deprecated function argument is used.
+ * Before this function is called, the argument must be checked for whether it was
+ * used by comparing it to its default value or evaluating whether it is empty.
+ * For example:
+ *
+ * if ( ! empty( $deprecated ) ) {
+ * _deprecated_argument( __FUNCTION__, '3.0' );
+ * }
+ *
+ *
+ * There is a hook deprecated_argument_run that will be called that can be used
+ * to get the backtrace up to what file and function used the deprecated
+ * argument.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * @since 3.0.0
+ * @access private
+ *
+ * @param string $function The function that was called.
+ * @param string $version The version of WordPress that deprecated the argument used.
+ * @param string $message Optional. A message regarding the change. Default null.
+ */
+function _deprecated_argument( $function, $version, $message = null ) {
+
+ /**
+ * Fires when a deprecated argument is called.
+ *
+ * @since 3.0.0
+ *
+ * @param string $function The function that was called.
+ * @param string $message A message regarding the change.
+ * @param string $version The version of WordPress that deprecated the argument used.
+ */
+ do_action( 'deprecated_argument_run', $function, $message, $version );
+
+ /**
+ * Filter whether to trigger an error for deprecated arguments.
+ *
+ * @since 3.0.0
+ *
+ * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
+ */
+ if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
+ if ( function_exists( '__' ) ) {
+ if ( ! is_null( $message ) )
+ trigger_error( sprintf( __('%1$s was called with an argument that is deprecated since version %2$s! %3$s'), $function, $version, $message ) );
+ else
+ trigger_error( sprintf( __('%1$s was called with an argument that is deprecated since version %2$s with no alternative available.'), $function, $version ) );
+ } else {
+ if ( ! is_null( $message ) )
+ trigger_error( sprintf( '%1$s was called with an argument that is deprecated since version %2$s! %3$s', $function, $version, $message ) );
+ else
+ trigger_error( sprintf( '%1$s was called with an argument that is deprecated since version %2$s with no alternative available.', $function, $version ) );
+ }
+ }
}
-function get_date_template() {
- return get_query_template('date');
+/**
+ * Mark something as being incorrectly called.
+ *
+ * There is a hook doing_it_wrong_run that will be called that can be used
+ * to get the backtrace up to what file and function called the deprecated
+ * function.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param string $function The function that was called.
+ * @param string $message A message explaining what has been done incorrectly.
+ * @param string $version The version of WordPress where the message was added.
+ */
+function _doing_it_wrong( $function, $message, $version ) {
+
+ /**
+ * Fires when the given function is being used incorrectly.
+ *
+ * @since 3.1.0
+ *
+ * @param string $function The function that was called.
+ * @param string $message A message explaining what has been done incorrectly.
+ * @param string $version The version of WordPress where the message was added.
+ */
+ do_action( 'doing_it_wrong_run', $function, $message, $version );
+
+ /**
+ * Filter whether to trigger an error for _doing_it_wrong() calls.
+ *
+ * @since 3.1.0
+ *
+ * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
+ */
+ if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
+ if ( function_exists( '__' ) ) {
+ $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
+ /* translators: %s: Codex URL */
+ $message .= ' ' . sprintf( __( 'Please see Debugging in WordPress for more information.' ),
+ __( 'https://codex.wordpress.org/Debugging_in_WordPress' )
+ );
+ trigger_error( sprintf( __( '%1$s was called incorrectly. %2$s %3$s' ), $function, $message, $version ) );
+ } else {
+ $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
+ $message .= sprintf( ' Please see Debugging in WordPress for more information.',
+ 'https://codex.wordpress.org/Debugging_in_WordPress'
+ );
+ trigger_error( sprintf( '%1$s was called incorrectly. %2$s %3$s', $function, $message, $version ) );
+ }
+ }
}
-function get_home_template() {
- $template = '';
+/**
+ * Is the server running earlier than 1.5.0 version of lighttpd?
+ *
+ * @since 2.5.0
+ *
+ * @return bool Whether the server is running lighttpd < 1.5.0.
+ */
+function is_lighttpd_before_150() {
+ $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
+ $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
+ return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
+}
+
+/**
+ * Does the specified module exist in the Apache config?
+ *
+ * @since 2.5.0
+ *
+ * @global bool $is_apache
+ *
+ * @param string $mod The module, e.g. mod_rewrite.
+ * @param bool $default Optional. The default return value if the module is not found. Default false.
+ * @return bool Whether the specified module is loaded.
+ */
+function apache_mod_loaded($mod, $default = false) {
+ global $is_apache;
+
+ if ( !$is_apache )
+ return false;
+
+ if ( function_exists( 'apache_get_modules' ) ) {
+ $mods = apache_get_modules();
+ if ( in_array($mod, $mods) )
+ return true;
+ } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
+ ob_start();
+ phpinfo(8);
+ $phpinfo = ob_get_clean();
+ if ( false !== strpos($phpinfo, $mod) )
+ return true;
+ }
+ return $default;
+}
+
+/**
+ * Check if IIS 7+ supports pretty permalinks.
+ *
+ * @since 2.8.0
+ *
+ * @global bool $is_iis7
+ *
+ * @return bool Whether IIS7 supports permalinks.
+ */
+function iis7_supports_permalinks() {
+ global $is_iis7;
+
+ $supports_permalinks = false;
+ if ( $is_iis7 ) {
+ /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
+ * easily update the xml configuration file, hence we just bail out and tell user that
+ * pretty permalinks cannot be used.
+ *
+ * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
+ * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
+ * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
+ * via ISAPI then pretty permalinks will not work.
+ */
+ $supports_permalinks = class_exists( 'DOMDocument', false ) && isset($_SERVER['IIS_UrlRewriteModule']) && ( PHP_SAPI == 'cgi-fcgi' );
+ }
- if ( file_exists(TEMPLATEPATH . "/home.php") )
- $template = TEMPLATEPATH . "/home.php";
- else if ( file_exists(TEMPLATEPATH . "/index.php") )
- $template = TEMPLATEPATH . "/index.php";
+ /**
+ * Filter whether IIS 7+ supports pretty permalinks.
+ *
+ * @since 2.8.0
+ *
+ * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
+ */
+ return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
+}
+
+/**
+ * File validates against allowed set of defined rules.
+ *
+ * A return value of '1' means that the $file contains either '..' or './'. A
+ * return value of '2' means that the $file contains ':' after the first
+ * character. A return value of '3' means that the file is not in the allowed
+ * files list.
+ *
+ * @since 1.2.0
+ *
+ * @param string $file File path.
+ * @param array $allowed_files List of allowed files.
+ * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
+ */
+function validate_file( $file, $allowed_files = '' ) {
+ if ( false !== strpos( $file, '..' ) )
+ return 1;
+
+ if ( false !== strpos( $file, './' ) )
+ return 1;
+
+ if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
+ return 3;
+
+ if (':' == substr( $file, 1, 1 ) )
+ return 2;
- return apply_filters('home_template', $template);
+ return 0;
}
-function get_page_template() {
- global $wp_query;
-
- $id = (int) $wp_query->post->ID;
- $template = get_post_meta($id, '_wp_page_template', true);
+/**
+ * Determine if SSL is used.
+ *
+ * @since 2.6.0
+ *
+ * @return bool True if SSL, false if not used.
+ */
+function is_ssl() {
+ if ( isset($_SERVER['HTTPS']) ) {
+ if ( 'on' == strtolower($_SERVER['HTTPS']) )
+ return true;
+ if ( '1' == $_SERVER['HTTPS'] )
+ return true;
+ } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
+ return true;
+ }
+ return false;
+}
- if ( 'default' == $template )
- $template = '';
+/**
+ * Whether to force SSL used for the Administration Screens.
+ *
+ * @since 2.6.0
+ *
+ * @staticvar bool $forced
+ *
+ * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
+ * @return bool True if forced, false if not forced.
+ */
+function force_ssl_admin( $force = null ) {
+ static $forced = false;
+
+ if ( !is_null( $force ) ) {
+ $old_forced = $forced;
+ $forced = $force;
+ return $old_forced;
+ }
- if ( ! empty($template) && file_exists(TEMPLATEPATH . "/$template") )
- $template = TEMPLATEPATH . "/$template";
- else if ( file_exists(TEMPLATEPATH . "/page.php") )
- $template = TEMPLATEPATH . "/page.php";
- else
- $template = '';
+ return $forced;
+}
+
+/**
+ * Guess the URL for the site.
+ *
+ * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
+ * directory.
+ *
+ * @since 2.6.0
+ *
+ * @return string The guessed URL.
+ */
+function wp_guess_url() {
+ if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
+ $url = WP_SITEURL;
+ } else {
+ $abspath_fix = str_replace( '\\', '/', ABSPATH );
+ $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
- return apply_filters('page_template', $template);
-}
+ // The request is for the admin
+ if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
+ $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
-function get_paged_template() {
- return get_query_template('paged');
-}
+ // The request is for a file in ABSPATH
+ } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
+ // Strip off any file/query params in the path
+ $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
-function get_search_template() {
- return get_query_template('search');
-}
+ } else {
+ if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
+ // Request is hitting a file inside ABSPATH
+ $directory = str_replace( ABSPATH, '', $script_filename_dir );
+ // Strip off the sub directory, and any file/query params
+ $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
+ } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
+ // Request is hitting a file above ABSPATH
+ $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
+ // Strip off any file/query params from the path, appending the sub directory to the install
+ $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
+ } else {
+ $path = $_SERVER['REQUEST_URI'];
+ }
+ }
-function get_single_template() {
- return get_query_template('single');
-}
+ $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
+ $url = $schema . $_SERVER['HTTP_HOST'] . $path;
+ }
-function get_attachment_template() {
- global $posts;
- $type = explode('/', $posts[0]->post_mime_type);
- if ( $template = get_query_template($type[0]) )
- return $template;
- elseif ( $template = get_query_template($type[1]) )
- return $template;
- elseif ( $template = get_query_template("$type[0]_$type[1]") )
- return $template;
- else
- return get_query_template('attachment');
-}
+ return rtrim($url, '/');
+}
+
+/**
+ * Temporarily suspend cache additions.
+ *
+ * Stops more data being added to the cache, but still allows cache retrieval.
+ * This is useful for actions, such as imports, when a lot of data would otherwise
+ * be almost uselessly added to the cache.
+ *
+ * Suspension lasts for a single page load at most. Remember to call this
+ * function again if you wish to re-enable cache adds earlier.
+ *
+ * @since 3.3.0
+ *
+ * @staticvar bool $_suspend
+ *
+ * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
+ * @return bool The current suspend setting
+ */
+function wp_suspend_cache_addition( $suspend = null ) {
+ static $_suspend = false;
+
+ if ( is_bool( $suspend ) )
+ $_suspend = $suspend;
+
+ return $_suspend;
+}
+
+/**
+ * Suspend cache invalidation.
+ *
+ * Turns cache invalidation on and off. Useful during imports where you don't wont to do
+ * invalidations every time a post is inserted. Callers must be sure that what they are
+ * doing won't lead to an inconsistent cache when invalidation is suspended.
+ *
+ * @since 2.7.0
+ *
+ * @global bool $_wp_suspend_cache_invalidation
+ *
+ * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
+ * @return bool The current suspend setting.
+ */
+function wp_suspend_cache_invalidation( $suspend = true ) {
+ global $_wp_suspend_cache_invalidation;
+
+ $current_suspend = $_wp_suspend_cache_invalidation;
+ $_wp_suspend_cache_invalidation = $suspend;
+ return $current_suspend;
+}
+
+/**
+ * Determine whether a site is the main site of the current network.
+ *
+ * @since 3.0.0
+ *
+ * @global object $current_site
+ *
+ * @param int $site_id Optional. Site ID to test. Defaults to current site.
+ * Defaults to current site.
+ * @return bool True if $site_id is the main site of the network, or if not
+ * running Multisite.
+ */
+function is_main_site( $site_id = null ) {
+ // This is the current network's information; 'site' is old terminology.
+ global $current_site;
+
+ if ( ! is_multisite() )
+ return true;
-function get_comments_popup_template() {
- if ( file_exists( TEMPLATEPATH . '/comments-popup.php') )
- $template = TEMPLATEPATH . '/comments-popup.php';
- else
- $template = get_theme_root() . '/default/comments-popup.php';
+ if ( ! $site_id )
+ $site_id = get_current_blog_id();
- return apply_filters('comments_popup_template', $template);
+ return (int) $site_id === (int) $current_site->blog_id;
}
-// Borrowed from the PHP Manual user notes. Convert entities, while
-// preserving already-encoded entities:
-function htmlentities2($myHTML) {
- $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
- $translation_table[chr(38)] = '&';
- return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($myHTML, $translation_table));
-}
+/**
+ * Determine whether a network is the main network of the Multisite install.
+ *
+ * @since 3.7.0
+ *
+ * @param int $network_id Optional. Network ID to test. Defaults to current network.
+ * @return bool True if $network_id is the main network, or if not running Multisite.
+ */
+function is_main_network( $network_id = null ) {
+ if ( ! is_multisite() ) {
+ return true;
+ }
+ $current_network_id = (int) get_current_site()->id;
-function is_plugin_page() {
- global $plugin_page;
+ if ( null === $network_id ) {
+ $network_id = $current_network_id;
+ }
- if ( isset($plugin_page) )
- return true;
+ $network_id = (int) $network_id;
- return false;
+ return ( $network_id === get_main_network_id() );
}
-/*
-add_query_arg: Returns a modified querystring by adding
-a single key & value or an associative array.
-Setting a key value to emptystring removes the key.
-Omitting oldquery_or_uri uses the $_SERVER value.
+/**
+ * Get the main network ID.
+ *
+ * @since 4.3.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @return int The ID of the main network.
+ */
+function get_main_network_id() {
+ global $wpdb;
-Parameters:
-add_query_arg(newkey, newvalue, oldquery_or_uri) or
-add_query_arg(associative_array, oldquery_or_uri)
-*/
-function add_query_arg() {
- $ret = '';
- if ( is_array(func_get_arg(0)) ) {
- if ( @func_num_args() < 2 )
- $uri = $_SERVER['REQUEST_URI'];
- else
- $uri = @func_get_arg(1);
+ if ( ! is_multisite() ) {
+ return 1;
+ }
+
+ if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
+ $main_network_id = PRIMARY_NETWORK_ID;
+ } elseif ( 1 === (int) get_current_site()->id ) {
+ // If the current network has an ID of 1, assume it is the main network.
+ $main_network_id = 1;
} else {
- if ( @func_num_args() < 3 )
- $uri = $_SERVER['REQUEST_URI'];
- else
- $uri = @func_get_arg(2);
+ $main_network_id = wp_cache_get( 'primary_network_id', 'site-options' );
+
+ if ( false === $main_network_id ) {
+ $main_network_id = (int) $wpdb->get_var( "SELECT id FROM {$wpdb->site} ORDER BY id LIMIT 1" );
+ wp_cache_add( 'primary_network_id', $main_network_id, 'site-options' );
+ }
}
- if ( $frag = strstr($uri, '#') )
- $uri = substr($uri, 0, -strlen($frag));
- else
- $frag = '';
+ /**
+ * Filter the main network ID.
+ *
+ * @since 4.3.0
+ *
+ * @param int $main_network_id The ID of the main network.
+ */
+ return (int) apply_filters( 'get_main_network_id', $main_network_id );
+}
+
+/**
+ * Determine whether global terms are enabled.
+ *
+ * @since 3.0.0
+ *
+ * @staticvar bool $global_terms
+ *
+ * @return bool True if multisite and global terms enabled.
+ */
+function global_terms_enabled() {
+ if ( ! is_multisite() )
+ return false;
- if ( preg_match('|^https?://|i', $uri, $matches) ) {
- $protocol = $matches[0];
- $uri = substr($uri, strlen($protocol));
- } else {
- $protocol = '';
+ static $global_terms = null;
+ if ( is_null( $global_terms ) ) {
+
+ /**
+ * Filter whether global terms are enabled.
+ *
+ * Passing a non-null value to the filter will effectively short-circuit the function,
+ * returning the value of the 'global_terms_enabled' site option instead.
+ *
+ * @since 3.0.0
+ *
+ * @param null $enabled Whether global terms are enabled.
+ */
+ $filter = apply_filters( 'global_terms_enabled', null );
+ if ( ! is_null( $filter ) )
+ $global_terms = (bool) $filter;
+ else
+ $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
+ }
+ return $global_terms;
+}
+
+/**
+ * gmt_offset modification for smart timezone handling.
+ *
+ * Overrides the gmt_offset option if we have a timezone_string available.
+ *
+ * @since 2.8.0
+ *
+ * @return float|false Timezone GMT offset, false otherwise.
+ */
+function wp_timezone_override_offset() {
+ if ( !$timezone_string = get_option( 'timezone_string' ) ) {
+ return false;
}
- if ( strstr($uri, '?') ) {
- $parts = explode('?', $uri, 2);
- if ( 1 == count($parts) ) {
- $base = '?';
- $query = $parts[0];
- } else {
- $base = $parts[0] . '?';
- $query = $parts[1];
+ $timezone_object = timezone_open( $timezone_string );
+ $datetime_object = date_create();
+ if ( false === $timezone_object || false === $datetime_object ) {
+ return false;
+ }
+ return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
+}
+
+/**
+ * Sort-helper for timezones.
+ *
+ * @since 2.9.0
+ * @access private
+ *
+ * @param array $a
+ * @param array $b
+ * @return int
+ */
+function _wp_timezone_choice_usort_callback( $a, $b ) {
+ // Don't use translated versions of Etc
+ if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
+ // Make the order of these more like the old dropdown
+ if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
+ return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
}
- } else if ( !empty($protocol) || strstr($uri, '/') ) {
- $base = $uri . '?';
- $query = '';
+ if ( 'UTC' === $a['city'] ) {
+ if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
+ return 1;
+ }
+ return -1;
+ }
+ if ( 'UTC' === $b['city'] ) {
+ if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
+ return -1;
+ }
+ return 1;
+ }
+ return strnatcasecmp( $a['city'], $b['city'] );
+ }
+ if ( $a['t_continent'] == $b['t_continent'] ) {
+ if ( $a['t_city'] == $b['t_city'] ) {
+ return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
+ }
+ return strnatcasecmp( $a['t_city'], $b['t_city'] );
} else {
- $base = '';
- $query = $uri;
+ // Force Etc to the bottom of the list
+ if ( 'Etc' === $a['continent'] ) {
+ return 1;
+ }
+ if ( 'Etc' === $b['continent'] ) {
+ return -1;
+ }
+ return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
}
+}
- parse_str($query, $qs);
- if ( is_array(func_get_arg(0)) ) {
- $kayvees = func_get_arg(0);
- $qs = array_merge($qs, $kayvees);
- } else {
- $qs[func_get_arg(0)] = func_get_arg(1);
+/**
+ * Gives a nicely-formatted list of timezone strings.
+ *
+ * @since 2.9.0
+ *
+ * @staticvar bool $mo_loaded
+ *
+ * @param string $selected_zone Selected timezone.
+ * @return string
+ */
+function wp_timezone_choice( $selected_zone ) {
+ static $mo_loaded = false;
+
+ $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
+
+ // Load translations for continents and cities
+ if ( !$mo_loaded ) {
+ $locale = get_locale();
+ $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
+ load_textdomain( 'continents-cities', $mofile );
+ $mo_loaded = true;
}
- foreach($qs as $k => $v) {
- if ( $v != '' ) {
- if ( $ret != '' )
- $ret .= '&';
- $ret .= "$k=$v";
+ $zonen = array();
+ foreach ( timezone_identifiers_list() as $zone ) {
+ $zone = explode( '/', $zone );
+ if ( !in_array( $zone[0], $continents ) ) {
+ continue;
}
+
+ // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
+ $exists = array(
+ 0 => ( isset( $zone[0] ) && $zone[0] ),
+ 1 => ( isset( $zone[1] ) && $zone[1] ),
+ 2 => ( isset( $zone[2] ) && $zone[2] ),
+ );
+ $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
+ $exists[4] = ( $exists[1] && $exists[3] );
+ $exists[5] = ( $exists[2] && $exists[3] );
+
+ $zonen[] = array(
+ 'continent' => ( $exists[0] ? $zone[0] : '' ),
+ 'city' => ( $exists[1] ? $zone[1] : '' ),
+ 'subcity' => ( $exists[2] ? $zone[2] : '' ),
+ 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
+ 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
+ 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
+ );
}
- $ret = $protocol . $base . $ret . $frag;
- return trim($ret, '?');
-}
+ usort( $zonen, '_wp_timezone_choice_usort_callback' );
-function remove_query_arg($key, $query) {
- return add_query_arg($key, '', $query);
-}
+ $structure = array();
-function load_template($_template_file) {
- global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query,
- $wp_rewrite, $wpdb;
+ if ( empty( $selected_zone ) ) {
+ $structure[] = '';
+ }
- if ( is_array($wp_query->query_vars) )
- extract($wp_query->query_vars, EXTR_SKIP);
+ foreach ( $zonen as $key => $zone ) {
+ // Build value in an array to join later
+ $value = array( $zone['continent'] );
- require_once($_template_file);
-}
+ if ( empty( $zone['city'] ) ) {
+ // It's at the continent level (generally won't happen)
+ $display = $zone['t_continent'];
+ } else {
+ // It's inside a continent group
-function add_magic_quotes($array) {
- global $wpdb;
+ // Continent optgroup
+ if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
+ $label = $zone['t_continent'];
+ $structure[] = '';
+ }
+ }
- if ( !isset($parsed_url['scheme']) || !in_array($parsed_url['scheme'], array('http','https')) )
- $uri = 'http://' . $uri;
+ // Do UTC
+ $structure[] = '';
+
+ // Do manual UTC offsets
+ $structure[] = '';
+
+ return join( "\n", $structure );
+}
+
+/**
+ * Strip close comment and close php tags from file headers used by WP.
+ *
+ * @since 2.8.0
+ * @access private
+ *
+ * @see https://core.trac.wordpress.org/ticket/8497
+ *
+ * @param string $str Header comment to clean up.
+ * @return string
+ */
+function _cleanup_header_comment( $str ) {
+ return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
+}
+
+/**
+ * Permanently delete comments or posts of any type that have held a status
+ * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS.
+ *
+ * The default value of `EMPTY_TRASH_DAYS` is 30 (days).
+ *
+ * @since 2.9.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ */
+function wp_scheduled_delete() {
+ global $wpdb;
-function status_header( $header ) {
- if ( 200 == $header )
- $text = 'OK';
- elseif ( 301 == $header )
- $text = 'Moved Permanently';
- elseif ( 302 == $header )
- $text = 'Moved Temporarily';
- elseif ( 304 == $header )
- $text = 'Not Modified';
- elseif ( 404 == $header )
- $text = 'Not Found';
- elseif ( 410 == $header )
- $text = 'Gone';
+ $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
- if ( version_compare(phpversion(), '4.3.0', '>=') )
- @header("HTTP/1.1 $header $text", true, $header);
- else
- @header("HTTP/1.1 $header $text");
-}
+ $posts_to_delete = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
-function nocache_headers() {
- @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
- @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
- @ header('Cache-Control: no-cache, must-revalidate, max-age=0');
- @ header('Pragma: no-cache');
-}
+ foreach ( (array) $posts_to_delete as $post ) {
+ $post_id = (int) $post['post_id'];
+ if ( !$post_id )
+ continue;
-function get_usermeta( $user_id, $meta_key = '') {
- global $wpdb;
- $user_id = (int) $user_id;
+ $del_post = get_post($post_id);
- if ( !empty($meta_key) ) {
- $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
- $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
- } else {
- $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'");
+ if ( !$del_post || 'trash' != $del_post->post_status ) {
+ delete_post_meta($post_id, '_wp_trash_meta_status');
+ delete_post_meta($post_id, '_wp_trash_meta_time');
+ } else {
+ wp_delete_post($post_id);
+ }
}
- if ( empty($metas) ) {
- if ( empty($meta_key) )
- return array();
- else
- return '';
- }
+ $comments_to_delete = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
- foreach ($metas as $index => $meta) {
- @ $value = unserialize($meta->meta_value);
- if ( $value === FALSE )
- $value = $meta->meta_value;
+ foreach ( (array) $comments_to_delete as $comment ) {
+ $comment_id = (int) $comment['comment_id'];
+ if ( !$comment_id )
+ continue;
- $values[] = $value;
- }
+ $del_comment = get_comment($comment_id);
- if ( count($values) == 1 )
- return $values[0];
- else
- return $values;
+ if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
+ delete_comment_meta($comment_id, '_wp_trash_meta_time');
+ delete_comment_meta($comment_id, '_wp_trash_meta_status');
+ } else {
+ wp_delete_comment( $del_comment );
+ }
+ }
}
-function update_usermeta( $user_id, $meta_key, $meta_value ) {
- global $wpdb;
- if ( !is_numeric( $user_id ) )
- return false;
- $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
-
- // FIXME: usermeta data is assumed to be already escaped
- if ( is_string($meta_value) )
- $meta_value = stripslashes($meta_value);
- $meta_value = maybe_serialize($meta_value);
- $meta_value = $wpdb->escape($meta_value);
-
- if (empty($meta_value)) {
- delete_usermeta($user_id, $meta_key);
- }
-
- $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
- if ( !$cur ) {
- $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
- VALUES
- ( '$user_id', '$meta_key', '$meta_value' )");
- } else if ( $cur->meta_value != $meta_value ) {
- $wpdb->query("UPDATE $wpdb->usermeta SET meta_value = '$meta_value' WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
+/**
+ * Retrieve metadata from a file.
+ *
+ * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
+ * Each piece of metadata must be on its own line. Fields can not span multiple
+ * lines, the value will get cut at the end of the first line.
+ *
+ * If the file data is not within that first 8kiB, then the author should correct
+ * their plugin file and move the data headers to the top.
+ *
+ * @link https://codex.wordpress.org/File_Header
+ *
+ * @since 2.9.0
+ *
+ * @param string $file Path to the file.
+ * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name').
+ * @param string $context Optional. If specified adds filter hook "extra_{$context}_headers".
+ * Default empty.
+ * @return array Array of file headers in `HeaderKey => Header Value` format.
+ */
+function get_file_data( $file, $default_headers, $context = '' ) {
+ // We don't need to write to the file, so just open for reading.
+ $fp = fopen( $file, 'r' );
+
+ // Pull only the first 8kiB of the file in.
+ $file_data = fread( $fp, 8192 );
+
+ // PHP will close file handle, but we are good citizens.
+ fclose( $fp );
+
+ // Make sure we catch CR-only line endings.
+ $file_data = str_replace( "\r", "\n", $file_data );
+
+ /**
+ * Filter extra file headers by context.
+ *
+ * The dynamic portion of the hook name, `$context`, refers to
+ * the context where extra headers might be loaded.
+ *
+ * @since 2.9.0
+ *
+ * @param array $extra_context_headers Empty array by default.
+ */
+ if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
+ $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
+ $all_headers = array_merge( $extra_headers, (array) $default_headers );
} else {
- return false;
+ $all_headers = $default_headers;
}
-
- $user = get_userdata($user_id);
- wp_cache_delete($user_id, 'users');
- wp_cache_delete($user->user_login, 'userlogins');
-
- return true;
-}
-function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) {
- global $wpdb;
- if ( !is_numeric( $user_id ) )
- return false;
- $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
-
- if ( is_array($meta_value) || is_object($meta_value) )
- $meta_value = serialize($meta_value);
- $meta_value = trim( $meta_value );
+ foreach ( $all_headers as $field => $regex ) {
+ if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
+ $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
+ else
+ $all_headers[ $field ] = '';
+ }
- if ( ! empty($meta_value) )
- $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'");
- else
- $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
-
- $user = get_userdata($user_id);
- wp_cache_delete($user_id, 'users');
- wp_cache_delete($user->user_login, 'userlogins');
-
+ return $all_headers;
+}
+
+/**
+ * Returns true.
+ *
+ * Useful for returning true to filters easily.
+ *
+ * @since 3.0.0
+ *
+ * @see __return_false()
+ *
+ * @return true True.
+ */
+function __return_true() {
return true;
}
-function register_activation_hook($file, $function) {
- $file = plugin_basename($file);
-
- add_action('activate_' . $file, $function);
-}
-
-function register_deactivation_hook($file, $function) {
- $file = plugin_basename($file);
-
- add_action('deactivate_' . $file, $function);
+/**
+ * Returns false.
+ *
+ * Useful for returning false to filters easily.
+ *
+ * @since 3.0.0
+ *
+ * @see __return_true()
+ *
+ * @return false False.
+ */
+function __return_false() {
+ return false;
}
-function plugin_basename($file) {
- $file = preg_replace('|\\\\+|', '\\\\', $file);
- $file = preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
- return $file;
+/**
+ * Returns 0.
+ *
+ * Useful for returning 0 to filters easily.
+ *
+ * @since 3.0.0
+ *
+ * @return int 0.
+ */
+function __return_zero() {
+ return 0;
}
-function get_num_queries() {
- global $wpdb;
- return $wpdb->num_queries;
+/**
+ * Returns an empty array.
+ *
+ * Useful for returning an empty array to filters easily.
+ *
+ * @since 3.0.0
+ *
+ * @return array Empty array.
+ */
+function __return_empty_array() {
+ return array();
+}
+
+/**
+ * Returns null.
+ *
+ * Useful for returning null to filters easily.
+ *
+ * @since 3.4.0
+ *
+ * @return null Null value.
+ */
+function __return_null() {
+ return null;
+}
+
+/**
+ * Returns an empty string.
+ *
+ * Useful for returning an empty string to filters easily.
+ *
+ * @since 3.7.0
+ *
+ * @see __return_null()
+ *
+ * @return string Empty string.
+ */
+function __return_empty_string() {
+ return '';
+}
+
+/**
+ * Send a HTTP header to disable content type sniffing in browsers which support it.
+ *
+ * @since 3.0.0
+ *
+ * @see http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
+ * @see http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
+ */
+function send_nosniff_header() {
+ @header( 'X-Content-Type-Options: nosniff' );
+}
+
+/**
+ * Return a MySQL expression for selecting the week number based on the start_of_week option.
+ *
+ * @ignore
+ * @since 3.0.0
+ *
+ * @param string $column Database column.
+ * @return string SQL clause.
+ */
+function _wp_mysql_week( $column ) {
+ switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
+ case 1 :
+ return "WEEK( $column, 1 )";
+ case 2 :
+ case 3 :
+ case 4 :
+ case 5 :
+ case 6 :
+ return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
+ case 0 :
+ default :
+ return "WEEK( $column, 0 )";
+ }
}
-function wp_nonce_url($actionurl, $action = -1) {
- return wp_specialchars(add_query_arg('_wpnonce', wp_create_nonce($action), $actionurl));
-}
+/**
+ * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
+ * @param int $start The ID to start the loop check at.
+ * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
+ * Use null to always use $callback
+ * @param array $callback_args Optional. Additional arguments to send to $callback.
+ * @return array IDs of all members of loop.
+ */
+function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
+ $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
+
+ if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
+ return array();
+
+ return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
+}
+
+/**
+ * Use the "The Tortoise and the Hare" algorithm to detect loops.
+ *
+ * For every step of the algorithm, the hare takes two steps and the tortoise one.
+ * If the hare ever laps the tortoise, there must be a loop.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
+ * @param int $start The ID to start the loop check at.
+ * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
+ * Default empty array.
+ * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
+ * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
+ * to true if you already know the given $start is part of a loop (otherwise
+ * the returned array might include branches). Default false.
+ * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
+ * $_return_loop
+ */
+function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
+ $tortoise = $hare = $evanescent_hare = $start;
+ $return = array();
+
+ // Set evanescent_hare to one past hare
+ // Increment hare two steps
+ while (
+ $tortoise
+ &&
+ ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
+ &&
+ ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
+ ) {
+ if ( $_return_loop )
+ $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
+
+ // tortoise got lapped - must be a loop
+ if ( $tortoise == $evanescent_hare || $tortoise == $hare )
+ return $_return_loop ? $return : $tortoise;
+
+ // Increment tortoise by one step
+ $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
+ }
-function wp_nonce_field($action = -1, $name = "_wpnonce", $referer = true) {
- $name = attribute_escape($name);
- echo '';
- if ( $referer )
- wp_referer_field();
+ return false;
}
-function wp_referer_field() {
- $ref = attribute_escape(stripslashes($_SERVER['REQUEST_URI']));
- echo '';
- if ( wp_get_original_referer() ) {
- $original_ref = attribute_escape(stripslashes(wp_get_original_referer()));
- echo '';
+/**
+ * Send a HTTP header to limit rendering of pages to same origin iframes.
+ *
+ * @since 3.1.3
+ *
+ * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
+ */
+function send_frame_options_header() {
+ @header( 'X-Frame-Options: SAMEORIGIN' );
+}
+
+/**
+ * Retrieve a list of protocols to allow in HTML attributes.
+ *
+ * @since 3.3.0
+ * @since 4.3.0 Added 'webcal' to the protocols array.
+ *
+ * @see wp_kses()
+ * @see esc_url()
+ *
+ * @staticvar array $protocols
+ *
+ * @return array Array of allowed protocols. Defaults to an array containing 'http', 'https',
+ * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet',
+ * 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', and 'webcal'.
+ */
+function wp_allowed_protocols() {
+ static $protocols = array();
+
+ if ( empty( $protocols ) ) {
+ $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', 'webcal' );
+
+ /**
+ * Filter the list of protocols allowed in HTML attributes.
+ *
+ * @since 3.0.0
+ *
+ * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
+ */
+ $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
}
-}
-function wp_original_referer_field() {
- echo '';
-}
+ return $protocols;
+}
+
+/**
+ * Return a comma-separated string of functions that have been called to get
+ * to the current point in code.
+ *
+ * @since 3.4.0
+ *
+ * @see https://core.trac.wordpress.org/ticket/19589
+ *
+ * @param string $ignore_class Optional. A class to ignore all function calls within - useful
+ * when you want to just give info about the callee. Default null.
+ * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
+ * back to the source of the issue. Default 0.
+ * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
+ * array returned. Default true.
+ * @return string|array Either a string containing a reversed comma separated trace or an array
+ * of individual calls.
+ */
+function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
+ if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
+ $trace = debug_backtrace( false );
+ else
+ $trace = debug_backtrace();
-function wp_get_referer() {
- foreach ( array($_REQUEST['_wp_http_referer'], $_SERVER['HTTP_REFERER']) as $ref )
- if ( !empty($ref) )
- return $ref;
- return false;
-}
+ $caller = array();
+ $check_class = ! is_null( $ignore_class );
+ $skip_frames++; // skip this function
-function wp_get_original_referer() {
- if ( !empty($_REQUEST['_wp_original_http_referer']) )
- return $_REQUEST['_wp_original_http_referer'];
- return false;
-}
+ foreach ( $trace as $call ) {
+ if ( $skip_frames > 0 ) {
+ $skip_frames--;
+ } elseif ( isset( $call['class'] ) ) {
+ if ( $check_class && $ignore_class == $call['class'] )
+ continue; // Filter out calls
-function wp_explain_nonce($action) {
- if ( $action !== -1 && preg_match('/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches) ) {
- $verb = $matches[1];
- $noun = $matches[2];
-
- $trans = array();
- $trans['update']['attachment'] = array(__('Are you sure you want to edit this attachment: "%s"?'), 'get_the_title');
-
- $trans['add']['category'] = array(__('Are you sure you want to add this category?'), false);
- $trans['delete']['category'] = array(__('Are you sure you want to delete this category: "%s"?'), 'get_catname');
- $trans['update']['category'] = array(__('Are you sure you want to edit this category: "%s"?'), 'get_catname');
-
- $trans['delete']['comment'] = array(__('Are you sure you want to delete this comment: "%s"?'), 'use_id');
- $trans['unapprove']['comment'] = array(__('Are you sure you want to unapprove this comment: "%s"?'), 'use_id');
- $trans['approve']['comment'] = array(__('Are you sure you want to approve this comment: "%s"?'), 'use_id');
- $trans['update']['comment'] = array(__('Are you sure you want to edit this comment: "%s"?'), 'use_id');
- $trans['bulk']['comments'] = array(__('Are you sure you want to bulk modify comments?'), false);
- $trans['moderate']['comments'] = array(__('Are you sure you want to moderate comments?'), false);
-
- $trans['add']['bookmark'] = array(__('Are you sure you want to add this bookmark?'), false);
- $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this bookmark: "%s"?'), 'use_id');
- $trans['update']['bookmark'] = array(__('Are you sure you want to edit this bookmark: "%s"?'), 'use_id');
- $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify bookmarks?'), false);
-
- $trans['add']['page'] = array(__('Are you sure you want to add this page?'), false);
- $trans['delete']['page'] = array(__('Are you sure you want to delete this page: "%s"?'), 'get_the_title');
- $trans['update']['page'] = array(__('Are you sure you want to edit this page: "%s"?'), 'get_the_title');
-
- $trans['edit']['plugin'] = array(__('Are you sure you want to edit this plugin file: "%s"?'), 'use_id');
- $trans['activate']['plugin'] = array(__('Are you sure you want to activate this plugin: "%s"?'), 'use_id');
- $trans['deactivate']['plugin'] = array(__('Are you sure you want to deactivate this plugin: "%s"?'), 'use_id');
-
- $trans['add']['post'] = array(__('Are you sure you want to add this post?'), false);
- $trans['delete']['post'] = array(__('Are you sure you want to delete this post: "%s"?'), 'get_the_title');
- $trans['update']['post'] = array(__('Are you sure you want to edit this post: "%s"?'), 'get_the_title');
-
- $trans['add']['user'] = array(__('Are you sure you want to add this user?'), false);
- $trans['delete']['users'] = array(__('Are you sure you want to delete users?'), false);
- $trans['bulk']['users'] = array(__('Are you sure you want to bulk modify users?'), false);
- $trans['update']['user'] = array(__('Are you sure you want to edit this user: "%s"?'), 'get_author_name');
- $trans['update']['profile'] = array(__('Are you sure you want to modify the profile for: "%s"?'), 'get_author_name');
-
- $trans['update']['options'] = array(__('Are you sure you want to edit your settings?'), false);
- $trans['update']['permalink'] = array(__('Are you sure you want to change your permalink structure to: %s?'), 'use_id');
- $trans['edit']['file'] = array(__('Are you sure you want to edit this file: "%s"?'), 'use_id');
- $trans['edit']['theme'] = array(__('Are you sure you want to edit this theme file: "%s"?'), 'use_id');
- $trans['switch']['theme'] = array(__('Are you sure you want to switch to this theme: "%s"?'), 'use_id');
-
- if ( isset($trans[$verb][$noun]) ) {
- if ( !empty($trans[$verb][$noun][1]) ) {
- $lookup = $trans[$verb][$noun][1];
- $object = $matches[4];
- if ( 'use_id' != $lookup )
- $object = call_user_func($lookup, $object);
- return sprintf($trans[$verb][$noun][0], $object);
+ $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
+ } else {
+ if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
+ $caller[] = "{$call['function']}('{$call['args'][0]}')";
+ } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
+ $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
} else {
- return $trans[$verb][$noun][0];
+ $caller[] = $call['function'];
}
}
}
+ if ( $pretty )
+ return join( ', ', array_reverse( $caller ) );
+ else
+ return $caller;
+}
+
+/**
+ * Retrieve ids that are not already present in the cache.
+ *
+ * @since 3.4.0
+ * @access private
+ *
+ * @param array $object_ids ID list.
+ * @param string $cache_key The cache bucket to check against.
+ *
+ * @return array List of ids not present in the cache.
+ */
+function _get_non_cached_ids( $object_ids, $cache_key ) {
+ $clean = array();
+ foreach ( $object_ids as $id ) {
+ $id = (int) $id;
+ if ( !wp_cache_get( $id, $cache_key ) ) {
+ $clean[] = $id;
+ }
+ }
- return __('Are you sure you want to do this?');
+ return $clean;
}
-function wp_nonce_ays($action) {
- global $pagenow, $menu, $submenu, $parent_file, $submenu_file;
+/**
+ * Test if the current device has the capability to upload files.
+ *
+ * @since 3.4.0
+ * @access private
+ *
+ * @return bool Whether the device is able to upload files.
+ */
+function _device_can_upload() {
+ if ( ! wp_is_mobile() )
+ return true;
- $adminurl = get_settings('siteurl') . '/wp-admin';
- if ( wp_get_referer() )
- $adminurl = attribute_escape(stripslashes(wp_get_referer()));
+ $ua = $_SERVER['HTTP_USER_AGENT'];
- $title = __('WordPress Confirmation');
- // Remove extra layer of slashes.
- $_POST = stripslashes_deep($_POST );
- if ( $_POST ) {
- $q = http_build_query($_POST);
- $q = explode( ini_get('arg_separator.output'), $q);
- $html .= "\t\n";
- } else {
- $html .= "\t