public function setUp() { parent::setUp(); if (wp_using_ext_object_cache()) { $this->markTestSkipped('Not testable with an external object cache.'); } }
/** * When the transient version increases, this is used to remove all past transients to avoid filling the DB. * * Note; this only works on transients appended with the transient version, and when object caching is not being used. * * @since 2.3.10 */ private static function delete_version_transients($version) { if (!wp_using_ext_object_cache() && !empty($version)) { global $wpdb; $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name LIKE %s;", "\\_transient\\_%" . $version)); } }
/** * Clear all transients cache for product data. * * @param int $post_id (default: 0) */ function wc_delete_product_transients($post_id = 0) { global $wpdb; if (wp_using_ext_object_cache()) { wp_cache_flush(); // There isn't a reliable method of looking up the names, so flush the cache. return; } $post_id = absint($post_id); // Clear core transients $transients_to_clear = array('wc_products_onsale', 'wc_hidden_product_ids', 'wc_hidden_product_ids_search', 'wc_attribute_taxonomies', 'wc_term_counts', 'wc_featured_products'); // Clear transients for which we don't have the name $wpdb->query("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_wc_uf_pid_%') OR `option_name` LIKE ('_transient_timeout_wc_uf_pid_%')"); $wpdb->query("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_wc_ln_count_%') OR `option_name` LIKE ('_transient_timeout_wc_ln_count_%')"); $wpdb->query("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_wc_ship_%') OR `option_name` LIKE ('_transient_timeout_wc_ship_%')"); $wpdb->query("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_wc_products_will_display_%') OR `option_name` LIKE ('_transient_timeout_wc_products_will_display_%')"); // Clear product specific transients $post_transient_names = array('wc_product_children_ids_', 'wc_product_total_stock_', 'wc_average_rating_', 'wc_rating_count_'); if ($post_id > 0) { foreach ($post_transient_names as $transient) { $transients_to_clear[] = $transient . $post_id; } } else { foreach ($post_transient_names as $transient) { $wpdb->query($wpdb->prepare("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE %s OR `option_name` LIKE %s", '_transient_' . $transient . '%', '_transient_timeout_' . $transient . '%')); } } // Delete transients foreach ($transients_to_clear as $transient) { delete_transient($transient); } do_action('woocommerce_delete_product_transients', $post_id); }
public function process() { global $wp_object_cache; $this->data['ext_object_cache'] = (bool) wp_using_ext_object_cache(); if (is_object($wp_object_cache)) { if (isset($wp_object_cache->cache_hits)) { $this->data['stats']['cache_hits'] = $wp_object_cache->cache_hits; } if (isset($wp_object_cache->cache_misses)) { $this->data['stats']['cache_misses'] = $wp_object_cache->cache_misses; } if (isset($wp_object_cache->stats)) { foreach ($wp_object_cache->stats as $key => $value) { if (!is_scalar($value)) { continue; } $this->data['stats'][$key] = $value; } } } if (isset($this->data['stats']['cache_hits']) && isset($this->data['stats']['cache_misses'])) { $total = $this->data['stats']['cache_misses'] + $this->data['stats']['cache_hits']; $this->data['cache_hit_percentage'] = 100 / $total * $this->data['stats']['cache_hits']; } }
* With external cache however, this isn't possible. Instead, this function is used * to append a unique string (based on time()) to each transient. When transients * are invalidated, the transient version will increment and data will be regenerated. * * @param string $group Name for the group of transients we need to invalidate * @param boolean $refresh true to force a new version * @return string transient version based on time(), 10 digits */ public static function get_transient_version($group, $refresh = false)
private static function delete_cache_value($group) { if (!wp_using_ext_object_cache()) { global $wpdb; $sql = "\n\t\t\t\tdelete from {$wpdb->options}\n\t\t\t\twhere option_name like '_transient_{$group}%' or option_name like '_transient_timeout_{$group}%'\n\t\t\t"; return $wpdb->query($sql); } return false; }
/** * Delete product view transients when needed e.g. when post status changes, or visibility/stock status is modified. */ public static function delete_product_query_transients() { // Increments the transient version to invalidate cache WC_Cache_Helper::get_transient_version('product_query', true); // If not using an external caching system, we can clear the transients out manually and avoid filling our DB if (!wp_using_ext_object_cache()) { global $wpdb; $wpdb->query("\n\t\t\t\tDELETE FROM `{$wpdb->options}`\n\t\t\t\tWHERE `option_name` LIKE ('\\_transient\\_wc\\_uf\\_pid\\_%')\n\t\t\t\tOR `option_name` LIKE ('\\_transient\\_timeout\\_wc\\_uf\\_pid\\_%')\n\t\t\t\tOR `option_name` LIKE ('\\_transient\\_wc\\_products\\_will\\_display\\_%')\n\t\t\t\tOR `option_name` LIKE ('\\_transient\\_timeout\\_wc\\_products\\_will\\_display\\_%')\n\t\t\t"); } }
function _get_cron_lock() { global $wpdb; $value = 0; if (wp_using_ext_object_cache()) { // Skip local cache and force refetch of doing_cron transient in case // another processs updated the cache $value = wp_cache_get('doing_cron', 'transient', true); } else { $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", '_transient_doing_cron')); if (is_object($row)) { $value = $row->option_value; } } return $value; }
/** * Delete a user transient * * @param \WP_User|int $user * @param string $transient * * @return bool */ public static final function delete_user_transient($user, $transient) { $user = $user instanceof \WP_User ?: new \WP_User($user); do_action('delete_user_transient_' . $transient, $transient, $user->ID); if (wp_using_ext_object_cache()) { $result = wp_cache_delete("{$transient}-{$user->ID}", 'user_transient'); } else { $result = delete_user_meta($user->ID, "_transient_{$transient}"); if ($result) { delete_user_meta($user->ID, "_transient_timeout_{$transient}"); } } if ($result) { do_action('deleted_user_transient', $transient); } return $result; }
/** * Register the allowed routes. * @param \Slim\Slim $app */ public function __construct(\Slim\Slim $app) { parent::__construct($app); $this->registerRoute('GET', 'posts/?', array(__NAMESPACE__ . '\\controllers\\Posts', 'find')); $this->registerRoute('GET', 'posts/:id/?', array(__NAMESPACE__ . '\\controllers\\Posts', 'findById')); $this->registerRoute('GET', 'posts/:id/comments/?', array(__NAMESPACE__ . '\\controllers\\Comments', 'findByPost')); $this->registerRoute('GET', 'users/?', array(__NAMESPACE__ . '\\controllers\\Users', 'find')); $this->registerRoute('GET', 'users/:id/?', array(__NAMESPACE__ . '\\controllers\\Users', 'findById')); $this->registerRoute('GET', 'taxonomies/?', array(__NAMESPACE__ . '\\controllers\\Taxonomies', 'find')); $this->registerRoute('GET', 'taxonomies/:name/?', array(__NAMESPACE__ . '\\controllers\\Taxonomies', 'findById')); $this->registerRoute('GET', 'taxonomies/:taxonomy_name/terms/?', array(__NAMESPACE__ . '\\controllers\\Terms', 'find')); $this->registerRoute('GET', 'taxonomies/:taxonomy_name/terms/:term_id/?', array(__NAMESPACE__ . '\\controllers\\Terms', 'findById')); $this->registerRoute('GET', 'rewrite_rules/?', array(__NAMESPACE__ . '\\controllers\\RewriteRules', 'find')); $this->registerRoute('GET', 'comments/?', array(__NAMESPACE__ . '\\controllers\\Comments', 'find')); $this->registerRoute('GET', 'comments/:id?', array(__NAMESPACE__ . '\\controllers\\Comments', 'findById')); if (function_exists('wp_using_ext_object_cache') && wp_using_ext_object_cache()) { //add filters for last-modified based off of the 'last_changed' caching in core $filter_last_post_mod = function ($last_modified) { if ($last_changed = wp_cache_get('last_changed', 'posts')) { list($micro, $time) = explode(' ', $last_changed); $last_modified = gmdate('Y-m-d H:i:s', $time); } return $last_modified; }; add_filter('thermal_get_lastpostmodified', $filter_last_post_mod); $filter_last_comment_mod = function ($last_modified) { if ($last_changed = wp_cache_get('last_changed', 'comments')) { list($micro, $time) = explode(' ', $last_changed); $last_modified = gmdate('Y-m-d H:i:s', $time); } return $last_modified; }; add_filter('thermal_get_lastcommentmodified', $filter_last_comment_mod); add_filter('thermal_comment_last_modified', $filter_last_comment_mod); $filter_last_term_mod = function ($last_modified) { if ($last_changed = wp_cache_get('last_changed', 'terms')) { list($micro, $time) = explode(' ', $last_changed); $last_modified = gmdate('Y-m-d H:i:s', $time); } return $last_modified; }; add_filter('thermal_get_lasttermmodified', $filter_last_term_mod); add_filter('thermal_term_last_modified', $filter_last_term_mod); } }
/** * Get an individual setting from RBE's settings array. * * @since 1.0-RC3 * * @param string $setting The setting parameter. * @param array $args { * Misc settings. * @type bool $refetch Whether to refetch RBE's settings. Handy when you * need to ensure the settings are updated. Defaults to false. * } * @return string|bool */ function bp_rbe_get_setting($setting = '', $args = array()) { if (empty($setting) || !is_string($setting)) { return false; } $r = wp_parse_args($args, array('refetch' => false)); global $bp_rbe; // refetches RBE options if (true === $r['refetch']) { // flush cache if necessary if (!wp_using_ext_object_cache()) { wp_cache_flush(); } // refetch option $bp_rbe->settings = bp_get_option('bp-rbe'); } return isset($bp_rbe->settings[$setting]) ? $bp_rbe->settings[$setting] : false; }
/** * Set/update the value of a site transient. * * You do not need to serialize values, if the value needs to be serialize, then * it will be serialized before it is set. * * @since 2.9.0 * * @see set_transient() * * @param string $transient Transient name. Expected to not be SQL-escaped. Must be * 40 characters or fewer in length. * @param mixed $value Transient value. Expected to not be SQL-escaped. * @param int $expiration Optional. Time until expiration in seconds. Default 0. * @return bool False if value was not set and true if value was set. */ function set_site_transient($transient, $value, $expiration = 0) { /** * Filter the value of a specific site transient before it is set. * * The dynamic portion of the hook name, `$transient`, refers to the transient name. * * @since 3.0.0 * @since 4.4.0 The `$transient` parameter was added * * @param mixed $value Value of site transient. * @param string $transient Transient name. */ $value = apply_filters('pre_set_site_transient_' . $transient, $value, $transient); $expiration = (int) $expiration; if (wp_using_ext_object_cache()) { $result = wp_cache_set($transient, $value, 'site-transient', $expiration); } else { $transient_timeout = '_site_transient_timeout_' . $transient; $option = '_site_transient_' . $transient; if (false === get_network_option($option)) { if ($expiration) { add_network_option($transient_timeout, time() + $expiration); } $result = add_network_option($option, $value); } else { if ($expiration) { update_network_option($transient_timeout, time() + $expiration); } $result = update_network_option($option, $value); } } if ($result) { /** * Fires after the value for a specific site transient has been set. * * The dynamic portion of the hook name, `$transient`, refers to the transient name. * * @since 3.0.0 * @since 4.4.0 The `$transient` parameter was added * * @param mixed $value Site transient value. * @param int $expiration Time until expiration in seconds. Default 0. * @param string $transient Transient name. */ do_action('set_site_transient_' . $transient, $value, $expiration, $transient); /** * Fires after the value for a site transient has been set. * * @since 3.0.0 * * @param string $transient The name of the site transient. * @param mixed $value Site transient value. * @param int $expiration Time until expiration in seconds. Default 0. */ do_action('setted_site_transient', $transient, $value, $expiration); } return $result; }
public function testGetTermLastModified() { if (!function_exists('wp_using_ext_object_cache')) { return; } //temporarily turn on object cache since no core methods provide last modified for terms without caching enabled $tmp = wp_using_ext_object_cache(); wp_using_ext_object_cache(true); $testdata = $this->_insertTestData(); list($status, $headers, $body) = $this->_getResponse(array('REQUEST_METHOD' => 'GET', 'PATH_INFO' => Voce\Thermal\get_api_base() . 'v1/taxonomies/public_taxonomy_a/terms/' . $testdata['term_a']['term_id'], 'QUERY_STRING' => '')); $data = json_decode($body); $this->assertEquals('200', $status); $this->assertNotEmpty($headers['last-modified']); $last_modified = $headers['last-modified']; list($status, $headers, $body) = $this->_getResponse(array('REQUEST_METHOD' => 'GET', 'PATH_INFO' => Voce\Thermal\get_api_base() . 'v1/taxonomies/public_taxonomy_a/terms/' . $testdata['term_a']['term_id'], 'QUERY_STRING' => '', 'IF_MODIFIED_SINCE' => $last_modified)); $this->assertEquals('304', $status); $this->assertEmpty($body); wp_using_ext_object_cache($tmp); }
function output($section_name, $config, $options, $return = false, $withoptions = false) { /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { wp_using_ext_object_cache(false); } $uid = 'vp_' . md5(serialize(func_get_args())); if (false === ($data = get_transient('mod_' . $uid))) { $data = op_sl_parse('video_player', array('section_name' => $section_name, 'config' => $config, 'options' => $options, 'use_controls' => $this->use_controls, 'player_count' => $this->player_count)); if (is_string($data) && 0 === strpos($data, '##')) { $data = substr($data, 2); } elseif (!empty($data)) { set_transient('mod_' . $uid, $data, OP_SL_ELEMENT_CACHE_LIFETIME); } else { $data = array('use_controls' => $this->use_controls, 'player_count' => $this->player_count, 'out' => '', 'new_options' => array()); } } if (isset($data['use_controls'])) { $this->use_controls = $data['use_controls']; } if (isset($data['player_count'])) { $this->player_count = $this->player_count + (int) $data['player_count']; } /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { wp_using_ext_object_cache(true); } if ($return) { return $withoptions ? array('output' => $data['out'], 'options' => $data['new_options']) : $data['out']; } echo $data['out']; }
/** * Expected pluggable function signatures. * * @return array Array of signatures keyed by their function name. */ public function getPluggableFunctionSignatures() { $signatures = array('wp_set_current_user' => array('id', 'name' => ''), 'wp_get_current_user' => array(), 'get_userdata' => array('user_id'), 'get_user_by' => array('field', 'value'), 'cache_users' => array('user_ids'), 'wp_mail' => array('to', 'subject', 'message', 'headers' => '', 'attachments' => array()), 'wp_authenticate' => array('username', 'password'), 'wp_logout' => array(), 'wp_validate_auth_cookie' => array('cookie' => '', 'scheme' => ''), 'wp_generate_auth_cookie' => array('user_id', 'expiration', 'scheme' => 'auth', 'token' => ''), 'wp_parse_auth_cookie' => array('cookie' => '', 'scheme' => ''), 'wp_set_auth_cookie' => array('user_id', 'remember' => false, 'secure' => '', 'token' => ''), 'wp_clear_auth_cookie' => array(), 'is_user_logged_in' => array(), 'auth_redirect' => array(), 'check_admin_referer' => array('action' => -1, 'query_arg' => '_wpnonce'), 'check_ajax_referer' => array('action' => -1, 'query_arg' => false, 'die' => true), 'wp_redirect' => array('location', 'status' => 302), 'wp_sanitize_redirect' => array('location'), '_wp_sanitize_utf8_in_redirect' => array('matches'), 'wp_safe_redirect' => array('location', 'status' => 302), 'wp_validate_redirect' => array('location', 'default' => ''), 'wp_notify_postauthor' => array('comment_id', 'deprecated' => null), 'wp_notify_moderator' => array('comment_id'), 'wp_password_change_notification' => array('user'), 'wp_new_user_notification' => array('user_id', 'deprecated' => null, 'notify' => ''), 'wp_nonce_tick' => array(), 'wp_verify_nonce' => array('nonce', 'action' => -1), 'wp_create_nonce' => array('action' => -1), 'wp_salt' => array('scheme' => 'auth'), 'wp_hash' => array('data', 'scheme' => 'auth'), 'wp_hash_password' => array('password'), 'wp_check_password' => array('password', 'hash', 'user_id' => ''), 'wp_generate_password' => array('length' => 12, 'special_chars' => true, 'extra_special_chars' => false), 'wp_rand' => array('min' => 0, 'max' => 0), 'wp_set_password' => array('password', 'user_id'), 'get_avatar' => array('id_or_email', 'size' => 96, 'default' => '', 'alt' => '', 'args' => null), 'wp_text_diff' => array('left_string', 'right_string', 'args' => null), 'install_network' => array(), 'wp_install' => array('blog_title', 'user_name', 'user_email', 'public', 'deprecated' => '', 'user_password' => '', 'language' => ''), 'wp_install_defaults' => array('user_id'), 'wp_new_blog_notification' => array('blog_title', 'blog_url', 'user_id', 'password'), 'wp_upgrade' => array(), 'install_global_terms' => array()); // Pluggable function signatures are not tested when an external object cache is in use. #31491 if (!wp_using_ext_object_cache()) { $signatures = array_merge($signatures, array('wp_cache_add' => array('key', 'data', 'group' => '', 'expire' => 0), 'wp_cache_close' => array(), 'wp_cache_decr' => array('key', 'offset' => 1, 'group' => ''), 'wp_cache_delete' => array('key', 'group' => ''), 'wp_cache_flush' => array(), 'wp_cache_get' => array('key', 'group' => '', 'force' => false, 'found' => null), 'wp_cache_incr' => array('key', 'offset' => 1, 'group' => ''), 'wp_cache_init' => array(), 'wp_cache_replace' => array('key', 'data', 'group' => '', 'expire' => 0), 'wp_cache_set' => array('key', 'data', 'group' => '', 'expire' => 0), 'wp_cache_switch_to_blog' => array('blog_id'), 'wp_cache_add_global_groups' => array('groups'), 'wp_cache_add_non_persistent_groups' => array('groups'), 'wp_cache_reset' => array())); } return $signatures; }
/** * Invalidate sitemap cache * * @param null|string $type The type to get the key for. Null for all caches. * * @return void */ public static function invalidate_storage($type = null) { // Global validator gets cleared when no type is provided. $old_validator = null; // Get the current type validator. if (!is_null($type)) { $old_validator = self::get_validator($type); } // Refresh validator. self::create_validator($type); if (!wp_using_ext_object_cache()) { // Clean up current cache from the database. self::cleanup_database($type, $old_validator); } // External object cache pushes old and unretrieved items out by itself so we don't have to do anything for that. }
/** * get the views * * @params int $post_id * @return int the views * @version 2.0.0 * */ public static function get_views($post_id = null) { if (!$post_id) { global $post; $post_id = $post->ID; } $meta = (int) get_post_meta($post_id, self::$post_meta_key, true) + 1; if (wp_using_ext_object_cache()) { return $meta + (int) wp_cache_get($post_id, __CLASS__); } return $meta; }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @todo determine early if the query can be run using ES, otherwise defer to WP_Query * * @return array List of posts. */ public function get_posts() { global $wpdb; /** * In addition to what's below, other fields include: * post_id * post_author * post_author.user_nicename * post_date * post_date.year * post_date.month * post_date.week * post_date.day * post_date.day_of_year * post_date.day_of_week * post_date.hour * post_date.minute * post_date.second * post_date_gmt (plus all the same tokens as post_date) * post_content * post_content.analyzed * post_title * post_title.analyzed * post_excerpt * post_status * ping_status * post_password * post_name * post_modified (plus all the same tokens as post_date) * post_modified_gmt (plus all the same tokens as post_date) * post_parent * menu_order * post_type * post_mime_type * comment_count */ $this->es_map = apply_filters('es_field_map', array('post_meta' => 'post_meta.%s', 'post_meta.analyzed' => 'post_meta.%s.analyzed', 'post_meta.long' => 'post_meta.%s.long', 'post_meta.double' => 'post_meta.%s.double', 'post_meta.binary' => 'post_meta.%s.boolean', 'post_meta.date' => 'post_meta.%s.date', 'post_meta.datetime' => 'post_meta.%s.datetime', 'post_meta.time' => 'post_meta.%s.time', 'post_meta.signed' => 'post_meta.%s.signed', 'post_meta.unsigned' => 'post_meta.%s.unsigned', 'term_id' => 'terms.%s.term_id', 'term_slug' => 'terms.%s.slug', 'term_name' => 'terms.%s.name', 'term_tt_id' => 'terms.%s.term_taxonomy_id', 'category_id' => 'terms.%s.term_id', 'category_slug' => 'terms.%s.slug', 'category_name' => 'terms.%s.name', 'category_tt_id' => 'terms.%s.term_taxonomy_id', 'tag_id' => 'terms.%s.term_id', 'tag_slug' => 'terms.%s.slug', 'tag_name' => 'terms.%s.name', 'tag_tt_id' => 'terms.%s.term_taxonomy_id')); $this->parse_query(); if (isset($this->query_vars['es'])) { unset($this->query_vars['es']); } do_action_ref_array('pre_get_posts', array(&$this)); do_action_ref_array('es_pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new ES_WP_Meta_Query(); $this->meta_query->parse_query_vars($q); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5(serialize($this->query_vars)); if ($hash != $this->query_vars_hash) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $post_status_join = false; $page = 1; // ES $filter = array(); $query = array(); $sort = array(); $fields = array(); $from = 0; $size = 10; if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if (wp_using_ext_object_cache()) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } switch ($q['fields']) { case 'ids': $fields = array($this->es_map('post_id')); break; case 'id=>parent': $fields = array($this->es_map('post_id'), $this->es_map('post_parent')); break; default: if (apply_filters('es_query_use_source', false)) { $fields = array('_source'); } else { $fields = array($this->es_map('post_id')); } } if ('' !== $q['menu_order']) { $filter[] = $this->dsl_terms($this->es_map('menu_order'), $q['menu_order']); } // The "m" parameter is meant for months but accepts datetimes of varying specificity if ($q['m']) { $date = array('year' => substr($q['m'], 0, 4)); $m_len = strlen($q['m']); if ($m_len > 5) { $date['month'] = substr($q['m'], 4, 2); } if ($m_len > 7) { $date['day'] = substr($q['m'], 6, 2); } if ($m_len > 9) { $date['hour'] = substr($q['m'], 8, 2); } if ($m_len > 11) { $date['minute'] = substr($q['m'], 10, 2); } if ($m_len > 13) { $date['second'] = substr($q['m'], 12, 2); // If we have absolute precision, we can use a term filter instead of a range $filter[] = $this->dsl_terms($this->es_map('post_date'), ES_WP_Date_Query::build_datetime($date)); } else { // We don't have second-level precision, so we need to build a range query from what we have $date_query = new ES_WP_Date_Query(array('after' => $date, 'before' => $date, 'inclusive' => true)); $date_filter = $date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } } } unset($date_query, $date_filter, $date, $m_len); // Handle the other individual date parameters $date_parameters = array(); if ('' !== $q['hour']) { $date_parameters['hour'] = $q['hour']; } if ('' !== $q['minute']) { $date_parameters['minute'] = $q['minute']; } if ('' !== $q['second']) { $date_parameters['second'] = $q['second']; } if ($q['year']) { $date_parameters['year'] = $q['year']; } if ($q['monthnum']) { $date_parameters['month'] = $q['monthnum']; } if ($q['w']) { $date_parameters['week'] = $q['w']; } if ($q['day']) { $date_parameters['day'] = $q['day']; } if ($date_parameters) { $date_query = new ES_WP_Date_Query(array($date_parameters)); $date_filter = $date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } } unset($date_parameters, $date_query, $date_filter); // Handle complex date queries if (!empty($q['date_query'])) { $this->date_query = new ES_WP_Date_Query($q['date_query']); $date_filter = $this->date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } unset($date_filter); } // If we've got a post_type AND it's not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' != $q['name']) { $q['name'] = sanitize_title_for_query($q['name']); $filter[] = $this->dsl_terms($this->es_map('post_name'), $q['name']); } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename'])); $q['name'] = $q['pagename']; $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($reqpage)); $reqpage_obj = get_post($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment'])); $q['name'] = $q['attachment']; $filter[] = $this->dsl_terms($this->es_map('post_name'), $q['attachment']); } if (isset($q['comments_popup']) && intval($q['comments_popup'])) { $q['p'] = absint($q['comments_popup']); } // If an attachment is requested by number, let it supersede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($q['p'])); } elseif ($q['post__in']) { $post__in = array_map('absint', $q['post__in']); $filter[] = $this->dsl_terms($this->es_map('post_id'), $post__in); } elseif ($q['post__not_in']) { $post__not_in = array_map('absint', $q['post__not_in']); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_id'), $post__not_in)); } if (is_numeric($q['post_parent'])) { $filter[] = $this->dsl_terms($this->es_map('post_parent'), absint($q['post_parent'])); } elseif ($q['post_parent__in']) { $post_parent__in = array_map('absint', $q['post_parent__in']); $filter[] = $this->dsl_terms($this->es_map('post_parent'), $post_parent__in); } elseif ($q['post_parent__not_in']) { $post_parent__not_in = array_map('absint', $q['post_parent__not_in']); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_parent'), $post_parent__not_in)); } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($q['page_id'])); } } // If a search pattern is specified, load the posts that match. if (!empty($q['s'])) { $search = $this->parse_search($q); } /** * Filter the search query. * * @param string $search Search filter for ES query. * @param ES_WP_Query $this The current ES_WP_Query object. */ if (!empty($search)) { $query['must'] = apply_filters_ref_array('es_posts_search', array($search, &$this)); if (!is_user_logged_in()) { $filter[] = array('or' => array($this->dsl_terms($this->es_map('post_password'), ''), $this->dsl_missing($this->es_map('post_password')))); } } // Taxonomies if (!$this->is_singular) { $this->parse_tax_query($q); $this->tax_query = new ES_WP_Tax_Query($this->tax_query); $tax_filter = $this->tax_query->get_dsl($this); if (false === $tax_filter) { return $this->no_results(); } if (!empty($tax_filter)) { $filter[] = $tax_filter; } unset($tax_filter); } if ($this->is_tax) { if (empty($post_type)) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = wp_list_pluck($this->tax_query->queries, 'taxonomy'); foreach (get_post_types(array('exclude_from_search' => false)) as $pt) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies($pt); if (array_intersect($taxonomies, $object_taxonomies)) { $post_type[] = $pt; } } if (!$post_type) { $post_type = 'any'; } elseif (count($post_type) == 1) { $post_type = $post_type[0]; } // @todo: no good way to do this in ES; workarounds? $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { // @todo: no good way to do this in ES; workarounds? $post_status_join = true; } } // Back-compat if (!empty($this->tax_query->queries)) { $tax_query_in_and = wp_list_filter($this->tax_query->queries, array('operator' => 'NOT IN'), 'NOT'); if (!empty($tax_query_in_and)) { if (!isset($q['taxonomy'])) { foreach ($tax_query_in_and as $a_tax_query) { if (!in_array($a_tax_query['taxonomy'], array('category', 'post_tag'))) { $q['taxonomy'] = $a_tax_query['taxonomy']; if ('slug' == $a_tax_query['field']) { $q['term'] = $a_tax_query['terms'][0]; } else { $q['term_id'] = $a_tax_query['terms'][0]; } break; } } } $cat_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'category')); if (!empty($cat_query)) { $cat_query = reset($cat_query); if (!empty($cat_query['terms'][0])) { $the_cat = get_term_by($cat_query['field'], $cat_query['terms'][0], 'category'); if ($the_cat) { $this->set('cat', $the_cat->term_id); $this->set('category_name', $the_cat->slug); } unset($the_cat); } } unset($cat_query); $tag_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'post_tag')); if (!empty($tag_query)) { $tag_query = reset($tag_query); if (!empty($tag_query['terms'][0])) { $the_tag = get_term_by($tag_query['field'], $tag_query['terms'][0], 'post_tag'); if ($the_tag) { $this->set('tag_id', $the_tag->term_id); } unset($the_tag); } } unset($tag_query); } } // @todo: hmmmm if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) { $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if (!empty($q['author']) && $q['author'] != '0') { $q['author'] = addslashes_gpc('' . urldecode($q['author'])); $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author']))); foreach ($authors as $author) { $key = $author > 0 ? 'author__in' : 'author__not_in'; $q[$key][] = abs($author); } $q['author'] = implode(',', $authors); } if (!empty($q['author__not_in'])) { $author__not_in = array_map('absint', array_unique((array) $q['author__not_in'])); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_author'), $author__not_in)); } elseif (!empty($q['author__in'])) { $author__in = array_map('absint', array_unique((array) $q['author__in'])); $filter[] = $this->dsl_terms($this->es_map('post_author'), $author__in); } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query($q['author_name']); $filter[] = $this->dsl_terms($this->es_map('post_author.user_nicename'), $q['author_name']); } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $es_mime = $this->post_mime_type_query($q['post_mime_type'], $wpdb->posts); if (!empty($es_mime['filters'])) { $filter[] = $es_mime['filters']; } if (!empty($es_mime['query'])) { if (empty($query['should'])) { $query['should'] = $es_mime['query']; } else { $query['should'] = array_merge($query['should'], $es_mime['query']); } } } if (!isset($q['order'])) { $q['order'] = 'desc'; } else { $q['order'] = $this->parse_order($q['order']); } // Order by if (empty($q['orderby'])) { /* * Boolean false or empty array blanks out ORDER BY, * while leaving the value unset or otherwise empty sets the default. */ if (isset($q['orderby']) && (is_array($q['orderby']) || false === $q['orderby'])) { $orderby = ''; } else { $sort[] = array($this->es_map('post_date') => $q['order']); } } elseif ('none' == $q['orderby']) { // nothing to see here } elseif ($q['orderby'] == 'post__in' && !empty($post__in)) { // @todo: Figure this out... Elasticsearch doesn't have an equivalent of this // $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )"; } elseif ($q['orderby'] == 'post_parent__in' && !empty($post_parent__in)) { // (see above) // $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )"; } else { if (is_array($q['orderby'])) { foreach ($q['orderby'] as $_orderby => $order) { $orderby = addslashes_gpc(urldecode($_orderby)); $parsed = $this->parse_orderby($orderby); if (!$parsed) { continue; } $sort[] = array($parsed => $this->parse_order($order)); } } else { $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); foreach (explode(' ', $q['orderby']) as $i => $orderby) { $parsed = $this->parse_orderby($orderby); // Only allow certain values for safety. if (!$parsed) { continue; } $sort[] = array($parsed => $q['order']); } if (empty($sort)) { $sort[] = array($this->es_map('post_date') => $q['order']); } } } // Order search results by relevance only when another "orderby" is not specified in the query. if (!empty($q['s'])) { $search_orderby = array(); if (empty($q['orderby']) && !$this->is_feed || isset($q['orderby']) && 'relevance' === $q['orderby']) { $search_orderby = array('_score'); } /** * Filter the order used when ordering search results. * * @param array $search_orderby The order clause. * @param ES_WP_Query $this The current ES_WP_Query instance. */ $search_orderby = apply_filters('es_posts_search_orderby', $search_orderby, $this); if ($search_orderby) { $sort = $sort ? array_merge($search_orderby, $sort) : $search_orderby; } } if (is_array($post_type) && count($post_type) > 1) { $post_type_cap = 'multiple_post_type'; } else { if (is_array($post_type)) { $post_type = reset($post_type); } $post_type_object = get_post_type_object($post_type); if (empty($post_type_object)) { $post_type_cap = $post_type; } } if ('any' == $post_type) { $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (empty($in_search_post_types)) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } else { $filter[] = $this->dsl_terms($this->es_map('post_type'), array_values($in_search_post_types)); } } elseif (!empty($post_type)) { $filter[] = $this->dsl_terms($this->es_map('post_type'), array_values((array) $post_type)); if (!is_array($post_type)) { $post_type_object = get_post_type_object($post_type); } } elseif ($this->is_attachment) { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'attachment'); $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'page'); $post_type_object = get_post_type_object('page'); } else { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'post'); $post_type_object = get_post_type_object('post'); } $edit_cap = 'edit_post'; $read_cap = 'read_post'; if (!empty($post_type_object)) { $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } $user_id = get_current_user_id(); if (!empty($q['post_status'])) { $statuswheres = array(); $q_status = $q['post_status']; if (!is_array($q_status)) { $q_status = explode(',', $q_status); } $r_status = array(); $p_status = array(); $e_status = array(); if (in_array('any', $q_status)) { $e_status = get_post_stati(array('exclude_from_search' => true)); $e_status = array_values($e_status); } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = $status; } else { $r_status[] = $status; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { // $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")"; $status_ands[] = array('not' => $this->dsl_terms($this->es_map('post_status'), $e_status)); } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { // $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))"; $status_ands[] = array('bool' => array('must' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $r_status)))); } else { // $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")"; $status_ands[] = $this->dsl_terms($this->es_map('post_status'), $r_status); } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { // $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))"; $status_ands[] = array('bool' => array('must' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $p_status)))); } else { // $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")"; $status_ands[] = $this->dsl_terms($this->es_map('post_status'), $p_status); } } if ($post_status_join) { // @todo: no good way to do this in ES... /* $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) "; foreach ( $statuswheres as $index => $statuswhere ) $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; */ } $filter = array_merge($filter, $status_ands); } elseif (!$this->is_singular) { $singular_states = array('publish'); // Add public states. $singular_states = array_merge($singular_states, (array) get_post_stati(array('public' => true))); if ($this->is_admin) { // Add protected states that should show in the admin all list. $singular_states = array_merge($singular_states, (array) get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true))); } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); $singular_states_ors = array(); foreach ((array) $private_states as $state) { // @todo: leaving off here if (current_user_can($read_private_cap)) { $singular_states[] = $state; } else { $singular_states_ors[] = array('and' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $state))); } } } $singular_states = array_values(array_unique($singular_states)); $singular_states_filter = $this->dsl_terms($this->es_map('post_status'), $singular_states); if (!empty($singular_states_ors)) { $singular_states_ors[] = $singular_states_filter; $filter[] = array('or' => $singular_states_ors); } else { $filter[] = $singular_states_filter; } unset($singular_states, $singular_states_filter, $singular_states_ors, $private_states); } if (!empty($this->meta_query->queries)) { $filter[] = $this->meta_query->get_dsl($this, 'post'); } // Apply filters on the filter clause prior to paging so that any // manipulations to them are reflected in the paging by day queries. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_query_filter', array($filter, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (!$page) { $page = 1; } if (empty($q['offset'])) { $from = ($page - 1) * $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $from = absint($q['offset']); } $size = $q['posts_per_page']; } else { $from = $size = false; } // Comments feeds // @todo: come back to this if (0 && $this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { $cjoin = apply_filters_ref_array('es_comment_feed_join', array($cjoin, &$this)); $cwhere = apply_filters_ref_array('es_comment_feed_where', array($cwhere, &$this)); $cgroupby = apply_filters_ref_array('es_comment_feed_groupby', array($cgroupby, &$this)); $corderby = apply_filters_ref_array('es_comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $climits = apply_filters_ref_array('es_comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } // Run cleanup on our filter and query $filter = array_filter($filter); if (!empty($filter)) { $filter = array('and' => $filter); } $query = array_filter($query); if (!empty($query)) { if (1 == count($query) && !empty($query['must']) && 1 == count($query['must'])) { $query = $query['must']; } else { $query = array('bool' => $query); if (!empty($query['bool']['should'])) { $query['bool']['minimum_should_match'] = 1; } } } $pieces = array('filter', 'query', 'sort', 'fields', 'size', 'from'); // Apply post-paging filters on our clauses. Only plugins that // manipulate paging queries should use these hooks. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_posts_filter_paged', array($filter, &$this)); $query = apply_filters_ref_array('es_posts_query_paged', array($query, &$this)); $sort = apply_filters_ref_array('es_posts_sort', array($sort, &$this)); $fields = apply_filters_ref_array('es_posts_fields', array($fields, &$this)); $size = apply_filters_ref_array('es_posts_size', array($size, &$this)); $from = apply_filters_ref_array('es_posts_from', array($from, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('es_posts_clauses', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } // Announce current selection parameters. For use by caching plugins. do_action('es_posts_selection', array('filter' => $filter, 'query' => $query, 'sort' => $sort, 'fields' => $fields, 'size' => $size, 'from' => $from)); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_posts_filter_request', array($filter, &$this)); $query = apply_filters_ref_array('es_posts_query_request', array($query, &$this)); $sort = apply_filters_ref_array('es_posts_sort_request', array($sort, &$this)); $fields = apply_filters_ref_array('es_posts_fields_request', array($fields, &$this)); $size = apply_filters_ref_array('es_posts_size_request', array($size, &$this)); $from = apply_filters_ref_array('es_posts_from_request', array($from, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('es_posts_clauses_request', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } $this->es_args = array('filter' => $filter, 'query' => $query, 'sort' => $sort, 'fields' => $fields, 'from' => $from, 'size' => $size); // Remove empty criteria foreach ($this->es_args as $key => $value) { if (empty($value) && 0 !== $value) { unset($this->es_args[$key]); } } // Elasticsearch needs a size, so we set it very high if posts_per_page = -1 if (-1 == $q['posts_per_page'] && !isset($this->es_args['size'])) { $this->es_args['size'] = $size = apply_filters('es_query_max_results', 1000); } $old_args = $this->es_args; if (!$q['suppress_filters']) { $this->es_args = apply_filters_ref_array('es_posts_request', array($this->es_args, &$this)); } if ('ids' == $q['fields'] || 'id=>parent' == $q['fields']) { $this->es_response = $this->query_es($this->es_args); $this->set_posts($q, $this->es_response); $this->post_count = count($this->posts); $this->set_found_posts($q, $this->es_response); return $this->posts; } $this->es_response = $this->query_es($this->es_args); $this->set_posts($q, $this->es_response); $this->set_found_posts($q, $this->es_response); // The rest of this method is mostly core // Convert to WP_Post objects if ($this->posts) { $this->posts = array_map('get_post', $this->posts); } // Raw results filter. Prior to status checks. if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('es_posts_results', array($this->posts, &$this)); } // @todo: address this if (0 && !empty($this->posts) && $this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters_ref_array('es_comment_feed_join', array('', &$this)); $cwhere = apply_filters_ref_array('es_comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); $cgroupby = apply_filters_ref_array('es_comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('es_comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('es_comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if (!$post_status_obj->public) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts[0] = get_post(apply_filters_ref_array('es_the_preview', array($this->posts[0], &$this))); } } // @todo: address this // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if (0 && $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies = get_posts(array('post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true)); foreach ($stickies as $sticky_post) { array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('es_the_posts', array($this->posts, &$this)); } // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ($this->posts) { $this->post_count = count($this->posts); $this->posts = array_map('get_post', $this->posts); if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } $this->post = reset($this->posts); } else { $this->post_count = 0; $this->posts = array(); } return $this->posts; }
/** * Returns all menu items of a navigation menu. * * @since 3.0.0 * * @param string $menu menu name, id, or slug * @param string $args * @return mixed $items array of menu items, else false. */ function wp_get_nav_menu_items($menu, $args = array()) { $menu = wp_get_nav_menu_object($menu); if (!$menu) { return false; } static $fetched = array(); $items = get_objects_in_term($menu->term_id, 'nav_menu'); if (empty($items)) { return $items; } $defaults = array('order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'nav_menu_item', 'post_status' => 'publish', 'output' => ARRAY_A, 'output_key' => 'menu_order', 'nopaging' => true); $args = wp_parse_args($args, $defaults); if (count($items) > 1) { $args['include'] = implode(',', $items); } else { $args['include'] = $items[0]; } $items = get_posts($args); if (is_wp_error($items) || !is_array($items)) { return false; } // Get all posts and terms at once to prime the caches if (empty($fetched[$menu->term_id]) || wp_using_ext_object_cache()) { $fetched[$menu->term_id] = true; $posts = array(); $terms = array(); foreach ($items as $item) { $object_id = get_post_meta($item->ID, '_menu_item_object_id', true); $object = get_post_meta($item->ID, '_menu_item_object', true); $type = get_post_meta($item->ID, '_menu_item_type', true); if ('post_type' == $type) { $posts[$object][] = $object_id; } elseif ('taxonomy' == $type) { $terms[$object][] = $object_id; } } if (!empty($posts)) { foreach (array_keys($posts) as $post_type) { get_posts(array('post__in' => $posts[$post_type], 'post_type' => $post_type, 'nopaging' => true, 'update_post_term_cache' => false)); } } unset($posts); if (!empty($terms)) { foreach (array_keys($terms) as $taxonomy) { get_terms($taxonomy, array('include' => $terms[$taxonomy])); } } unset($terms); } $items = array_map('wp_setup_nav_menu_item', $items); if (!is_admin()) { // Remove invalid items only in frontend $items = array_filter($items, '_is_valid_nav_menu_item'); } if (ARRAY_A == $args['output']) { $GLOBALS['_menu_item_sort_prop'] = $args['output_key']; usort($items, '_sort_nav_menu_items'); $i = 1; foreach ($items as $k => $item) { $items[$k]->{$args}['output_key'] = $i++; } } /** * Filter the navigation menu items being returned. * * @since 3.0.0 * * @param array $items An array of menu item post objects. * @param object $menu The menu object. * @param array $args An array of arguments used to retrieve menu item objects. */ return apply_filters('wp_get_nav_menu_items', $items, $menu, $args); }
/** * Start the WordPress object cache. * * If an object-cache.php file exists in the wp-content directory, * it uses that drop-in as an external object cache. * * @since 3.0.0 * @access private * * @global int $blog_id Blog ID. */ function wp_start_object_cache() { global $blog_id; $first_init = false; if (!function_exists('wp_cache_init')) { if (file_exists(WP_CONTENT_DIR . '/object-cache.php')) { require_once WP_CONTENT_DIR . '/object-cache.php'; if (function_exists('wp_cache_init')) { wp_using_ext_object_cache(true); } } $first_init = true; } elseif (!wp_using_ext_object_cache() && file_exists(WP_CONTENT_DIR . '/object-cache.php')) { /* * Sometimes advanced-cache.php can load object-cache.php before * it is loaded here. This breaks the function_exists check above * and can result in `$_wp_using_ext_object_cache` being set * incorrectly. Double check if an external cache exists. */ wp_using_ext_object_cache(true); } if (!wp_using_ext_object_cache()) { require_once ABSPATH . WPINC . '/cache.php'; } /* * If cache supports reset, reset instead of init if already * initialized. Reset signals to the cache that global IDs * have changed and it may need to update keys and cleanup caches. */ if (!$first_init && function_exists('wp_cache_switch_to_blog')) { wp_cache_switch_to_blog($blog_id); } elseif (function_exists('wp_cache_init')) { wp_cache_init(); } if (function_exists('wp_cache_add_global_groups')) { wp_cache_add_global_groups(array('users', 'userlogins', 'usermeta', 'user_meta', 'useremail', 'userslugs', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache')); wp_cache_add_non_persistent_groups(array('comment', 'counts', 'plugins')); } }
/** * Prime the post cache with swapped post_content. This is a sneaky way of getting around * the fact that there are no good hooks to call on the *.getPost xmlrpc methods. * * @return null */ private function prime_post_cache($post_id = false) { global $wp_xmlrpc_server; if (!$post_id) { $post_id = $wp_xmlrpc_server->message->params[0]; } // prime the post cache if ($this->is_markdown($post_id)) { $post = get_post($post_id); if (!empty($post->post_content_filtered)) { wp_cache_delete($post->ID, 'posts'); $post = $this->swap_for_editing($post); wp_cache_add($post->ID, $post, 'posts'); $this->posts_to_uncache[] = $post_id; } } // uncache munged posts if using a persistent object cache if (wp_using_ext_object_cache()) { add_action('shutdown', array($this, 'uncache_munged_posts')); } }
/** * Get array of related posts matched by ElasticSearch. * * @param int $post_id * @param int $size * @param array $filters * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta * @return array */ protected function _get_related_post_ids($post_id, $size, array $filters) { $now_ts = time(); $cache_meta_key = '_jetpack_related_posts_cache'; $body = array('size' => (int) $size); if (!empty($filters)) { $body['filter'] = array('and' => $filters); } // Build cache key $cache_key = md5(serialize($body)); // Load all cached values if (wp_using_ext_object_cache()) { $transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}"; $cache = get_transient($transient_name); if (false !== $cache) { return $cache; } } else { $cache = get_post_meta($post_id, $cache_meta_key, true); if (empty($cache)) { $cache = array(); } // Cache is valid! Return cached value. if (isset($cache[$cache_key]) && is_array($cache[$cache_key]) && $cache[$cache_key]['expires'] > $now_ts) { return $cache[$cache_key]['payload']; } } $response = wp_remote_post("https://public-api.wordpress.com/rest/v1/sites/{$this->_blog_id_wpcom}/posts/{$post_id}/related/", array('timeout' => 10, 'user-agent' => 'jetpack_related_posts', 'sslverify' => true, 'body' => $body)); // Oh no... return nothing don't cache errors. if (is_wp_error($response)) { if (isset($cache[$cache_key]) && is_array($cache[$cache_key])) { return $cache[$cache_key]['payload']; } else { return array(); } } $results = json_decode(wp_remote_retrieve_body($response), true); $related_posts = array(); if (is_array($results) && !empty($results['hits'])) { foreach ($results['hits'] as $hit) { $related_posts[] = array('id' => $hit['fields']['post_id']); } } // An empty array might indicate no related posts or that posts // are not yet synced to WordPress.com, so we cache for only 1 // minute in this case if (empty($related_posts)) { $cache_ttl = 60; } else { $cache_ttl = 12 * HOUR_IN_SECONDS; } // Update cache if (wp_using_ext_object_cache()) { set_transient($transient_name, $related_posts, $cache_ttl); } else { // Copy all valid cache values $new_cache = array(); foreach ($cache as $k => $v) { if (is_array($v) && $v['expires'] > $now_ts) { $new_cache[$k] = $v; } } // Set new cache value $cache_expires = $cache_ttl + $now_ts; $new_cache[$cache_key] = array('expires' => $cache_expires, 'payload' => $related_posts); update_post_meta($post_id, $cache_meta_key, $new_cache); } return $related_posts; }
static function tour($atts) { /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { wp_using_ext_object_cache(false); } // Decode encoded chars $atts = op_urldecode($atts); $uid = 'tour_' . md5(serialize($atts)); if (false === ($markup = get_transient('el_' . $uid))) { $vars = shortcode_atts(array('style' => '1', 'get_started_link' => '', 'get_started_text' => '', 'tour_link' => '', 'tour_text' => '', 'headline' => '', 'subheadline' => ''), $atts); $markup = op_sl_parse('tour', $vars); if (is_string($markup) && 0 === strpos($markup, '##')) { $markup = substr($markup, 2); } elseif (!empty($markup)) { set_transient('el_' . $uid, $markup, OP_SL_ELEMENT_CACHE_LIFETIME); } } /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { wp_using_ext_object_cache(true); } return $markup; }
public function getFollowUpSequences() { /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { $extCache = wp_using_ext_object_cache(); if (true === $extCache) { wp_using_ext_object_cache(false); } } /* * Cache key consist of an hour value on purpose to be sure that cache will be invalidated every hour. * This is due to some plugins deleting _transient_timeout_* option and leaving _transient_* which makes it valid everytime. It won't expire. */ $cacheKey = md5($this->cachePrefix . '_' . __FUNCTION__ . date('H')); if (false === ($data = get_transient($cacheKey))) { $data = $this->provider->getFollowUpSequences(); uasort($data['lists'], array($this, 'sort')); set_transient($cacheKey, $data, self::CACHE_EXPIRY_TIME); } /* * Cache busting */ if (function_exists('wp_using_ext_object_cache')) { wp_using_ext_object_cache($extCache); } return $data; }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * * @return array List of posts. */ public function get_posts() { $this->parse_query(); /** * Fires after the query variable object is created, but before the actual query is run. * * Note: If using conditional tags, use the method versions within the passed instance * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions * like is_main_query() test against the global $wp_query instance, not the passed one. * * @since 2.0.0 * * @param WP_Query &$this The WP_Query instance (passed by reference). */ do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars($q); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5(serialize($this->query_vars)); if ($hash != $this->query_vars_hash) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $post_status_join = false; $page = 1; if (isset($q['caller_get_posts'])) { _deprecated_argument('WP_Query', '3.1.0', __('"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.')); if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = $q['caller_get_posts']; } } if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if (wp_using_ext_object_cache()) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['lazy_load_term_meta'])) { $q['lazy_load_term_meta'] = $q['update_post_term_cache']; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (empty($q['posts_per_page'])) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { // This overrides posts_per_page. if (!empty($q['posts_per_rss'])) { $q['posts_per_page'] = $q['posts_per_rss']; } else { $q['posts_per_page'] = get_option('posts_per_rss'); } $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } elseif ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if (isset($q['no_found_rows'])) { $q['no_found_rows'] = (bool) $q['no_found_rows']; } else { $q['no_found_rows'] = false; } switch ($q['fields']) { case 'ids': $fields = "{$this->db->posts}.ID"; break; case 'id=>parent': $fields = "{$this->db->posts}.ID, {$this->db->posts}.post_parent"; break; default: $fields = "{$this->db->posts}.*"; } if ('' !== $q['menu_order']) { $where .= " AND {$this->db->posts}.menu_order = " . $q['menu_order']; } // The "m" parameter is meant for months but accepts datetimes of varying specificity if ($q['m']) { $where .= " AND YEAR({$this->db->posts}.post_date)=" . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= " AND MONTH({$this->db->posts}.post_date)=" . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= " AND DAYOFMONTH({$this->db->posts}.post_date)=" . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= " AND HOUR({$this->db->posts}.post_date)=" . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= " AND MINUTE({$this->db->posts}.post_date)=" . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= " AND SECOND({$this->db->posts}.post_date)=" . substr($q['m'], 12, 2); } } // Handle the other individual date parameters $date_parameters = array(); if ('' !== $q['hour']) { $date_parameters['hour'] = $q['hour']; } if ('' !== $q['minute']) { $date_parameters['minute'] = $q['minute']; } if ('' !== $q['second']) { $date_parameters['second'] = $q['second']; } if ($q['year']) { $date_parameters['year'] = $q['year']; } if ($q['monthnum']) { $date_parameters['monthnum'] = $q['monthnum']; } if ($q['w']) { $date_parameters['week'] = $q['w']; } if ($q['day']) { $date_parameters['day'] = $q['day']; } if ($date_parameters) { $date_query = new WP_Date_Query(array($date_parameters)); $where .= $date_query->get_sql(); } unset($date_parameters, $date_query); // Handle complex date queries if (!empty($q['date_query'])) { $this->date_query = new WP_Date_Query($q['date_query']); $where .= $this->date_query->get_sql(); } // If we've got a post_type AND it's not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical) { // Non-hierarchical post types can directly use 'name'. $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post types will operate through 'pagename'. $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' !== $q['title']) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_title = %s", stripslashes($q['title'])); } // Parameters related to 'post_name'. if ('' != $q['name']) { $q['name'] = sanitize_title_for_query($q['name']); $where .= " AND {$this->db->posts}.post_name = '" . $q['name'] . "'"; } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename'])); $q['name'] = $q['pagename']; $where .= " AND ({$this->db->posts}.ID = '{$reqpage}')"; $reqpage_obj = get_post($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment'])); $q['name'] = $q['attachment']; $where .= " AND {$this->db->posts}.post_name = '" . $q['attachment'] . "'"; } elseif (is_array($q['post_name__in']) && !empty($q['post_name__in'])) { $q['post_name__in'] = array_map('sanitize_title_for_query', $q['post_name__in']); $post_name__in = "'" . implode("','", $q['post_name__in']) . "'"; $where .= " AND {$this->db->posts}.post_name IN ({$post_name__in})"; } // If an attachment is requested by number, let it supersede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $where .= " AND {$this->db->posts}.ID = " . $q['p']; } elseif ($q['post__in']) { $post__in = implode(',', array_map('absint', $q['post__in'])); $where .= " AND {$this->db->posts}.ID IN ({$post__in})"; } elseif ($q['post__not_in']) { $post__not_in = implode(',', array_map('absint', $q['post__not_in'])); $where .= " AND {$this->db->posts}.ID NOT IN ({$post__not_in})"; } if (is_numeric($q['post_parent'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_parent = %d ", $q['post_parent']); } elseif ($q['post_parent__in']) { $post_parent__in = implode(',', array_map('absint', $q['post_parent__in'])); $where .= " AND {$this->db->posts}.post_parent IN ({$post_parent__in})"; } elseif ($q['post_parent__not_in']) { $post_parent__not_in = implode(',', array_map('absint', $q['post_parent__not_in'])); $where .= " AND {$this->db->posts}.post_parent NOT IN ({$post_parent__not_in})"; } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = " AND {$this->db->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match. if (strlen($q['s'])) { $search = $this->parse_search($q); } if (!$q['suppress_filters']) { /** * Filters the search SQL that is used in the WHERE clause of WP_Query. * * @since 3.0.0 * * @param string $search Search SQL for WHERE clause. * @param WP_Query $this The current WP_Query object. */ $search = apply_filters_ref_array('posts_search', array($search, &$this)); } // Taxonomies if (!$this->is_singular) { $this->parse_tax_query($q); $clauses = $this->tax_query->get_sql($this->db->posts, 'ID'); $join .= $clauses['join']; $where .= $clauses['where']; } if ($this->is_tax) { if (empty($post_type)) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = array_keys($this->tax_query->queried_terms); foreach (get_post_types(array('exclude_from_search' => false)) as $pt) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies($pt); if (array_intersect($taxonomies, $object_taxonomies)) { $post_type[] = $pt; } } if (!$post_type) { $post_type = 'any'; } elseif (count($post_type) == 1) { $post_type = $post_type[0]; } $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { $post_status_join = true; } } /* * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and * 'category_name' vars are set for backward compatibility. */ if (!empty($this->tax_query->queried_terms)) { /* * Set 'taxonomy', 'term', and 'term_id' to the * first taxonomy other than 'post_tag' or 'category'. */ if (!isset($q['taxonomy'])) { foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) { if (empty($queried_items['terms'][0])) { continue; } if (!in_array($queried_taxonomy, array('category', 'post_tag'))) { $q['taxonomy'] = $queried_taxonomy; if ('slug' === $queried_items['field']) { $q['term'] = $queried_items['terms'][0]; } else { $q['term_id'] = $queried_items['terms'][0]; } // Take the first one we find. break; } } } // 'cat', 'category_name', 'tag_id' foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) { if (empty($queried_items['terms'][0])) { continue; } if ('category' === $queried_taxonomy) { $the_cat = get_term_by($queried_items['field'], $queried_items['terms'][0], 'category'); if ($the_cat) { $this->set('cat', $the_cat->term_id); $this->set('category_name', $the_cat->slug); } unset($the_cat); } if ('post_tag' === $queried_taxonomy) { $the_tag = get_term_by($queried_items['field'], $queried_items['terms'][0], 'post_tag'); if ($the_tag) { $this->set('tag_id', $the_tag->term_id); } unset($the_tag); } } } if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) { $groupby = "{$this->db->posts}.ID"; } // Author/user stuff if (!empty($q['author']) && $q['author'] != '0') { $q['author'] = addslashes_gpc('' . urldecode($q['author'])); $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author']))); foreach ($authors as $author) { $key = $author > 0 ? 'author__in' : 'author__not_in'; $q[$key][] = abs($author); } $q['author'] = implode(',', $authors); } if (!empty($q['author__not_in'])) { $author__not_in = implode(',', array_map('absint', array_unique((array) $q['author__not_in']))); $where .= " AND {$this->db->posts}.post_author NOT IN ({$author__not_in}) "; } elseif (!empty($q['author__in'])) { $author__in = implode(',', array_map('absint', array_unique((array) $q['author__in']))); $where .= " AND {$this->db->posts}.post_author IN ({$author__in}) "; } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query($q['author_name']); $q['author'] = get_user_by('slug', $q['author_name']); if ($q['author']) { $q['author'] = $q['author']->ID; } $whichauthor .= " AND ({$this->db->posts}.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $this->db->posts); } $where .= $search . $whichauthor . $whichmimetype; if (!empty($this->meta_query->queries)) { $clauses = $this->meta_query->get_sql('post', $this->db->posts, 'ID', $this); $join .= $clauses['join']; $where .= $clauses['where']; } $rand = isset($q['orderby']) && 'rand' === $q['orderby']; if (!isset($q['order'])) { $q['order'] = $rand ? '' : 'DESC'; } else { $q['order'] = $rand ? '' : $this->parse_order($q['order']); } // Order by. if (empty($q['orderby'])) { /* * Boolean false or empty array blanks out ORDER BY, * while leaving the value unset or otherwise empty sets the default. */ if (isset($q['orderby']) && (is_array($q['orderby']) || false === $q['orderby'])) { $orderby = ''; } else { $orderby = "{$this->db->posts}.post_date " . $q['order']; } } elseif ('none' == $q['orderby']) { $orderby = ''; } elseif ($q['orderby'] == 'post__in' && !empty($post__in)) { $orderby = "FIELD( {$this->db->posts}.ID, {$post__in} )"; } elseif ($q['orderby'] == 'post_parent__in' && !empty($post_parent__in)) { $orderby = "FIELD( {$this->db->posts}.post_parent, {$post_parent__in} )"; } elseif ($q['orderby'] == 'post_name__in' && !empty($post_name__in)) { $orderby = "FIELD( {$this->db->posts}.post_name, {$post_name__in} )"; } else { $orderby_array = array(); if (is_array($q['orderby'])) { foreach ($q['orderby'] as $_orderby => $order) { $orderby = addslashes_gpc(urldecode($_orderby)); $parsed = $this->parse_orderby($orderby); if (!$parsed) { continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order($order); } $orderby = implode(', ', $orderby_array); } else { $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); foreach (explode(' ', $q['orderby']) as $i => $orderby) { $parsed = $this->parse_orderby($orderby); // Only allow certain values for safety. if (!$parsed) { continue; } $orderby_array[] = $parsed; } $orderby = implode(' ' . $q['order'] . ', ', $orderby_array); if (empty($orderby)) { $orderby = "{$this->db->posts}.post_date " . $q['order']; } elseif (!empty($q['order'])) { $orderby .= " {$q['order']}"; } } } // Order search results by relevance only when another "orderby" is not specified in the query. if (!empty($q['s'])) { $search_orderby = ''; if (!empty($q['search_orderby_title']) && (empty($q['orderby']) && !$this->is_feed) || isset($q['orderby']) && 'relevance' === $q['orderby']) { $search_orderby = $this->parse_search_order($q); } if (!$q['suppress_filters']) { /** * Filters the ORDER BY used when ordering search results. * * @since 3.7.0 * * @param string $search_orderby The ORDER BY clause. * @param WP_Query $this The current WP_Query instance. */ $search_orderby = apply_filters('posts_search_orderby', $search_orderby, $this); } if ($search_orderby) { $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby; } } if (is_array($post_type) && count($post_type) > 1) { $post_type_cap = 'multiple_post_type'; } else { if (is_array($post_type)) { $post_type = reset($post_type); } $post_type_object = get_post_type_object($post_type); if (empty($post_type_object)) { $post_type_cap = $post_type; } } if (isset($q['post_password'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_password = %s", $q['post_password']); if (empty($q['perm'])) { $q['perm'] = 'readable'; } } elseif (isset($q['has_password'])) { $where .= sprintf(" AND {$this->db->posts}.post_password %s ''", $q['has_password'] ? '!=' : '='); } if (!empty($q['comment_status'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.comment_status = %s ", $q['comment_status']); } if (!empty($q['ping_status'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.ping_status = %s ", $q['ping_status']); } if ('any' == $post_type) { $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (empty($in_search_post_types)) { $where .= ' AND 1=0 '; } else { $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')"; } } elseif (!empty($post_type) && is_array($post_type)) { $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $post_type) . "')"; } elseif (!empty($post_type)) { $where .= " AND {$this->db->posts}.post_type = '{$post_type}'"; $post_type_object = get_post_type_object($post_type); } elseif ($this->is_attachment) { $where .= " AND {$this->db->posts}.post_type = 'attachment'"; $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $where .= " AND {$this->db->posts}.post_type = 'page'"; $post_type_object = get_post_type_object('page'); } else { $where .= " AND {$this->db->posts}.post_type = 'post'"; $post_type_object = get_post_type_object('post'); } $edit_cap = 'edit_post'; $read_cap = 'read_post'; if (!empty($post_type_object)) { $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } $user_id = get_current_user_id(); $q_status = array(); if (!empty($q['post_status'])) { $statuswheres = array(); $q_status = $q['post_status']; if (!is_array($q_status)) { $q_status = explode(',', $q_status); } $r_status = array(); $p_status = array(); $e_status = array(); if (in_array('any', $q_status)) { foreach (get_post_stati(array('exclude_from_search' => true)) as $status) { if (!in_array($status, $q_status)) { $e_status[] = "{$this->db->posts}.post_status <> '{$status}'"; } } } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = "{$this->db->posts}.post_status = '{$status}'"; } else { $r_status[] = "{$this->db->posts}.post_status = '{$status}'"; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { $statuswheres[] = "(" . join(' AND ', $e_status) . ")"; } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $r_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $r_status) . ")"; } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $p_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $p_status) . ")"; } } if ($post_status_join) { $join .= " LEFT JOIN {$this->db->posts} AS p2 ON ({$this->db->posts}.post_parent = p2.ID) "; foreach ($statuswheres as $index => $statuswhere) { $statuswheres[$index] = "({$statuswhere} OR ({$this->db->posts}.post_status = 'inherit' AND " . str_replace($this->db->posts, 'p2', $statuswhere) . "))"; } } $where_status = implode(' OR ', $statuswheres); if (!empty($where_status)) { $where .= " AND ({$where_status})"; } } elseif (!$this->is_singular) { $where .= " AND ({$this->db->posts}.post_status = 'publish'"; // Add public states. $public_states = get_post_stati(array('public' => true)); foreach ((array) $public_states as $state) { if ('publish' == $state) { // Publish is hard-coded above. continue; } $where .= " OR {$this->db->posts}.post_status = '{$state}'"; } if ($this->is_admin) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true)); foreach ((array) $admin_all_states as $state) { $where .= " OR {$this->db->posts}.post_status = '{$state}'"; } } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); foreach ((array) $private_states as $state) { $where .= current_user_can($read_private_cap) ? " OR {$this->db->posts}.post_status = '{$state}'" : " OR {$this->db->posts}.post_author = {$user_id} AND {$this->db->posts}.post_status = '{$state}'"; } } $where .= ')'; } /* * Apply filters on where and join prior to paging so that any * manipulations to them are reflected in the paging by day queries. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * @since 1.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where', array($where, &$this)); /** * Filters the JOIN clause of the query. * * @since 1.5.0 * * @param string $where The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join', array($join, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (!$page) { $page = 1; } // If 'offset' is provided, it takes precedence over 'paged'. if (isset($q['offset']) && is_numeric($q['offset'])) { $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; } else { $pgstrt = absint(($page - 1) * $q['posts_per_page']) . ', '; } $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } // Comments feeds if ($this->is_comment_feed && !$this->is_singular) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$this->db->posts} ON ({$this->db->comments}.comment_post_ID = {$this->db->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$this->db->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$this->db->posts} ON ( {$this->db->comments}.comment_post_ID = {$this->db->posts}.ID )"; $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' && post_type = 'attachment' ) ) AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { /** * Filters the JOIN clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cjoin The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this)); /** * Filters the WHERE clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cwhere The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this)); /** * Filters the GROUP BY clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cgroupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this)); /** * Filters the ORDER BY clause of the comments feed query before sending. * * @since 2.8.0 * * @param string $corderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); /** * Filters the LIMIT clause of the comments feed query before sending. * * @since 2.8.0 * * @param string $climits The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $comments = (array) $this->db->get_results("SELECT {$distinct} {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); // Convert to WP_Comment $this->comments = array_map('get_comment', $comments); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$this->db->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } $pieces = array('where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits'); /* * Apply post-paging filters on where and join. Only plugins that * manipulate paging queries should use these hooks. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * Specifically for manipulating paging queries. * * @since 1.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where_paged', array($where, &$this)); /** * Filters the GROUP BY clause of the query. * * @since 2.0.0 * * @param string $groupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this)); /** * Filters the JOIN clause of the query. * * Specifically for manipulating paging queries. * * @since 1.5.0 * * @param string $join The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join_paged', array($join, &$this)); /** * Filters the ORDER BY clause of the query. * * @since 1.5.1 * * @param string $orderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this)); /** * Filters the DISTINCT clause of the query. * * @since 2.1.0 * * @param string $distinct The DISTINCT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this)); /** * Filters the LIMIT clause of the query. * * @since 2.1.0 * * @param string $limits The LIMIT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $limits = apply_filters_ref_array('post_limits', array($limits, &$this)); /** * Filters the SELECT clause of the query. * * @since 2.1.0 * * @param string $fields The SELECT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $fields = apply_filters_ref_array('posts_fields', array($fields, &$this)); /** * Filters all query clauses at once, for convenience. * * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, * fields (SELECT), and LIMITS clauses. * * @since 3.1.0 * * @param array $clauses The list of clauses for the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $clauses = (array) apply_filters_ref_array('posts_clauses', array(compact($pieces), &$this)); $where = isset($clauses['where']) ? $clauses['where'] : ''; $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : ''; $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; } /** * Fires to announce the query's current selection parameters. * * For use by caching plugins. * * @since 2.3.0 * * @param string $selection The assembled selection query. */ do_action('posts_selection', $where . $groupby . $orderby . $limits . $join); /* * Filters again for the benefit of caching plugins. * Regular plugins should use the hooks above. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where_request', array($where, &$this)); /** * Filters the GROUP BY clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $groupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this)); /** * Filters the JOIN clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $join The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join_request', array($join, &$this)); /** * Filters the ORDER BY clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $orderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this)); /** * Filters the DISTINCT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $distinct The DISTINCT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this)); /** * Filters the SELECT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $fields The SELECT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this)); /** * Filters the LIMIT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $limits The LIMIT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this)); /** * Filters all query clauses at once, for convenience. * * For use by caching plugins. * * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, * fields (SELECT), and LIMITS clauses. * * @since 3.1.0 * * @param array $pieces The pieces of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this)); $where = isset($clauses['where']) ? $clauses['where'] : ''; $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : ''; $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; } if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $found_rows = ''; if (!$q['no_found_rows'] && !empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->request = $old_request = "SELECT {$found_rows} {$distinct} {$fields} FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; if (!$q['suppress_filters']) { /** * Filters the completed SQL query before sending. * * @since 2.0.0 * * @param string $request The complete SQL query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this)); } /** * Filters the posts array before the query takes place. * * Return a non-null value to bypass WordPress's default post queries. * * Filtering functions that require pagination information are encouraged to set * the `found_posts` and `max_num_pages` properties of the WP_Query object, * passed to the filter by reference. If WP_Query does not perform a database * query, it will not have enough information to generate these values itself. * * @since 4.6.0 * * @param array|null $posts Return an array of post data to short-circuit WP's query, * or null to allow WP to run its normal queries. * @param WP_Query $this The WP_Query instance, passed by reference. */ $this->posts = apply_filters_ref_array('posts_pre_query', array(null, &$this)); if ('ids' == $q['fields']) { if (null === $this->posts) { $this->posts = $this->db->get_col($this->request); } $this->posts = array_map('intval', $this->posts); $this->post_count = count($this->posts); $this->set_found_posts($q, $limits); return $this->posts; } if ('id=>parent' == $q['fields']) { if (null === $this->posts) { $this->posts = $this->db->get_results($this->request); } $this->post_count = count($this->posts); $this->set_found_posts($q, $limits); $r = array(); foreach ($this->posts as $key => $post) { $this->posts[$key]->ID = (int) $post->ID; $this->posts[$key]->post_parent = (int) $post->post_parent; $r[(int) $post->ID] = (int) $post->post_parent; } return $r; } if (null === $this->posts) { $split_the_query = $old_request == $this->request && "{$this->db->posts}.*" == $fields && !empty($limits) && $q['posts_per_page'] < 500; /** * Filters whether to split the query. * * Splitting the query will cause it to fetch just the IDs of the found posts * (and then individually fetch each post by ID), rather than fetching every * complete row at once. One massive result vs. many small results. * * @since 3.4.0 * * @param bool $split_the_query Whether or not to split the query. * @param WP_Query $this The WP_Query instance. */ $split_the_query = apply_filters('split_the_query', $split_the_query, $this); if ($split_the_query) { // First get the IDs and then fill in the objects $this->request = "SELECT {$found_rows} {$distinct} {$this->db->posts}.ID FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; /** * Filters the Post IDs SQL request before sending. * * @since 3.4.0 * * @param string $request The post ID request. * @param WP_Query $this The WP_Query instance. */ $this->request = apply_filters('posts_request_ids', $this->request, $this); $ids = $this->db->get_col($this->request); if ($ids) { $this->posts = $ids; $this->set_found_posts($q, $limits); _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']); } else { $this->posts = array(); } } else { $this->posts = $this->db->get_results($this->request); $this->set_found_posts($q, $limits); } } // Convert to WP_Post objects. if ($this->posts) { $this->posts = array_map('get_post', $this->posts); } if (!$q['suppress_filters']) { /** * Filters the raw post results array, prior to status checks. * * @since 2.3.0 * * @param array $posts The post results array. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this)); } if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) { /** This filter is documented in wp-includes/query.php */ $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this)); /** This filter is documented in wp-includes/query.php */ $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); /** This filter is documented in wp-includes/query.php */ $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; /** This filter is documented in wp-includes/query.php */ $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; /** This filter is documented in wp-includes/query.php */ $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $comments = $this->db->get_results($comments_request); // Convert to WP_Comment $this->comments = array_map('get_comment', $comments); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); if ('attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent) { $this->is_page = false; $this->is_single = true; $this->is_attachment = true; } $post_status_obj = get_post_status_object($status); // If the post_status was specifically requested, let it pass through. if (!$post_status_obj->public && !in_array($status, $q_status)) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) { /** * Filters the single post for preview mode. * * @since 2.7.0 * * @param WP_Post $post_preview The Post object. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts[0] = get_post(apply_filters_ref_array('the_preview', array($this->posts[0], &$this))); } } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies = get_posts(array('post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true)); foreach ($stickies as $sticky_post) { array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up. if (!empty($this->comments)) { wp_queue_comments_for_comment_meta_lazyload($this->comments); } if (!$q['suppress_filters']) { /** * Filters the array of retrieved posts after they've been fetched and * internally processed. * * @since 1.5.0 * * @param array $posts The array of retrieved posts. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this)); } // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ($this->posts) { $this->post_count = count($this->posts); $this->posts = array_map('get_post', $this->posts); if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } $this->post = reset($this->posts); } else { $this->post_count = 0; $this->posts = array(); } if ($q['lazy_load_term_meta']) { wp_queue_posts_for_term_meta_lazyload($this->posts); } return $this->posts; }
public function deleteNetworkLock($ntk) { if (wp_using_ext_object_cache()) { wp_cache_delete($ntk . 'roplock', 'transient'); } else { delete_transient($ntk . 'roplock'); } }
/** * Set/update the value of a site transient. * * You do not need to serialize values, if the value needs to be serialize, then * it will be serialized before it is set. * * @see set_transient() * @since 2.9.0 * @package WordPress * @subpackage Transient * * @uses apply_filters() Calls 'pre_set_site_transient_$transient' hook to allow overwriting the * transient value to be stored. * @uses do_action() Calls 'set_site_transient_$transient' and 'setted_site_transient' hooks on success. * * @param string $transient Transient name. Expected to not be SQL-escaped. * @param mixed $value Transient value. Expected to not be SQL-escaped. * @param int $expiration Time until expiration in seconds, default 0 * @return bool False if value was not set and true if value was set. */ function set_site_transient($transient, $value, $expiration = 0) { $value = apply_filters('pre_set_site_transient_' . $transient, $value); $expiration = (int) $expiration; if (wp_using_ext_object_cache()) { $result = wp_cache_set($transient, $value, 'site-transient', $expiration); } else { $transient_timeout = '_site_transient_timeout_' . $transient; $option = '_site_transient_' . $transient; if (false === get_site_option($option)) { if ($expiration) { add_site_option($transient_timeout, time() + $expiration); } $result = add_site_option($option, $value); } else { if ($expiration) { update_site_option($transient_timeout, time() + $expiration); } $result = update_site_option($option, $value); } } if ($result) { do_action('set_site_transient_' . $transient, $value, $expiration); do_action('setted_site_transient', $transient, $value, $expiration); } return $result; }
/** * Clear entire XML sitemap cache * * @param array $types */ public static function clear_sitemap_cache($types = array()) { global $wpdb; if (wp_using_ext_object_cache()) { return; } if (!apply_filters('YMBESEO_enable_xml_sitemap_transient_caching', true)) { return; } // Not sure about efficiency, but that's what code elsewhere does R. $options = YMBESEO_Options::get_all(); if (true !== $options['enablexmlsitemap']) { return; } $query = "DELETE FROM {$wpdb->options} WHERE"; if (!empty($types)) { $first = true; foreach ($types as $sitemap_type) { if (!$first) { $query .= ' OR '; } $query .= " option_name LIKE '_transient_YMBESEO_sitemap_cache_" . $sitemap_type . "_%' OR option_name LIKE '_transient_timeout_YMBESEO_sitemap_cache_" . $sitemap_type . "_%'"; $first = false; } } else { $query .= " option_name LIKE '_transient_YMBESEO_sitemap_%' OR option_name LIKE '_transient_timeout_YMBESEO_sitemap_%'"; } $wpdb->query($query); }
/** * When the transient version increases, this is used to remove all past transients to avoid filling the DB. * * Note; this only works on transients appended with the transient version, and when object caching is not being used. * * @since 2.3.10 */ public static function delete_version_transients($version = '') { if (!wp_using_ext_object_cache() && !empty($version)) { global $wpdb; $limit = apply_filters('woocommerce_delete_version_transients_limit', 1000); $affected = $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id LIMIT %d;", "\\_transient\\_%" . $version, $limit)); // If affected rows is equal to limit, there are more rows to delete. Delete in 10 secs. if ($affected === $limit) { wp_schedule_single_event(time() + 10, 'delete_version_transients', array($version)); } } }
/** * Retrieve a network by its domain and path. * * @since 4.4.0 * @access public * @static * * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return WP_Network|bool Network object if successful. False when no network is found. */ public static function get_by_path($domain = '', $path = '', $segments = null) { global $wpdb; $domains = array($domain); $pieces = explode('.', $domain); /* * It's possible one domain to search is 'com', but it might as well * be 'localhost' or some other locally mapped domain. */ while (array_shift($pieces)) { if (!empty($pieces)) { $domains[] = implode('.', $pieces); } } /* * If we've gotten to this function during normal execution, there is * more than one network installed. At this point, who knows how many * we have. Attempt to optimize for the situation where networks are * only domains, thus meaning paths never need to be considered. * * This is a very basic optimization; anything further could have * drawbacks depending on the setup, so this is best done per-install. */ $using_paths = true; if (wp_using_ext_object_cache()) { $using_paths = wp_cache_get('networks_have_paths', 'site-options'); if (false === $using_paths) { $using_paths = $wpdb->get_var("SELECT id FROM {$wpdb->site} WHERE path <> '/' LIMIT 1"); wp_cache_add('networks_have_paths', (int) $using_paths, 'site-options'); } } $paths = array(); if (true === $using_paths) { $path_segments = array_filter(explode('/', trim($path, '/'))); /** * Filter the number of path segments to consider when searching for a site. * * @since 3.9.0 * * @param int|null $segments The number of path segments to consider. WordPress by default looks at * one path segment. The function default of null only makes sense when you * know the requested path should match a network. * @param string $domain The requested domain. * @param string $path The requested path, in full. */ $segments = apply_filters('network_by_path_segments_count', $segments, $domain, $path); if (null !== $segments && count($path_segments) > $segments) { $path_segments = array_slice($path_segments, 0, $segments); } while (count($path_segments)) { $paths[] = '/' . implode('/', $path_segments) . '/'; array_pop($path_segments); } $paths[] = '/'; } /** * Determine a network by its domain and path. * * This allows one to short-circuit the default logic, perhaps by * replacing it with a routine that is more optimal for your setup. * * Return null to avoid the short-circuit. Return false if no network * can be found at the requested domain and path. Otherwise, return * an object from wp_get_network(). * * @since 3.9.0 * * @param null|bool|object $network Network value to return by path. * @param string $domain The requested domain. * @param string $path The requested path, in full. * @param int|null $segments The suggested number of paths to consult. * Default null, meaning the entire path was to be consulted. * @param array $paths The paths to search for, based on $path and $segments. */ $pre = apply_filters('pre_get_network_by_path', null, $domain, $path, $segments, $paths); if (null !== $pre) { return $pre; } // @todo Consider additional optimization routes, perhaps as an opt-in for plugins. // We already have paths covered. What about how far domains should be drilled down (including www)? $search_domains = "'" . implode("', '", $wpdb->_escape($domains)) . "'"; if (false === $using_paths) { $network = $wpdb->get_row("\n\t\t\t\tSELECT * FROM {$wpdb->site}\n\t\t\t\tWHERE domain IN ({$search_domains})\n\t\t\t\tORDER BY CHAR_LENGTH(domain)\n\t\t\t\tDESC LIMIT 1\n\t\t\t"); if (!empty($network) && !is_wp_error($network)) { return new WP_Network($network); } return false; } else { $search_paths = "'" . implode("', '", $wpdb->_escape($paths)) . "'"; $networks = $wpdb->get_results("\n\t\t\t\tSELECT * FROM {$wpdb->site}\n\t\t\t\tWHERE domain IN ({$search_domains})\n\t\t\t\tAND path IN ({$search_paths})\n\t\t\t\tORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC\n\t\t\t"); } /* * Domains are sorted by length of domain, then by length of path. * The domain must match for the path to be considered. Otherwise, * a network with the path of / will suffice. */ $found = false; foreach ($networks as $network) { if ($network->domain === $domain || "www.{$network->domain}" === $domain) { if (in_array($network->path, $paths, true)) { $found = true; break; } } if ($network->path === '/') { $found = true; break; } } if (true === $found) { return new WP_Network($network); } return false; }