Ejemplo n.º 1
0
/**
 * Clean search string from XSS exploits.
 *
 * @since	1.0
 *
 * @param	string $val    Potentially unclean string
 * @return	string	Cleaned string
 */
function bsearch_clean_terms($val)
{
    global $bsearch_settings;
    $val = stripslashes(urldecode($val));
    $badwords = array_map('trim', explode(',', $bsearch_settings['badwords']));
    $censorChar = ' ';
    /**
     * Allow the censored character to be replaced.
     *
     * @since	2.1.0
     *
     * @param	string	$censorChar	Censored character
     * @param	string	$val		Raw search string
     */
    $censorChar = apply_filters('bsearch_censor_char', $censorChar, $val);
    $val_censored = bsearch_censor_string($val, $badwords, $censorChar);
    // No more bad words
    $val = $val_censored['clean'];
    $val = addslashes_gpc($val);
    $val = wp_kses_post($val);
    /**
     * Clean search string from XSS exploits.
     *
     * @since	2.0.0
     *
     * @param	string	$val	Cleaned string
     */
    return apply_filters('bsearch_clean_terms', $val);
}
 function make_duplicate($master_post_id, $lang)
 {
     global $wpml_post_translations;
     do_action('icl_before_make_duplicate', $master_post_id, $lang);
     $master_post = get_post($master_post_id);
     $is_duplicated = false;
     $translations = $wpml_post_translations->get_element_translations($master_post_id, false, false);
     if (isset($translations[$lang])) {
         $post_array['ID'] = $translations[$lang];
         if (WPML_WordPress_Actions::is_bulk_trash($post_array['ID']) || WPML_WordPress_Actions::is_bulk_untrash($post_array['ID'])) {
             return true;
         }
         $is_duplicated = get_post_meta($translations[$lang], '_icl_lang_duplicate_of', true);
     }
     $post_array['post_author'] = $master_post->post_author;
     $post_array['post_date'] = $master_post->post_date;
     $post_array['post_date_gmt'] = $master_post->post_date_gmt;
     $duplicated_post_content = $this->duplicate_post_content($lang, $master_post);
     $post_array['post_content'] = addslashes_gpc($duplicated_post_content);
     $duplicated_post_title = $this->duplicate_post_title($lang, $master_post);
     $post_array['post_title'] = addslashes_gpc($duplicated_post_title);
     $duplicated_post_excerpt = $this->duplicate_post_excerpt($lang, $master_post);
     $post_array['post_excerpt'] = addslashes_gpc($duplicated_post_excerpt);
     if ($this->sitepress->get_setting('sync_post_status')) {
         $sync_post_status = true;
     } else {
         $sync_post_status = !isset($post_array['ID']) || $this->sitepress->get_setting('sync_delete') && $master_post->post_status === 'trash' || $is_duplicated;
     }
     if ($sync_post_status || isset($post_array['ID']) && get_post_status($post_array['ID']) === 'auto-draft') {
         $post_array['post_status'] = $master_post->post_status;
     }
     $post_array['comment_status'] = $master_post->comment_status;
     $post_array['ping_status'] = $master_post->ping_status;
     $post_array['post_name'] = $master_post->post_name;
     if ($master_post->post_parent) {
         $parent = $this->sitepress->get_object_id($master_post->post_parent, $master_post->post_type, false, $lang);
         $post_array['post_parent'] = $parent;
     }
     $post_array['menu_order'] = $master_post->menu_order;
     $post_array['post_type'] = $master_post->post_type;
     $post_array['post_mime_type'] = $master_post->post_mime_type;
     $trid = $this->sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
     $id = $this->save_duplicate($post_array, $lang);
     require_once ICL_PLUGIN_PATH . '/inc/cache.php';
     icl_cache_clear();
     global $ICL_Pro_Translation;
     /** @var WPML_Pro_Translation $ICL_Pro_Translation */
     if ($ICL_Pro_Translation) {
         $ICL_Pro_Translation->_content_fix_links_to_translated_content($id, $lang);
     }
     if (!is_wp_error($id)) {
         $ret = $this->run_wpml_actions($master_post, $trid, $lang, $id, $post_array);
     } else {
         $ret = false;
     }
     return $ret;
 }
Ejemplo n.º 3
0
	function &get_posts() {
		global $wpdb, $pagenow, $user_ID;

		do_action('pre_get_posts', array(&$this));

		// Shorthand.
		$q = $this->query_vars;	

		// First let's clear some variables
		$whichcat = '';
		$whichauthor = '';
		$whichpage = '';
		$result = '';
		$where = '';
		$limits = '';
		$distinct = '';
		$join = '';

		if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
			$q['posts_per_page'] = get_settings('posts_per_page');
		if ( !isset($q['what_to_show']) )
			$q['what_to_show'] = get_settings('what_to_show');
		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_settings('posts_per_rss');
			$q['what_to_show'] = 'posts';
		}

		if (isset($q['page'])) {
			$q['page'] = trim($q['page'], '/');
			$q['page'] = (int) $q['page'];
			$q['page'] = abs($q['page']);
		}
	
		$add_hours = intval(get_settings('gmt_offset'));
		$add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours));
		$wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)";

		// If a month is specified in the querystring, load that month
		if ( (int) $q['m'] ) {
			$q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
			$where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4);
			if (strlen($q['m'])>5)
				$where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2);
			if (strlen($q['m'])>7)
				$where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2);
			if (strlen($q['m'])>9)
				$where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2);
			if (strlen($q['m'])>11)
				$where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2);
			if (strlen($q['m'])>13)
				$where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2);
		}

		if ( (int) $q['hour'] ) {
			$q['hour'] = '' . intval($q['hour']);
			$where .= " AND HOUR(post_date)='" . $q['hour'] . "'";
		}

		if ( (int) $q['minute'] ) {
			$q['minute'] = '' . intval($q['minute']);
			$where .= " AND MINUTE(post_date)='" . $q['minute'] . "'";
		}

		if ( (int) $q['second'] ) {
			$q['second'] = '' . intval($q['second']);
			$where .= " AND SECOND(post_date)='" . $q['second'] . "'";
		}

		if ( (int) $q['year'] ) {
			$q['year'] = '' . intval($q['year']);
			$where .= " AND YEAR(post_date)='" . $q['year'] . "'";
		}

		if ( (int) $q['monthnum'] ) {
			$q['monthnum'] = '' . intval($q['monthnum']);
			$where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'";
		}

		if ( (int) $q['day'] ) {
			$q['day'] = '' . intval($q['day']);
			$where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'";
		}

		// Compat.  Map subpost to attachment.
		if ( '' != $q['subpost'] )
			$q['attachment'] = $q['subpost'];
		if ( '' != $q['subpost_id'] )
			$q['attachment_id'] = $q['subpost_id'];

		if ('' != $q['name']) {
			$q['name'] = sanitize_title($q['name']);
			$where .= " AND post_name = '" . $q['name'] . "'";
		} else if ('' != $q['pagename']) {
			$q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
			$page_paths = '/' . trim($q['pagename'], '/');
			$q['pagename'] = sanitize_title(basename($page_paths));
			$q['name'] = $q['pagename'];
			$page_paths = explode('/', $page_paths);
			foreach($page_paths as $pathdir)
				$page_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
				
			$all_page_ids = get_all_page_ids();
			$reqpage = 0;
			if (is_array($all_page_ids)) { foreach ( $all_page_ids as $page_id ) {
				$page = get_page($page_id);
				if ( $page->fullpath == $page_path ) {
					$reqpage = $page_id;
					break;
				}
			} }
			
			$where .= " AND (ID = '$reqpage')";
		} elseif ('' != $q['attachment']) {
			$q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
			$attach_paths = '/' . trim($q['attachment'], '/');
			$q['attachment'] = sanitize_title(basename($attach_paths));
			$q['name'] = $q['attachment'];
			$where .= " AND post_name = '" . $q['attachment'] . "'";
		}

		if ( (int) $q['w'] ) {
			$q['w'] = ''.intval($q['w']);
			$where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'";
		}

		if ( intval($q['comments_popup']) )
			$q['p'] = intval($q['comments_popup']);

		// If a attachment is requested by number, let it supercede any post number.
		if ( ($q['attachment_id'] != '') && (intval($q['attachment_id']) != 0) )
			$q['p'] = (int) $q['attachment_id'];

		// If a post number is specified, load that post
		if (($q['p'] != '') && intval($q['p']) != 0) {
			$q['p'] =  (int) $q['p'];
			$where = ' AND ID = ' . $q['p'];
		}

		if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) {
			$q['page_id'] = intval($q['page_id']);
			$q['p'] = $q['page_id'];
			$where = ' AND ID = '.$q['page_id'];
		}

		// If a search pattern is specified, load the posts that match
		if (!empty($q['s'])) {
			$q['s'] = addslashes_gpc($q['s']);
			$search = ' AND (';
			$q['s'] = preg_replace('/, +/', ' ', $q['s']);
			$q['s'] = str_replace(',', ' ', $q['s']);
			$q['s'] = str_replace('"', ' ', $q['s']);
			$q['s'] = trim($q['s']);
			if ($q['exact']) {
				$n = '';
			} else {
				$n = '%';
			}
			if (!$q['sentence']) {
				$s_array = explode(' ',$q['s']);
				$q['search_terms'] = $s_array;
				$search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))';
				for ( $i = 1; $i < count($s_array); $i = $i + 1) {
					$search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))';
				}
				$search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')';
				$search .= ')';
			} else {
				$search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))';
			}
		}

		// Category stuff

		if ((empty($q['cat'])) || ($q['cat'] == '0') || 
				// Bypass cat checks if fetching specific posts
				( $this->is_single || $this->is_page )) {
			$whichcat='';
		} else {
			$q['cat'] = ''.urldecode($q['cat']).'';
			$q['cat'] = addslashes_gpc($q['cat']);
			if (stristr($q['cat'],'-')) {
				// Note: if we have a negative, we ignore all the positives. It must
				// always mean 'everything /except/ this one'. We should be able to do
				// multiple negatives but we don't :-(
				$eq = '!=';
				$andor = 'AND';
				$q['cat'] = explode('-',$q['cat']);
				$q['cat'] = intval($q['cat'][1]);
			} else {
				$eq = '=';
				$andor = 'OR';
			}
			$join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) ";
			$cat_array = preg_split('/[,\s]+/', $q['cat']);
			$whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]);
			$whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' ');
			for ($i = 1; $i < (count($cat_array)); $i = $i + 1) {
				$whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]);
				$whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' ');
			}
			$whichcat .= ')';
			if ($eq == '!=') {
				$q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category.
			}
		}

		// Category stuff for nice URIs

		global $cache_categories;
		if ('' != $q['category_name']) {
			$cat_paths = '/' . trim(urldecode($q['category_name']), '/');
			$q['category_name'] = sanitize_title(basename($cat_paths));
			$cat_paths = explode('/', $cat_paths);
			foreach($cat_paths as $pathdir)
				$cat_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);

			$all_cat_ids = get_all_category_ids();
			$q['cat'] = 0; $partial_match = 0;
			foreach ( $all_cat_ids as $cat_id ) {
				$cat = get_category($cat_id);
				if ( $cat->fullpath == $cat_path ) {
					$q['cat'] = $cat_id;
					break;
				} elseif ( $cat->category_nicename == $q['category_name'] ) {
					$partial_match = $cat_id;
				}
			}
			
			//if we don't match the entire hierarchy fallback on just matching the nicename
			if (!$q['cat'] && $partial_match) {
				$q['cat'] = $partial_match;
			}			

			$tables = ", $wpdb->post2cat, $wpdb->categories";
			$join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) ";
			$whichcat = " AND (category_id = '" . $q['cat'] . "'";
			$whichcat .= get_category_children($q['cat'], " OR category_id = ");
			$whichcat .= ")";
		}

		// Author/user stuff

		if ((empty($q['author'])) || ($q['author'] == '0')) {
			$whichauthor='';
		} else {
			$q['author'] = ''.urldecode($q['author']).'';
			$q['author'] = addslashes_gpc($q['author']);
			if (stristr($q['author'], '-')) {
				$eq = '!=';
				$andor = 'AND';
				$q['author'] = explode('-', $q['author']);
				$q['author'] = ''.intval($q['author'][1]);
			} else {
				$eq = '=';
				$andor = 'OR';
			}
			$author_array = preg_split('/[,\s]+/', $q['author']);
			$whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]);
			for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
				$whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]);
			}
			$whichauthor .= ')';
		}

		// Author stuff for nice URIs

		if ('' != $q['author_name']) {
			if (stristr($q['author_name'],'/')) {
				$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 trailling slash
				}
			}
			$q['author_name'] = sanitize_title($q['author_name']);
			$q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
			$whichauthor .= ' AND (post_author = '.intval($q['author']).')';
		}
		
		$where .= $search.$whichcat.$whichauthor;

		if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) {
			$q['order']='DESC';
		}

		// Order by
		if (empty($q['orderby'])) {
			$q['orderby']='date '.$q['order'];
		} else {
			// Used to filter values
			$allowed_keys = array('author', 'date', 'category', 'title', 'modified');
			$q['orderby'] = urldecode($q['orderby']);
			$q['orderby'] = addslashes_gpc($q['orderby']);
			$orderby_array = explode(' ',$q['orderby']);
			if (!in_array($orderby_array[0],$allowed_keys)) {
				$orderby_array[0] = 'date';
			}
			$q['orderby'] = $orderby_array[0].' '.$q['order'];
			if (count($orderby_array)>1) {
				for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) {
					// Only allow certain values for safety
					if (in_array($orderby_array[$i],$allowed_keys)) {
						$q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order'];
					}
				}
			}
		}

		$now = gmdate('Y-m-d H:i:59');
		
		//only select past-dated posts, except if a logged in user is viewing a single: then, if they
		//can edit the post, we let them through
		if ($pagenow != 'post.php' && $pagenow != 'edit.php' && !($this->is_single && $user_ID)) {
			$where .= " AND post_date_gmt <= '$now'";
			$distinct = 'DISTINCT';
		}

		if ( $this->is_attachment ) {
			$where .= " AND (post_status = 'attachment')";
		} elseif ($this->is_page) {
			$where .= " AND (post_status = 'static')";
		} elseif ($this->is_single) {
			$where .= " AND (post_status != 'static')";
		} else {
			$where .= " AND (post_status = 'publish'";

			if (isset($user_ID) && ('' != intval($user_ID)))
				$where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')";
			else
				$where .= ')';				
		}

		if (! $this->is_attachment )
			$where .= " AND post_status != 'attachment'";

		// Apply filters on where and join prior to paging so that any
		// manipulations to them are reflected in the paging by day queries.
		$where = apply_filters('posts_where', $where);
		$join = apply_filters('posts_join', $join);

		// Paging
		if (empty($q['nopaging']) && ! $this->is_single && ! $this->is_page) {
			$page = abs(intval($q['paged']));
			if (empty($page)) {
				$page = 1;
			}

			if (($q['what_to_show'] == 'posts')) {
				$q['offset'] = abs(intval($q['offset']));
				if ( empty($q['offset']) ) {
					$pgstrt = '';
					$pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', ';
					$limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
				} else { // we're ignoring $page and using 'offset'
					$pgstrt = $q['offset'] . ', ';
					$limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
				}
			} elseif ($q['what_to_show'] == 'days') {
				$startrow = $q['posts_per_page'] * (intval($page)-1);
				$start_date = $wpdb->get_var("SELECT max(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $startrow,1");
				$endrow = $startrow + $q['posts_per_page'] - 1;
				$end_date = $wpdb->get_var("SELECT min(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $endrow,1");

				if ($page > 1) {
					$where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'";
				} else {
					$where .= " AND post_date >= '$end_date'";
				}
			}
		}

		// Apply post-paging filters on where and join.  Only plugins that
		// manipulate paging queries should use these hooks.
		$where = apply_filters('posts_where_paged', $where);
		$groupby = " $wpdb->posts.ID ";
		$groupby = apply_filters('posts_groupby', $groupby);
		$join = apply_filters('posts_join_paged', $join);
		$orderby = "post_" . $q['orderby'];
		$orderby = apply_filters('posts_orderby', $orderby); 
		$request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1" . $where . " GROUP BY " . $groupby . " ORDER BY " . $orderby . " $limits";
		$this->request = apply_filters('posts_request', $request);

		$this->posts = $wpdb->get_results($this->request);

		// Check post status to determine if post should be displayed.
		if ( !empty($this->posts) && $this->is_single ) {
			$status = get_post_status($this->posts[0]);
			if ( ('publish' != $status) && ('static' != $status) ) {
				if ( ! (isset($user_ID) && ('' != intval($user_ID))) ) {
					// User must be logged in to view unpublished posts.
					$this->posts = array();
				} else {
					if ('draft' == $status) {
						// User must have edit permissions on the draft to preview.
						if (! current_user_can('edit_post', $this->posts[0]->ID)) {
							$this->posts = array();
						} else {
							$this->is_preview = true;
							$this->posts[0]->post_date = current_time('mysql');
						}
					} else {
						if (! current_user_can('read_post', $this->posts[0]->ID))
							$this->posts = array();
					}
				}
			} else {
				if (mysql2date('U', $this->posts[0]->post_date_gmt) > mysql2date('U', $now)) { //it's future dated
					$this->is_preview = true;
					if (!current_user_can('edit_post', $this->posts[0]->ID)) {
						$this->posts = array ( );
					}
				}
			}
		}

		update_post_caches($this->posts);

		$this->posts = apply_filters('the_posts', $this->posts);
		$this->post_count = count($this->posts);
		if ($this->post_count > 0) {
			$this->post = $this->posts[0];
		}
		
		// Save any changes made to the query vars.
		$this->query_vars = $q;
		return $this->posts;
	}
Ejemplo n.º 4
0
 function &get_posts()
 {
     global $wpdb, $pagenow, $user_ID;
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     $q = $this->fill_query_vars($q);
     // First let's clear some variables
     $distinct = '';
     $whichcat = '';
     $whichauthor = '';
     $whichpage = '';
     $result = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     if (!isset($q['post_type'])) {
         $q['post_type'] = 'post';
     }
     $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 ($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'] = (int) $q['page'];
         $q['page'] = abs($q['page']);
     }
     $add_hours = intval(get_option('gmt_offset'));
     $add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours));
     $wp_posts_post_date_field = "post_date";
     // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)";
     // If a month is specified in the querystring, load that month
     if ((int) $q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2);
         }
     }
     if ((int) $q['hour']) {
         $q['hour'] = '' . intval($q['hour']);
         $where .= " AND HOUR(post_date)='" . $q['hour'] . "'";
     }
     if ((int) $q['minute']) {
         $q['minute'] = '' . intval($q['minute']);
         $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'";
     }
     if ((int) $q['second']) {
         $q['second'] = '' . intval($q['second']);
         $where .= " AND SECOND(post_date)='" . $q['second'] . "'";
     }
     if ((int) $q['year']) {
         $q['year'] = '' . intval($q['year']);
         $where .= " AND YEAR(post_date)='" . $q['year'] . "'";
     }
     if ((int) $q['monthnum']) {
         $q['monthnum'] = '' . intval($q['monthnum']);
         $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'";
     }
     if ((int) $q['day']) {
         $q['day'] = '' . intval($q['day']);
         $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'";
     }
     // Compat.  Map subpost to attachment.
     if ('' != $q['subpost']) {
         $q['attachment'] = $q['subpost'];
     }
     if ('' != $q['subpost_id']) {
         $q['attachment_id'] = $q['subpost_id'];
     }
     if ('' != $q['name']) {
         $q['name'] = sanitize_title($q['name']);
         $where .= " AND post_name = '" . $q['name'] . "'";
     } else {
         if ('' != $q['pagename']) {
             $reqpage = get_page_by_path($q['pagename']);
             if (!empty($reqpage)) {
                 $reqpage = $reqpage->ID;
             } else {
                 $reqpage = 0;
             }
             if ('page' == get_option('show_on_front') && $reqpage == get_option('page_for_posts')) {
                 $this->is_singular = false;
                 $this->is_page = false;
                 $this->is_home = true;
                 $this->is_posts_page = true;
             } else {
                 $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
                 $page_paths = '/' . trim($q['pagename'], '/');
                 $q['pagename'] = sanitize_title(basename($page_paths));
                 $q['name'] = $q['pagename'];
                 $where .= " AND (ID = '{$reqpage}')";
             }
         } elseif ('' != $q['attachment']) {
             $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
             $attach_paths = '/' . trim($q['attachment'], '/');
             $q['attachment'] = sanitize_title(basename($attach_paths));
             $q['name'] = $q['attachment'];
             $where .= " AND post_name = '" . $q['attachment'] . "'";
         }
     }
     if ((int) $q['w']) {
         $q['w'] = '' . intval($q['w']);
         $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'";
     }
     if (intval($q['comments_popup'])) {
         $q['p'] = intval($q['comments_popup']);
     }
     // If a attachment is requested by number, let it supercede any post number.
     if ($q['attachment_id'] != '' && intval($q['attachment_id']) != 0) {
         $q['p'] = (int) $q['attachment_id'];
     }
     // If a post number is specified, load that post
     if ($q['p'] != '' && intval($q['p']) != 0) {
         $q['p'] = (int) $q['p'];
         $where = ' AND ID = ' . $q['p'];
     }
     if ($q['page_id'] != '' && intval($q['page_id']) != 0) {
         $q['page_id'] = intval($q['page_id']);
         if ('page' == get_option('show_on_front') && $q['page_id'] == get_option('page_for_posts')) {
             $this->is_singular = false;
             $this->is_page = false;
             $this->is_home = true;
             $this->is_posts_page = true;
         } else {
             $q['p'] = $q['page_id'];
             $where = ' AND ID = ' . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if ($q['sentence']) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q[s], $matches);
             $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
         }
         $n = $q['exact'] ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = addslashes_gpc($term);
             $search .= "{$searchand}((post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         $term = addslashes_gpc($q['s']);
         if (!$q['sentence'] && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) {
             $search .= " OR (post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}')";
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
         }
     }
     // Category stuff
     if (empty($q['cat']) || $q['cat'] == '0' || ($this->is_single || $this->is_page)) {
         $whichcat = '';
     } else {
         $q['cat'] = '' . urldecode($q['cat']) . '';
         $q['cat'] = addslashes_gpc($q['cat']);
         $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) ";
         $cat_array = preg_split('/[,\\s]+/', $q['cat']);
         $in_cats = $out_cats = $out_posts = '';
         foreach ($cat_array as $cat) {
             $cat = intval($cat);
             $in = strstr($cat, '-') ? false : true;
             $cat = trim($cat, '-');
             if ($in) {
                 $in_cats .= "{$cat}, " . get_category_children($cat, '', ', ');
             } else {
                 $out_cats .= "{$cat}, " . get_category_children($cat, '', ', ');
             }
         }
         $in_cats = substr($in_cats, 0, -2);
         $out_cats = substr($out_cats, 0, -2);
         if (strlen($in_cats) > 0) {
             $in_cats = " AND {$wpdb->post2cat}.category_id IN ({$in_cats})";
         }
         if (strlen($out_cats) > 0) {
             $ids = $wpdb->get_col("SELECT post_id FROM {$wpdb->post2cat} WHERE {$wpdb->post2cat}.category_id IN ({$out_cats})");
             if (is_array($ids) && count($ids > 0)) {
                 foreach ($ids as $id) {
                     $out_posts .= "{$id}, ";
                 }
                 $out_posts = substr($out_posts, 0, -2);
             }
             if (strlen($out_posts) > 0) {
                 $out_cats = " AND {$wpdb->posts}.ID NOT IN ({$out_posts})";
             } else {
                 $out_cats = '';
             }
         }
         $whichcat = $in_cats . $out_cats;
         $groupby = "{$wpdb->posts}.ID";
     }
     // Category stuff for nice URLs
     if ('' != $q['category_name']) {
         $reqcat = get_category_by_path($q['category_name']);
         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
         $cat_paths = '/' . trim($q['category_name'], '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = explode('/', $cat_paths);
         $cat_path = '';
         foreach ((array) $cat_paths as $pathdir) {
             $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir);
         }
         //if we don't match the entire hierarchy fallback on just matching the nicename
         if (empty($reqcat)) {
             $reqcat = get_category_by_path($q['category_name'], false);
         }
         if (!empty($reqcat)) {
             $reqcat = $reqcat->cat_ID;
         } else {
             $reqcat = 0;
         }
         $q['cat'] = $reqcat;
         $tables = ", {$wpdb->post2cat}, {$wpdb->categories}";
         $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) LEFT JOIN {$wpdb->categories} ON ({$wpdb->post2cat}.category_id = {$wpdb->categories}.cat_ID) ";
         $whichcat = " AND category_id IN ({$q['cat']}, ";
         $whichcat .= get_category_children($q['cat'], '', ', ');
         $whichcat = substr($whichcat, 0, -2);
         $whichcat .= ")";
         $groupby = "{$wpdb->posts}.ID";
     }
     // Author/user stuff
     if (empty($q['author']) || $q['author'] == '0') {
         $whichauthor = '';
     } else {
         $q['author'] = '' . urldecode($q['author']) . '';
         $q['author'] = addslashes_gpc($q['author']);
         if (stristr($q['author'], '-')) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = '' . intval($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $whichauthor .= ' AND (post_author ' . $eq . ' ' . intval($author_array[0]);
         for ($i = 1; $i < count($author_array); $i = $i + 1) {
             $whichauthor .= ' ' . $andor . ' post_author ' . $eq . ' ' . intval($author_array[$i]);
         }
         $whichauthor .= ')';
     }
     // Author stuff for nice URLs
     if ('' != $q['author_name']) {
         if (stristr($q['author_name'], '/')) {
             $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 trailling slash
             }
         }
         $q['author_name'] = sanitize_title($q['author_name']);
         $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'");
         $whichauthor .= ' AND (post_author = ' . intval($q['author']) . ')';
     }
     $where .= $search . $whichcat . $whichauthor;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $q['orderby'] = 'post_date ' . $q['order'];
     } else {
         // Used to filter values
         $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order');
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = explode(' ', $q['orderby']);
         if (empty($orderby_array)) {
             $orderby_array[] = $q['orderby'];
         }
         $q['orderby'] = '';
         for ($i = 0; $i < count($orderby_array); $i++) {
             // Only allow certain values for safety
             $orderby = $orderby_array[$i];
             if ('menu_order' != $orderby) {
                 $orderby = 'post_' . $orderby;
             }
             if (in_array($orderby_array[$i], $allowed_keys)) {
                 $q['orderby'] .= ($i == 0 ? '' : ',') . "{$orderby} {$q['order']}";
             }
         }
         if (empty($q['orderby'])) {
             $q['orderby'] = 'post_date ' . $q['order'];
         }
     }
     if ($this->is_attachment) {
         $where .= " AND (post_type = 'attachment')";
     } elseif ($this->is_page) {
         $where .= " AND (post_type = 'page')";
     } elseif ($this->is_single) {
         $where .= " AND (post_type = 'post')";
     } else {
         $where .= " AND (post_type = '{$post_type}' AND (post_status = 'publish'";
         if (is_admin()) {
             $where .= " OR post_status = 'future' OR post_status = 'draft'";
         }
         if (is_user_logged_in()) {
             if ('post' == $post_type) {
                 $cap = 'read_private_posts';
             } else {
                 $cap = 'read_private_pages';
             }
             if (current_user_can($cap)) {
                 $where .= " OR post_status = 'private'";
             } else {
                 $where .= " OR post_author = {$user_ID} AND post_status = 'private'";
             }
         }
         $where .= '))';
     }
     // Apply filters on where and join prior to paging so that any
     // manipulations to them are reflected in the paging by day queries.
     $where = apply_filters('posts_where', $where);
     $join = apply_filters('posts_join', $join);
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = abs(intval($q['paged']));
         if (empty($page)) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = '';
             $pgstrt = (intval($page) - 1) * $q['posts_per_page'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = abs(intval($q['offset']));
             $pgstrt = $q['offset'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         }
     }
     // Apply post-paging filters on where and join.  Only plugins that
     // manipulate paging queries should use these hooks.
     $where = apply_filters('posts_where_paged', $where);
     $groupby = apply_filters('posts_groupby', $groupby);
     if (!empty($groupby)) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     $join = apply_filters('posts_join_paged', $join);
     $orderby = apply_filters('posts_orderby', $q['orderby']);
     $distinct = apply_filters('posts_distinct', $distinct);
     $fields = apply_filters('posts_fields', "{$wpdb->posts}.*");
     $limits = apply_filters('post_limits', $limits);
     $found_rows = '';
     if (!empty($limits)) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     $request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} ORDER BY {$orderby} {$limits}";
     $this->request = apply_filters('posts_request', $request);
     $this->posts = $wpdb->get_results($this->request);
     if (!empty($limits)) {
         $found_posts_query = apply_filters('found_posts_query', 'SELECT FOUND_ROWS()');
         $this->found_posts = $wpdb->get_var($found_posts_query);
         $this->found_posts = apply_filters('found_posts', $this->found_posts);
         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
     }
     // 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]);
         //$type = get_post_type($this->posts[0]);
         if ('publish' != $status) {
             if (!is_user_logged_in()) {
                 // User must be logged in to view unpublished posts.
                 $this->posts = array();
             } else {
                 if ('draft' == $status) {
                     // User must have edit permissions on the draft to preview.
                     if (!current_user_can('edit_post', $this->posts[0]->ID)) {
                         $this->posts = array();
                     } else {
                         $this->is_preview = true;
                         $this->posts[0]->post_date = current_time('mysql');
                     }
                 } else {
                     if ('future' == $status) {
                         $this->is_preview = true;
                         if (!current_user_can('edit_post', $this->posts[0]->ID)) {
                             $this->posts = array();
                         }
                     } else {
                         if (!current_user_can('read_post', $this->posts[0]->ID)) {
                             $this->posts = array();
                         }
                     }
                 }
             }
         }
     }
     $this->posts = apply_filters('the_posts', $this->posts);
     update_post_caches($this->posts);
     $this->post_count = count($this->posts);
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }
    $author_name = preg_replace('|[^a-z0-9-_]|', '', strtolower($author_name));
    $author = $wpdb->get_var("SELECT ID FROM {$wpdb->users[$wp_id]} WHERE user_login='******'");
    $whichauthor .= ' AND (post_author = ' . intval($author) . ')';
}
$where .= $search . $whichcat . $whichauthor;
if (empty($order) || strtoupper($order) != 'ASC' && strtoupper($order) != 'DESC') {
    $order = 'DESC';
}
// order by stuff
if (empty($orderby)) {
    $orderby = 'date ' . $order;
} else {
    // used to filter values
    $allowed_keys = array('author', 'date', 'category', 'title');
    $orderby = urldecode($orderby);
    $orderby = addslashes_gpc($orderby);
    $orderby_array = explode(' ', $orderby);
    if (!in_array($orderby_array[0], $allowed_keys)) {
        $orderby_array[0] = 'date';
    }
    $orderby = $orderby_array[0] . ' ' . $order;
    if (count($orderby_array) > 1) {
        for ($i = 1; $i < count($orderby_array); $i = $i + 1) {
            // Only allow certain values for safety
            if (in_array($orderby_array[$i], $allowed_keys)) {
                $orderby .= ',post_' . $orderby_array[$i] . ' ' . $order;
            }
        }
    }
}
if (!$whichcat && !$m && !$p && !$w && !$s && empty($poststart) && empty($postend)) {
	/**
	 * Extended get_terms function support
	 * - Limit category
	 * - Limit days
	 * - Selection restrict
	 * - Min usage
	 *
	 * @param string|array $taxonomies
	 * @param string $args
	 * @return array
	 */
	function getTerms( $taxonomies, $args = '', $skip_cache = false, $internal_st = false ) {
		global $wpdb;
		$empty_array = array();

		$single_taxonomy = false;
		if ( !is_array($taxonomies) ) {
			$single_taxonomy = true;
			$taxonomies = array($taxonomies);
		}

		foreach ( $taxonomies as $taxonomy ) {
			if ( ! is_taxonomy($taxonomy) ) {
				return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
			}
		}

		$in_taxonomies = "'" . implode("', '", $taxonomies) . "'";

		$defaults = array(
			'orderby' => 'name',
			'order' => 'ASC',
			'cloud_selection' => 'count-desc',
			'hide_empty' => true,
			'exclude' => '',
			'include' => '',
			'number' => '',
			'fields' => 'all',
			'slug' => '',
			'parent' => '',
			'hierarchical' => true,
			'child_of' => 0,
			'get' => '',
			'name__like' => '',
			'st_name_like' => '',
			'pad_counts' => false,
			'offset' => '',
			'search' => '',
			'limit_days' => 0,
			'category' => 0,
			'min_usage' => 0
		);

		$args = wp_parse_args( $args, $defaults );
		if ( $internal_st != true ) { // Allow limit :)
			$args['number'] = absint( $args['number'] );
		}
		$args['offset'] = absint( $args['offset'] );
		if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) || '' != $args['parent'] ) {
			$args['child_of'] = 0;
			$args['hierarchical'] = false;
			$args['pad_counts'] = false;
		}

		if ( 'all' == $args['get'] ) {
			$args['child_of'] = 0;
			$args['hide_empty'] = 0;
			$args['hierarchical'] = false;
			$args['pad_counts'] = false;
		}
		extract($args, EXTR_SKIP);

		if ( $child_of ) {
			$hierarchy = _get_term_hierarchy($taxonomies[0]);
			if ( !isset($hierarchy[$child_of]) )
				return $empty_array;
		}

		if ( $parent ) {
			$hierarchy = _get_term_hierarchy($taxonomies[0]);
			if ( !isset($hierarchy[$parent]) )
				return $empty_array;
		}
		
		if ( $skip_cache != true ) {
			// $args can be whatever, only use the args defined in defaults to compute the key
			$filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
			$key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
			$last_changed = wp_cache_get('last_changed', 'terms');
			if ( !$last_changed ) {
			    $last_changed = time();
			    wp_cache_set('last_changed', $last_changed, 'terms');
			}
			$cache_key = "get_terms:$key:$last_changed";
			
			if ( $cache = wp_cache_get( $cache_key, 'terms' ) ) {
			    $terms = apply_filters('get_terms', $cache, $taxonomies, $args);
			    return $terms;
			}
		}

		// Restrict category
		$category_sql = '';
		if ( !empty($category) && $category != '0' ) {
			$incategories = preg_split('/[\s,]+/', $category);

			$objects_id = get_objects_in_term( $incategories, 'category' );
			$objects_id = array_unique ($objects_id); // to be sure haven't duplicates

			if ( empty($objects_id) ) { // No posts for this category = no tags for this category
				return array();
			}

			foreach ( (array) $objects_id as $object_id ) {
				$category_sql .= "'". $object_id . "', ";
			}

			$category_sql = substr($category_sql, 0, strlen($category_sql) - 2); // Remove latest ", "
			$category_sql = 'AND p.ID IN ('.$category_sql.')';
		}

		// count-asc/count-desc/name-asc/name-desc/random
		$cloud_selection = strtolower($cloud_selection);
		switch ( $cloud_selection ) {
			case 'count-asc':
				$order_by = 'tt.count ASC';
				break;
			case 'random':
				$order_by = 'RAND()';
				break;
			case 'name-asc':
				$order_by = 't.name ASC';
				break;
			case 'name-desc':
				$order_by = 't.name DESC';
				break;
			default: // count-desc
			$order_by = 'tt.count DESC';
			break;
		}

		// Min usage
		$restict_usage = '';
		$min_usage = (int) $min_usage;
		if ( $min_usage != 0 ) {
			$restict_usage = ' AND tt.count >= '. $min_usage;
		}

		$where = '';
		$inclusions = '';
		if ( !empty($include) ) {
			$exclude = '';
			$interms = preg_split('/[\s,]+/',$include);
			foreach ( (array) $interms as $interm ) {
				if (empty($inclusions)) {
					$inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
				} else {
					$inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
				}
			}
		}

		if ( !empty($inclusions) ) {
			$inclusions .= ')';
		}
		$where .= $inclusions;

		$exclusions = '';
		if ( !empty($exclude) ) {
			$exterms = preg_split('/[\s,]+/',$exclude);
			foreach ( (array) $exterms as $exterm ) {
				if (empty($exclusions)) {
					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
				} else {
					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
				}
			}
		}

		if ( !empty($exclusions) ) {
			$exclusions .= ')';
		}
		$exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
		$where .= $exclusions;

		if ( !empty($slug) ) {
			$slug = sanitize_title($slug);
			$where .= " AND t.slug = '$slug'";
		}

		if ( !empty($name__like) ) {
			$where .= " AND t.name LIKE '{$name__like}%'";
		}

		if ( strpos($st_name_like, ' ') != false || strpos($st_name_like, ' ') != null ) {
			$tmp = '';
			$sts = explode(' ', $st_name_like);
			foreach ( (array) $sts as $st ) {
				if ( empty($st) )
				continue;

				$st = addslashes_gpc($st);
				$tmp .= " t.name LIKE '%{$st}%' OR ";
			}
			// Remove latest OR
			$tmp = substr( $tmp, 0, strlen($tmp) - 4);

			$where .= " AND ( $tmp ) ";
			unset($tmp)	;
		} elseif ( !empty($st_name_like) ) {
			$where .= " AND t.name LIKE '%{$st_name_like}%'";
		}

		if ( '' != $parent ) {
			$parent = (int) $parent;
			$where .= " AND tt.parent = '$parent'";
		}

		if ( $hide_empty && !$hierarchical ) {
			$where .= ' AND tt.count > 0';
		}

		$number_sql = '';
		if ( strpos($number, ',') != false || strpos($number, ',') != null ) {
			$number_sql = $number;
		} else {
			$number = (int) $number;
			if ( $number != 0 ) {
				$number_sql = 'LIMIT ' . $number;
			}
		}

		if ( !empty($search) ) {
			$search = like_escape($search);
			$where .= " AND (t.name LIKE '%$search%')";
		}

		$select_this = '';

		if ( 'all' == $fields ) {
			$select_this = 't.*, tt.*';
		} else if ( 'ids' == $fields ) {
 	        $select_this = 't.term_id, tt.parent, tt.count';
		} else if ( 'names' == $fields ) {
			$select_this = 't.term_id, tt.parent, tt.count, t.name';
		}

		// Limit posts date
		$limitdays_sql = '';
		$limit_days = (int) $limit_days;
		if ( $limit_days != 0 ) {
			$limitdays_sql = 'AND p.post_date_gmt > "' .date( 'Y-m-d H:i:s', time() - $limit_days * 86400 ). '"';
		}

		$query = "SELECT {$select_this}
			FROM {$wpdb->terms} AS t
			INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id
			INNER JOIN {$wpdb->term_relationships} AS tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
			INNER JOIN {$wpdb->posts} AS p ON tr.object_id = p.ID
			WHERE tt.taxonomy IN ( {$in_taxonomies} )
			AND p.post_date_gmt < '".current_time('mysql')."'
			{$limitdays_sql}
			{$category_sql}
			{$where}
			{$restict_usage}
			GROUP BY t.term_id
			ORDER BY {$order_by}
			{$number_sql}";
		
		if ( 'all' == $fields ) {
			$terms = $wpdb->get_results($query);
			if ( $skip_cache != true ) {
				update_term_cache($terms);
			}
		} else if ( ('ids' == $fields) || ('names' == $fields) ) {
			$terms = $wpdb->get_results($query);
		}

		if ( empty($terms) ) {
			$cache[ $key ] = array();
			wp_cache_set( 'get_terms', $cache, 'terms' );
			$terms = apply_filters('get_terms', array(), $taxonomies, $args);
			return $terms;
		}

		if ( $child_of ) {
		    $children = _get_term_hierarchy($taxonomies[0]);
		    if ( ! empty($children) )
		        $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
		}

		// Update term counts to include children.
 	    if ( $pad_counts && 'all' == $fields )
	        _pad_term_counts($terms, $taxonomies[0]);

		// Make sure we show empty categories that have children.
		if ( $hierarchical && $hide_empty && is_array($terms) ) {
		    foreach ( $terms as $k => $term ) {
		        if ( ! $term->count ) {
		            $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
		            if( is_array($children) )
		                foreach ( $children as $child )
		                    if ( $child->count )
		                        continue 2;
		
		            // It really is empty
		            unset($terms[$k]);
		        }
		    }
		}
		reset ( $terms );
		
		$_terms = array();
		if ( 'ids' == $fields ) {
		    while ( $term = array_shift($terms) )
		        $_terms[] = $term->term_id;
		    $terms = $_terms;
		} elseif ( 'names' == $fields ) {
		    while ( $term = array_shift($terms) )
		        $_terms[] = $term->name;
		    $terms = $_terms;
		}
		
		if ( $skip_cache != true ) {
			wp_cache_add( $cache_key, $terms, 'terms' );
		}

		$terms = apply_filters('get_terms', $terms, $taxonomies, $args);
		return $terms;
	}
Ejemplo n.º 7
0
<?php

$doing_rss = 1;
require 'wp-blog-header.php';
header('Content-type: text/xml; charset=' . get_settings('blog_charset'), true);
$link_cat = $_GET['link_cat'];
if (empty($link_cat) || $link_cat == 'all' || $link_cat == '0') {
    $sql_cat = '';
} else {
    // be safe
    $link_cat = '' . urldecode($link_cat) . '';
    $link_cat = addslashes_gpc($link_cat);
    $link_cat = intval($link_cat);
    if ($link_cat != 0) {
        $sql_cat = "AND {$wpdb->links}.link_category = {$link_cat}";
        $cat_name = $wpdb->get_var("SELECT {$wpdb->linkcategories}.cat_name FROM {$wpdb->linkcategories} WHERE {$wpdb->linkcategories}.cat_id = {$link_cat}");
        if (!empty($cat_name)) {
            $cat_name = ": category {$cat_name}";
        }
    }
}
echo '<?xml version="1.0"?' . ">\n";
?>
<!-- generator="wordpress/<?php 
echo $wp_version;
?>
" -->
<opml version="1.0">
    <head>
        <title>Links for <?php 
echo get_bloginfo('name') . $cat_name;
Ejemplo n.º 8
0
/**
 * Get the matches for the search term.
 *
 * @since	1.2
 *
 * @param	string $search_info    Search terms array
 * @param	bool   $bydate         Sort by date?
 * @return	array	Search results
 */
function get_bsearch_matches($search_query, $bydate)
{
    global $wpdb, $bsearch_settings;
    // if there are two items in $search_info, the string has been broken into separate terms that
    // are listed at $search_info[1]. The cleaned-up version of $search_query is still at the zero index.
    // This is when fulltext is disabled, and we search using LIKE
    $search_info = get_bsearch_terms($search_query);
    // Get search transient
    $search_query_transient = 'bs_' . preg_replace('/[^A-Za-z0-9\\-]/', '', str_replace(' ', '', $search_query));
    /**
     * Filter name of the search transient
     *
     * @since	2.1.0
     *
     * @param	string	$search_query_transient	Transient name
     * @param	array	$search_query	Search query
     */
    $search_query_transient = apply_filters('bsearch_transient_name', $search_query_transient, $search_query);
    $search_query_transient = substr($search_query_transient, 0, 40);
    // Name of the transient limited to 40 chars
    $matches = get_transient($search_query_transient);
    if ($matches) {
        if (isset($matches['search_query'])) {
            if ($matches['search_query'] == $search_query) {
                $results = $matches[0];
                /**
                 * Filter array holding the search results
                 *
                 * @since	1.2
                 *
                 * @param	object	$matches	Search results object
                 * @param	array	$search_info	Search query
                 */
                return apply_filters('get_bsearch_matches', $matches, $search_info);
            }
        }
    }
    // If no transient is set
    if (!isset($results)) {
        $sql = bsearch_sql_prepare($search_info, $bsearch_settings['boolean_mode'], $bydate);
        $results = $wpdb->get_results($sql);
    }
    // If no results are found then force BOOLEAN mode
    if (!$results) {
        $sql = bsearch_sql_prepare($search_info, 1, $bydate);
        $results = $wpdb->get_results($sql);
    }
    // If no results are found then force LIKE mode
    if (!$results) {
        // strip out all the fancy characters that fulltext would use
        $search_query = addslashes_gpc($search_query);
        $search_query = preg_replace('/, +/', ' ', $search_query);
        $search_query = str_replace(',', ' ', $search_query);
        $search_query = str_replace('"', ' ', $search_query);
        $search_query = trim($search_query);
        $search_words = explode(' ', $search_query);
        $s_array[0] = $search_query;
        // Save original query at [0]
        $s_array[1] = $search_words;
        // Save array of terms at [1]
        $search_info = $s_array;
        $sql = bsearch_sql_prepare($search_info, 0, $bydate);
        $results = $wpdb->get_results($sql);
    }
    $matches[0] = $results;
    $matches['search_query'] = $search_query;
    if ($bsearch_settings['cache']) {
        // Set search transient
        set_transient($search_query_transient, $matches, 7200);
    }
    /**
     * Described in better-search.php
     */
    return apply_filters('get_bsearch_matches', $matches, $search_info);
}
Ejemplo n.º 9
0
 /**
  * search for albums and return the result
  *
  * @since 1.7.0
  * @param string $request
  * @param int $limit number of results, 0 shows all results
  * @return Array Result of the request
  */
 function search_for_albums($request, $limit = 0)
 {
     global $wpdb;
     // If a search pattern is specified, load the posts that match
     if (!empty($request)) {
         // added slashes screw with quote grouping when done early, so done later
         $request = stripslashes($request);
         // split the words it a array if separated by a space or comma
         preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $request, $matches);
         $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
         $n = '%';
         $searchand = '';
         $search = '';
         foreach ((array) $search_terms as $term) {
             $term = addslashes_gpc($term);
             $search .= "{$searchand}(name LIKE '{$n}{$term}{$n}')";
             $searchand = ' AND ';
         }
         $term = esc_sql($request);
         if (count($search_terms) > 1 && $search_terms[0] != $request) {
             $search .= " OR (name LIKE '{$n}{$term}{$n}')";
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
         }
         $limit = $limit > 0 ? 'LIMIT ' . intval($limit) : '';
     } else {
         return false;
     }
     // build the final query
     $query = "SELECT * FROM {$wpdb->nggalbum} WHERE 1=1 {$search} ORDER BY name ASC {$limit}";
     $result = $wpdb->get_results($query);
     return $result;
 }
Ejemplo n.º 10
0
/**
 * SACK response function for saving post categories
 *
 * @since 1.2.0
 * @author scripts@schloebe.de
 */
function ame_ajax_save_categories()
{
    global $wpdb, $post;
    $postid = intval($_POST['postid']);
    $ame_cats = $_POST['ame_cats'];
    $ame_categories = substr($ame_cats, 0, -1);
    $catarray = explode(",", $ame_categories);
    wp_set_post_categories($postid, $catarray);
    unset($GLOBALS['category_cache']);
    $categories = get_the_category($postid);
    $ame_post_cats = "";
    if (!empty($categories)) {
        $out = array();
        foreach ($categories as $c) {
            $out[] = '<a href="edit.php?category_name=' . $c->slug . '"> ' . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'category', 'display')) . '</a>';
        }
        $ame_post_cats = join(', ', $out);
    } else {
        $ame_post_cats = __('Uncategorized');
    }
    do_action('edit_post', $postid, get_post($postid));
    do_action('save_post', $postid, get_post($postid));
    die("re_init();jQuery('span#ame_category" . $postid . "').fadeOut('fast', function() {\r\n\t\tjQuery('a#thickboxlink" . $postid . "').show();\r\n\t\tjQuery('span#ame_category" . $postid . "').html('" . addslashes_gpc($ame_post_cats) . "').fadeIn('fast');\r\n\t});");
}
Ejemplo n.º 11
0
        $value = mysql_real_escape_string($value);
    }
    return $value;
}
if (isset($_GET["s"])) {
    $search_term = quote_smart($_GET["s"]);
}
if (isset($_GET["from"])) {
    $from = (int) $_GET["from"];
    $pagenow = (int) ($from / $onepage + 1);
}
if (isset($_GET["page"])) {
    $pagenow = (int) $_GET["page"];
    $from = $pagenow * $onepage - $onepage;
}
$search_term = addslashes_gpc($search_term);
$search_term = preg_replace('/, +/', ' ', $search_term);
$search_term = str_replace(',', ' ', $search_term);
$search_term = str_replace('"', ' ', $search_term);
$search_term = trim($search_term);
$s_array = explode(' ', $search_term);
echo "<ul>";
if ($search_term != "") {
    $search = "SELECT ID, post_title FROM {$wpdb->posts} WHERE (post_title LIKE '{$wildcard}" . $s_array[0] . "{$wildcard}' OR post_content LIKE '{$wildcard}" . $s_array[0] . "{$wildcard}')";
    for ($i = 1; $i < count($s_array); $i = $i + 1) {
        $search .= " AND (post_title LIKE '{$wildcard}" . $s_array[$i] . "{$wildcard}' OR post_content LIKE '{$wildcard}" . $s_array[$i] . "{$wildcard}')";
    }
    $search .= " ORDER BY post_date DESC";
    $posts = $wpdb->get_results($search);
    if ($posts) {
        $results = true;
function sp_cron_check_news()
{
    $url = 'http://simple-press.com/downloads/simple-press/simple-press-news.xml';
    $response = wp_remote_get($url, array('timeout' => 5));
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
        return;
    }
    $body = wp_remote_retrieve_body($response);
    if (!$body) {
        return;
    }
    $newNews = new SimpleXMLElement($body);
    if ($newNews) {
        $data = sp_get_sfmeta('news', 'news');
        $cur_id = !empty($data[0]['meta_value']) ? $data[0]['meta_value']['id'] : -999;
        if ($newNews->news->id != $cur_id) {
            $curNews = array();
            $curNews['id'] = (string) $newNews->news->id;
            $curNews['show'] = 1;
            $curNews['news'] = addslashes_gpc((string) $newNews->news[0]->message);
            sp_add_sfmeta('news', 'news', $curNews, 0);
        }
    }
}
if (test_param('order')) {
    $_order = get_param('order');
    if (strtoupper($_order) != 'ASC' && strtoupper($_order) != 'DESC') {
        $_criteria_order = 'DESC';
    } else {
        $_criteria_order = $_order;
    }
}
// order by stuff
if (!test_param('orderby')) {
    $_criteria_sort = 'post_date';
} else {
    // used to filter values
    $_allowed_keys = array('author', 'date', 'category', 'title');
    $_order_keys = array('post_author', 'post_date', 'cat_name', 'post_title');
    $_orderby_list = explode(' ', addslashes_gpc(urldecode(get_param('orderby'))));
    if (!in_array($_orderby_list[0], $_allowed_keys)) {
        $_orderby_array[] = 'post_date';
    }
    for ($_i = 0; $_i < count($_orderby_list); $_i++) {
        // Only allow certain values for safety
        $_key = array_search($_orderby_list[$_i], $_allowed_keys);
        if ($_key !== false) {
            $_orderby_array[] = $_order_keys[$_key];
        }
    }
    $_criteria_sort = $_orderby_array;
    if (in_array('category', $_orderby_list) && !test_param('category_name')) {
        $_joinCriteria =& new XoopsJoinCriteria(wp_table('post2cat'), 'ID', 'post_id');
        $_joinCriteria->cascade(new XoopsJoinCriteria(wp_table('categories'), 'category_id', 'cat_ID'));
    }
Ejemplo n.º 14
0
 function duplicate_custom_fields($master_post_id, $lang)
 {
     global $wpdb, $sitepress;
     $duplicate_post_id = false;
     $post_type = get_post_field('post_type', $master_post_id);
     $trid = $sitepress->get_element_trid($master_post_id, 'post_' . $post_type);
     if ($trid) {
         $translations = $sitepress->get_element_translations($trid, 'post_' . $post_type);
         if (isset($translations[$lang])) {
             $duplicate_post_id = $translations[$lang]->element_id;
         } else {
             return false;
             // translation not found!
         }
     }
     $default_exceptions = array('_wp_old_slug', '_edit_last', '_edit_lock', '_icl_translator_note', '_icl_lang_duplicate_of', '_wpml_media_duplicate', '_wpml_media_featured');
     $exceptions = $default_exceptions;
     //Todo: make sure the following filter won't remove the default exceptions
     $exceptions = apply_filters('wpml_duplicate_custom_fields_exceptions', $exceptions);
     // low level copy
     $custom_fields_master = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE post_id=%d group by meta_key", $master_post_id));
     $custom_fields_duplicate = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE post_id=%d group by meta_key", $duplicate_post_id));
     $custom_fields_master = array_diff($custom_fields_master, $exceptions);
     $custom_fields_duplicate = array_diff($custom_fields_duplicate, $exceptions);
     $remove = array_diff($custom_fields_duplicate, $custom_fields_master);
     foreach ($remove as $key) {
         delete_post_meta($duplicate_post_id, $key);
     }
     foreach ($custom_fields_master as $key) {
         $master_custom_field_values_array = get_post_meta($master_post_id, $key);
         $master_custom_field_values_single = get_post_meta($master_post_id, $key, true);
         $is_repeated = false;
         if ($master_custom_field_values_array != $master_custom_field_values_single) {
             //Repeated fields
             $master_custom_field_values = $master_custom_field_values_array;
             $is_repeated = true;
         } else {
             //Field stored as serialized array
             $master_custom_field_values[] = $master_custom_field_values_single;
         }
         if ($is_repeated) {
             $duplicate_custom_field_values = get_post_meta($duplicate_post_id, $key);
         } else {
             $duplicate_custom_field_values[] = get_post_meta($duplicate_post_id, $key, true);
         }
         if (!$duplicate_custom_field_values || $master_custom_field_values != $duplicate_custom_field_values) {
             if ($is_repeated) {
                 //Delete the old one
                 delete_post_meta($duplicate_post_id, $key);
                 //And add new ones from the original
                 foreach ($master_custom_field_values as $master_custom_field_value) {
                     add_post_meta($duplicate_post_id, $key, addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_custom_field_value, $lang, array('context' => 'custom_field', 'attribute' => 'value', 'key' => $key))));
                 }
             } else {
                 update_post_meta($duplicate_post_id, $key, addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_custom_field_value, $lang, array('context' => 'custom_field', 'attribute' => 'value', 'key' => $key))));
             }
         }
     }
     return true;
 }
Ejemplo n.º 15
0
 function search_propertylist($query = '', $startat = 0, $show = STAYPRESS_PROPERTY_PER_PAGE, $type = 'all', $includethumbimages = false)
 {
     if ($type == 'all') {
         $type = 'publish,draft,pending,private';
     }
     // Need to redo this search
     if (!empty($query)) {
         // Check for a "smart" query lookup of id
         if (strpos(strtolower($query), 'id:') !== false) {
             $post__in = array((int) str_replace('id:', '', strtolower($query)));
         } else {
             $n = '%';
             $query = addslashes_gpc($query);
             $sql = "SELECT post_id FROM {$this->property} WHERE (reference LIKE '{$n}{$query}{$n}' OR title LIKE '{$n}{$query}{$n}' OR description LIKE '{$n}{$query}{$n}' OR country LIKE '{$n}{$query}{$n}' OR region LIKE '{$n}{$query}{$n}' OR town LIKE '{$n}{$query}{$n}')";
             $sql .= $this->db->prepare(" AND blog_id = %d", $this->blog_id);
             $results = $this->db->get_col($sql);
             if (empty($results)) {
                 return false;
             } else {
                 $post__in = $results;
             }
         }
     }
     $args = array('posts_per_page' => $show, 'offset' => $startat, 'orderby' => 'post_modified', 'order' => 'DESC', 'post_type' => STAYPRESS_PROPERTY_POST_TYPE, 'post_status' => $type, 'post__in' => $post__in);
     if (!$this->user->has_cap('edit_others_properties')) {
         $args['author'] = $this->user->ID;
     }
     $get_properties = new WP_Query();
     $propertylist = $get_properties->query($args);
     $this->max_num_pages = $get_properties->max_num_pages;
     $this->found_posts = $get_properties->found_posts;
     return $propertylist;
 }
Ejemplo n.º 16
0
 function ajax_library_actions()
 {
     global $wpdb;
     switch ($action = $_POST['action']) {
         case 'shiba_find_posts':
             check_ajax_referer('find-posts');
             if (empty($_POST['ps'])) {
                 exit;
             }
             $what = isset($_POST['type']) ? $_POST['type'] : 'post';
             $s = stripslashes($_POST['ps']);
             preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
             $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
             $searchand = $search = '';
             foreach ((array) $search_terms as $term) {
                 $term = addslashes_gpc($term);
                 $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '%{$term}%') OR ({$wpdb->posts}.post_content LIKE '%{$term}%'))";
                 $searchand = ' AND ';
             }
             $term = $wpdb->escape($s);
             if (count($search_terms) > 1 && $search_terms[0] != $s) {
                 $search .= " OR ({$wpdb->posts}.post_title LIKE '%{$term}%') OR ({$wpdb->posts}.post_content LIKE '%{$term}%')";
             }
             $posts = $wpdb->get_results("SELECT ID, post_title, post_status, post_date FROM {$wpdb->posts} WHERE post_type = '{$what}' AND {$search} ORDER BY post_date_gmt DESC LIMIT 50");
             if (!$posts) {
                 exit(__('No posts found.', THEMEDOMAIN));
             }
             $html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>' . __('Title') . '</th><th>' . __('Time') . '</th><th>' . __('Status') . '</th></tr></thead><tbody>';
             foreach ($posts as $post) {
                 switch ($post->post_status) {
                     case 'publish':
                     case 'private':
                         $stat = __('Published', THEMEDOMAIN);
                         break;
                     case 'future':
                         $stat = __('Scheduled', THEMEDOMAIN);
                         break;
                     case 'pending':
                         $stat = __('Pending Review', THEMEDOMAIN);
                         break;
                     case 'draft':
                         $stat = __('Unpublished', THEMEDOMAIN);
                         break;
                 }
                 if ('0000-00-00 00:00:00' == $post->post_date) {
                     $time = '';
                 } else {
                     /* translators: date format in table columns, see http://php.net/date */
                     $time = mysql2date(__('Y/m/d', THEMEDOMAIN), $post->post_date);
                 }
                 $html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-' . $post->ID . '" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
                 $html .= '<td><label for="found-' . $post->ID . '">' . esc_html($post->post_title) . '</label></td><td>' . esc_html($time) . '</td><td>' . esc_html($stat) . '</td></tr>' . "\n\n";
             }
             $html .= '</tbody></table>';
             $x = new WP_Ajax_Response();
             $x->add(array('what' => $what, 'data' => $html));
             $x->send();
             break;
     }
     // end switch
 }
Ejemplo n.º 17
0
		<?php 
        if ($match->home_points != NULL && $match->away_points != NULL) {
            ?>
		<?php 
            if ($final->isFinal) {
                ?>
		<?php 
                $img = '<img style="vertical-align: middle;" src="' . LEAGUEMANAGER_URL . '/admin/icons/cup.png" />';
                ?>
		<script type="text/javascript">
			jQuery('span#<?php 
                echo $final->field_id;
                ?>
').html('<?php 
                echo addslashes_gpc($img);
                ?>
').fadeIn('fast');
		</script>
		<?php 
            }
            ?>

		<p><strong><?php 
            echo $match->score;
            ?>
</strong></p>
		<?php 
        }
        ?>
	</td>
 /**
  * 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;
 }
Ejemplo n.º 19
0
 /**
  * Create the search categories query
  *
  * @since 1.8.7
  */
 public function build_search_categories()
 {
     global $wpdb;
     $vars = $this->query_instance->query_vars;
     $s = $vars['s'];
     $search_terms = $this->get_search_terms();
     $exact = isset($vars['exact']) ? $vars['exact'] : '';
     $search = '';
     if (!empty($search_terms)) {
         // Building search query for categories slug.
         $n = $exact ? '' : '%';
         $searchand = '';
         $searchSlug = '';
         foreach ($search_terms as $term) {
             $term = addslashes_gpc($term);
             $searchSlug .= "{$searchand}(tter.slug LIKE '{$n}" . sanitize_title_with_dashes($term) . "{$n}')";
             $searchand = ' AND ';
         }
         if (count($search_terms) > 1 && $search_terms[0] != $s) {
             $searchSlug = "({$searchSlug}) OR (tter.slug LIKE '{$n}" . sanitize_title_with_dashes($s) . "{$n}')";
         }
         if (!empty($searchSlug)) {
             $search = " OR ({$searchSlug}) ";
         }
         // Building search query for categories description.
         $searchand = '';
         $searchDesc = '';
         foreach ($search_terms as $term) {
             $term = addslashes_gpc($term);
             $searchDesc .= "{$searchand}(ttax.description LIKE '{$n}{$term}{$n}')";
             $searchand = ' AND ';
         }
         $sentence_term = esc_sql($s);
         if (count($search_terms) > 1 && $search_terms[0] != $sentence_term) {
             $searchDesc = "({$searchDesc}) OR (ttax.description LIKE '{$n}{$sentence_term}{$n}')";
         }
         if (!empty($searchDesc)) {
             $search = $search . " OR ({$searchDesc}) ";
         }
     }
     return $search;
 }
Ejemplo n.º 20
0
 /**
  * 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.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID;
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     $q = $this->fill_query_vars($q);
     // First let's clear some variables
     $distinct = '';
     $whichcat = '';
     $whichauthor = '';
     $whichmimetype = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $fields = "{$wpdb->posts}.*";
     $post_status_join = false;
     $page = 1;
     if (!isset($q['caller_get_posts'])) {
         $q['caller_get_posts'] = false;
     }
     if (!isset($q['suppress_filters'])) {
         $q['suppress_filters'] = false;
     }
     if (!isset($q['post_type'])) {
         if ($this->is_search) {
             $q['post_type'] = 'any';
         } else {
             $q['post_type'] = 'post';
         }
     }
     $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']);
     }
     // If a month is specified in the querystring, load that month
     if ($q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'";
     }
     if ('' != $q['name']) {
         $q['name'] = sanitize_title($q['name']);
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
     } else {
         if ('' != $q['pagename']) {
             if (isset($this->queried_object_id)) {
                 $reqpage = $this->queried_object_id;
             } 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'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
                 $page_paths = '/' . trim($q['pagename'], '/');
                 $q['pagename'] = sanitize_title(basename($page_paths));
                 $q['name'] = $q['pagename'];
                 $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')";
                 $reqpage_obj = get_page($reqpage);
                 if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) {
                     $this->is_attachment = true;
                     $this->is_page = true;
                     $q['attachment_id'] = $reqpage;
                 }
             }
         } elseif ('' != $q['attachment']) {
             $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
             $attach_paths = '/' . trim($q['attachment'], '/');
             $q['attachment'] = sanitize_title(basename($attach_paths));
             $q['name'] = $q['attachment'];
             $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
         }
     }
     if ($q['w']) {
         $where .= " AND WEEK({$wpdb->posts}.post_date, 1)='" . $q['w'] . "'";
     }
     if (intval($q['comments_popup'])) {
         $q['p'] = absint($q['comments_popup']);
     }
     // If an attachment is requested by number, let it supercede 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 {$wpdb->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$wpdb->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']);
     }
     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 {$wpdb->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if (!empty($q['sentence'])) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches);
             $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
         }
         $n = !empty($q['exact']) ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = addslashes_gpc($term);
             $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         $term = $wpdb->escape($q['s']);
         if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) {
             $search .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')";
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
         }
     }
     // Category stuff
     if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) {
         $whichcat = '';
     } else {
         $q['cat'] = '' . urldecode($q['cat']) . '';
         $q['cat'] = addslashes_gpc($q['cat']);
         $cat_array = preg_split('/[,\\s]+/', $q['cat']);
         $q['cat'] = '';
         $req_cats = array();
         foreach ((array) $cat_array as $cat) {
             $cat = intval($cat);
             $req_cats[] = $cat;
             $in = $cat > 0;
             $cat = abs($cat);
             if ($in) {
                 $q['category__in'][] = $cat;
                 $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
             } else {
                 $q['category__not_in'][] = $cat;
                 $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
             }
         }
         $q['cat'] = implode(',', $req_cats);
     }
     if (!empty($q['category__in'])) {
         $groupby = "{$wpdb->posts}.ID";
     }
     if (!empty($q['category__in'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $include_cats = "'" . implode("', '", $q['category__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) ";
     }
     if (!empty($q['category__not_in'])) {
         if ($wpdb->has_cap('subqueries')) {
             $cat_string = "'" . implode("', '", $q['category__not_in']) . "'";
             $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'category' AND tt.term_id IN ({$cat_string}) )";
         } else {
             $ids = get_objects_in_term($q['category__not_in'], 'category');
             if (is_wp_error($ids)) {
                 $ids = array();
             }
             if (is_array($ids) && count($ids > 0)) {
                 $out_posts = "'" . implode("', '", $ids) . "'";
                 $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})";
             }
         }
     }
     // Category stuff for nice URLs
     if ('' != $q['category_name'] && !$this->is_singular) {
         $reqcat = get_category_by_path($q['category_name']);
         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
         $cat_paths = '/' . trim($q['category_name'], '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = explode('/', $cat_paths);
         $cat_path = '';
         foreach ((array) $cat_paths as $pathdir) {
             $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir);
         }
         //if we don't match the entire hierarchy fallback on just matching the nicename
         if (empty($reqcat)) {
             $reqcat = get_category_by_path($q['category_name'], false);
         }
         if (!empty($reqcat)) {
             $reqcat = $reqcat->term_id;
         } else {
             $reqcat = 0;
         }
         $q['cat'] = $reqcat;
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $in_cats = array($q['cat']);
         $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
         $in_cats = "'" . implode("', '", $in_cats) . "'";
         $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})";
         $groupby = "{$wpdb->posts}.ID";
     }
     // Tags
     if ('' != $q['tag']) {
         if (strpos($q['tag'], ',') !== false) {
             $tags = preg_split('/[,\\s]+/', $q['tag']);
             foreach ((array) $tags as $tag) {
                 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $tag;
             }
         } else {
             if (preg_match('/[+\\s]+/', $q['tag'])) {
                 $tags = preg_split('/[+\\s]+/', $q['tag']);
                 foreach ((array) $tags as $tag) {
                     $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                     $q['tag_slug__and'][] = $tag;
                 }
             } else {
                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $q['tag'];
             }
         }
     }
     if (!empty($q['tag__in']) || !empty($q['tag_slug__in'])) {
         $groupby = "{$wpdb->posts}.ID";
     }
     if (!empty($q['tag__in'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) ";
         $reqtag = is_term($q['tag__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag['term_id'];
         }
     }
     if (!empty($q['tag_slug__in'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) INNER JOIN {$wpdb->terms} ON ({$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
         $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) ";
         $reqtag = get_term_by('slug', $q['tag_slug__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag->term_id;
         }
     }
     if (!empty($q['tag__not_in'])) {
         if ($wpdb->has_cap('subqueries')) {
             $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'";
             $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'post_tag' AND tt.term_id IN ({$tag_string}) )";
         } else {
             $ids = get_objects_in_term($q['tag__not_in'], 'post_tag');
             if (is_wp_error($ids)) {
                 $ids = array();
             }
             if (is_array($ids) && count($ids > 0)) {
                 $out_posts = "'" . implode("', '", $ids) . "'";
                 $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})";
             }
         }
     }
     // Tag and slug intersections.
     $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag');
     foreach ($intersections as $item => $taxonomy) {
         if (empty($q[$item])) {
             continue;
         }
         if ($item != 'category__and') {
             $reqtag = is_term($q[$item][0], 'post_tag');
             if (!empty($reqtag)) {
                 $q['tag_id'] = $reqtag['term_id'];
             }
         }
         $taxonomy_field = $item == 'tag_slug__and' ? 'slug' : 'term_id';
         $q[$item] = array_unique($q[$item]);
         $tsql = "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->term_relationships} tr ON (p.ID = tr.object_id) INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN {$wpdb->terms} t ON (tt.term_id = t.term_id)";
         $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')";
         $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
         $post_ids = $wpdb->get_col($tsql);
         if (count($post_ids)) {
             $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
         } else {
             $whichcat = " AND 0 = 1";
             break;
         }
     }
     // Taxonomies
     if ($this->is_tax) {
         if ('' != $q['taxonomy']) {
             $taxonomy = $q['taxonomy'];
             $tt[$taxonomy] = $q['term'];
             $terms = get_terms($q['taxonomy'], array('slug' => $q['term']));
         } else {
             foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) {
                 if (isset($t->query_var) && '' != $q[$t->query_var]) {
                     $terms = get_terms($taxonomy, array('slug' => $q[$t->query_var]));
                     if (!is_wp_error($terms)) {
                         break;
                     }
                 }
             }
         }
         if (is_wp_error($terms) || empty($terms)) {
             $whichcat = " AND 0 ";
         } else {
             foreach ($terms as $term) {
                 $term_ids[] = $term->term_id;
             }
             $post_ids = get_objects_in_term($term_ids, $taxonomy);
             if (!is_wp_error($post_ids) && count($post_ids)) {
                 $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
                 $post_type = 'any';
                 $q['post_status'] = 'publish';
                 $post_status_join = true;
             } else {
                 $whichcat = " AND 0 ";
             }
         }
     }
     // Author/user stuff
     if (empty($q['author']) || $q['author'] == '0') {
         $whichauthor = '';
     } else {
         $q['author'] = '' . urldecode($q['author']) . '';
         $q['author'] = addslashes_gpc($q['author']);
         if (strpos($q['author'], '-') !== false) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = '' . absint($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $whichauthor .= " AND ({$wpdb->posts}.post_author " . $eq . ' ' . absint($author_array[0]);
         for ($i = 1; $i < count($author_array); $i = $i + 1) {
             $whichauthor .= ' ' . $andor . " {$wpdb->posts}.post_author " . $eq . ' ' . absint($author_array[$i]);
         }
         $whichauthor .= ')';
     }
     // 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 trailling slash
             }
         }
         $q['author_name'] = sanitize_title($q['author_name']);
         $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'");
         $whichauthor .= " AND ({$wpdb->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']);
     }
     $where .= $search . $whichcat . $whichauthor . $whichmimetype;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
     } else {
         // Used to filter values
         $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand');
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = explode(' ', $q['orderby']);
         if (empty($orderby_array)) {
             $orderby_array[] = $q['orderby'];
         }
         $q['orderby'] = '';
         for ($i = 0; $i < count($orderby_array); $i++) {
             // Only allow certain values for safety
             $orderby = $orderby_array[$i];
             switch ($orderby) {
                 case 'menu_order':
                     break;
                 case 'ID':
                     $orderby = "{$wpdb->posts}.ID";
                     break;
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->postmeta}.meta_value";
                     break;
                 default:
                     $orderby = "{$wpdb->posts}.post_" . $orderby;
             }
             if (in_array($orderby_array[$i], $allowed_keys)) {
                 $q['orderby'] .= ($i == 0 ? '' : ',') . $orderby;
             }
         }
         // append ASC or DESC at the end
         if (!empty($q['orderby'])) {
             $q['orderby'] .= " {$q['order']}";
         }
         if (empty($q['orderby'])) {
             $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
         }
     }
     if ($this->is_attachment) {
         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
     } elseif ($this->is_page) {
         $where .= " AND {$wpdb->posts}.post_type = 'page'";
     } elseif ($this->is_single) {
         $where .= " AND {$wpdb->posts}.post_type = 'post'";
     } elseif ('any' == $post_type) {
         $where .= '';
     } else {
         $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'";
     }
     if (isset($q['post_status']) && '' != $q['post_status']) {
         $statuswheres = array();
         $q_status = explode(',', $q['post_status']);
         $r_status = array();
         $p_status = array();
         if (in_array('draft', $q_status)) {
             $r_status[] = "{$wpdb->posts}.post_status = 'draft'";
         }
         if (in_array('pending', $q_status)) {
             $r_status[] = "{$wpdb->posts}.post_status = 'pending'";
         }
         if (in_array('future', $q_status)) {
             $r_status[] = "{$wpdb->posts}.post_status = 'future'";
         }
         if (in_array('inherit', $q_status)) {
             $r_status[] = "{$wpdb->posts}.post_status = 'inherit'";
         }
         if (in_array('private', $q_status)) {
             $p_status[] = "{$wpdb->posts}.post_status = 'private'";
         }
         if (in_array('publish', $q_status)) {
             $r_status[] = "{$wpdb->posts}.post_status = 'publish'";
         }
         if (empty($q['perm']) || 'readable' != $q['perm']) {
             $r_status = array_merge($r_status, $p_status);
             unset($p_status);
         }
         if (!empty($r_status)) {
             if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can("edit_others_{$post_type}s")) {
                 $statuswheres[] = "({$wpdb->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_{$post_type}s")) {
                 $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $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) . "))";
             }
         }
         foreach ($statuswheres as $statuswhere) {
             $where .= " AND {$statuswhere}";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$wpdb->posts}.post_status = 'publish'";
         if (is_admin()) {
             $where .= " OR {$wpdb->posts}.post_status = 'future' OR {$wpdb->posts}.post_status = 'draft' OR {$wpdb->posts}.post_status = 'pending'";
         }
         if (is_user_logged_in()) {
             $where .= current_user_can("read_private_{$post_type}s") ? " OR {$wpdb->posts}.post_status = 'private'" : " OR {$wpdb->posts}.post_author = {$user_ID} AND {$wpdb->posts}.post_status = 'private'";
         }
         $where .= ')';
     }
     // postmeta queries
     if (!empty($q['meta_key']) || !empty($q['meta_value'])) {
         $join .= " LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) ";
     }
     if (!empty($q['meta_key'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s ", $q['meta_key']);
     }
     if (!empty($q['meta_value'])) {
         if (!isset($q['meta_compare']) || empty($q['meta_compare']) || !in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<='))) {
             $q['meta_compare'] = '=';
         }
         $where .= $wpdb->prepare("AND {$wpdb->postmeta}.meta_value {$q['meta_compare']} %s ", $q['meta_value']);
     }
     // 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']) {
         $where = apply_filters('posts_where', $where);
         $join = apply_filters('posts_join', $join);
     }
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = absint($q['paged']);
         if (empty($page)) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = '';
             $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         }
     }
     // Comments feeds
     if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) {
         if ($this->is_archive || $this->is_search) {
             $cjoin = "LEFT JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} ";
             $cwhere = "WHERE comment_approved = '1' {$where}";
             $cgroupby = "GROUP BY {$wpdb->comments}.comment_id";
         } else {
             // Other non singular e.g. front
             $cjoin = "LEFT 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('comment_feed_join', $cjoin);
             $cwhere = apply_filters('comment_feed_where', $cwhere);
             $cgroupby = apply_filters('comment_feed_groupby', $cgroupby);
         }
         $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss'));
         $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";
         }
     }
     $orderby = $q['orderby'];
     // Apply post-paging filters on where and join.  Only plugins that
     // manipulate paging queries should use these hooks.
     if (!$q['suppress_filters']) {
         $where = apply_filters('posts_where_paged', $where);
         $groupby = apply_filters('posts_groupby', $groupby);
         $join = apply_filters('posts_join_paged', $join);
         $orderby = apply_filters('posts_orderby', $orderby);
         $distinct = apply_filters('posts_distinct', $distinct);
         $limits = apply_filters('post_limits', $limits);
         if (!empty($q['meta_key'])) {
             $fields = "{$fields}, {$wpdb->postmeta}.meta_value";
         }
         $fields = apply_filters('posts_fields', $fields);
     }
     // Announce current selection parameters.  For use by caching plugins.
     do_action('posts_selection', $where . $groupby . $orderby . $limits . $join);
     // Filter again for the benefit of caching plugins.  Regular plugins should use the hooks above.
     if (!$q['suppress_filters']) {
         $where = apply_filters('posts_where_request', $where);
         $groupby = apply_filters('posts_groupby_request', $groupby);
         $join = apply_filters('posts_join_request', $join);
         $orderby = apply_filters('posts_orderby_request', $orderby);
         $distinct = apply_filters('posts_distinct_request', $distinct);
         $fields = apply_filters('posts_fields_request', $fields);
         $limits = apply_filters('post_limits_request', $limits);
     }
     if (!empty($groupby)) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     if (!empty($orderby)) {
         $orderby = 'ORDER BY ' . $orderby;
     }
     $found_rows = '';
     if (!empty($limits)) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     $this->request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         $this->request = apply_filters('posts_request', $this->request);
     }
     $this->posts = $wpdb->get_results($this->request);
     // Raw results filter.  Prior to status checks.
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters('posts_results', $this->posts);
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         $cjoin = apply_filters('comment_feed_join', '');
         $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'");
         $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss');
         $this->comments = $wpdb->get_results($comments_request);
         $this->comment_count = count($this->comments);
     }
     if (!empty($limits)) {
         $found_posts_query = apply_filters('found_posts_query', 'SELECT FOUND_ROWS()');
         $this->found_posts = $wpdb->get_var($found_posts_query);
         $this->found_posts = apply_filters('found_posts', $this->found_posts);
         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
     }
     // 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]);
         //$type = get_post_type($this->posts[0]);
         if ('publish' != $status) {
             if (!is_user_logged_in()) {
                 // User must be logged in to view unpublished posts.
                 $this->posts = array();
             } else {
                 if (in_array($status, array('draft', 'pending'))) {
                     // User must have edit permissions on the draft to preview.
                     if (!current_user_can('edit_post', $this->posts[0]->ID)) {
                         $this->posts = array();
                     } else {
                         $this->is_preview = true;
                         $this->posts[0]->post_date = current_time('mysql');
                     }
                 } else {
                     if ('future' == $status) {
                         $this->is_preview = true;
                         if (!current_user_can('edit_post', $this->posts[0]->ID)) {
                             $this->posts = array();
                         }
                     } else {
                         if (!current_user_can('read_post', $this->posts[0]->ID)) {
                             $this->posts = array();
                         }
                     }
                 }
             }
         }
         if ($this->is_preview && current_user_can("edit_{$post_type}", $this->posts[0]->ID)) {
             $this->posts[0] = apply_filters('the_preview', $this->posts[0]);
         }
     }
     // Put sticky posts at the top of the posts array
     $sticky_posts = get_option('sticky_posts');
     if ($this->is_home && $page <= 1 && !empty($sticky_posts) && !$q['caller_get_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);
                 array_splice($sticky_posts, $offset, 1);
             }
         }
         // Fetch sticky posts that weren't in the query results
         if (!empty($sticky_posts)) {
             $stickies__in = implode(',', array_map('absint', $sticky_posts));
             $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in})");
             /** @todo Make sure post is published or viewable by the current user */
             foreach ($stickies as $sticky_post) {
                 if ('publish' != $sticky_post->post_status) {
                     continue;
                 }
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters('the_posts', $this->posts);
     }
     update_post_caches($this->posts);
     $this->post_count = count($this->posts);
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }
Ejemplo n.º 21
0
/**
 * Build duplicated posts from a master post only in case of the duplicate not being present at the time.
 *
 * @param  int $master_post_id    The ID of the post to duplicate from.
 *                                Master post doesn't need to be in the default language.
 *
 * @uses  SitePress
 * @since 3.2
 * @use \SitePress::api_hooks
 */
function wpml_make_post_duplicates_action($master_post_id)
{
    global $sitepress;
    $master_post = get_post($master_post_id);
    if ($master_post->post_status == 'auto-draft' || $master_post->post_type == 'revision') {
        return;
    }
    $active_langs = $sitepress->get_active_languages();
    foreach ($active_langs as $lang_to => $one) {
        $trid = $sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
        $lang_from = $sitepress->get_source_language_by_trid($trid);
        if ($lang_from == $lang_to) {
            continue;
        }
        $post_array['post_author'] = $master_post->post_author;
        $post_array['post_date'] = $master_post->post_date;
        $post_array['post_date_gmt'] = $master_post->post_date_gmt;
        $post_array['post_content'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_content, $lang_to, array('context' => 'post', 'attribute' => 'content', 'key' => $master_post->ID)));
        $post_array['post_title'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_title, $lang_to, array('context' => 'post', 'attribute' => 'title', 'key' => $master_post->ID)));
        $post_array['post_excerpt'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_excerpt, $lang_to, array('context' => 'post', 'attribute' => 'excerpt', 'key' => $master_post->ID)));
        $post_array['post_status'] = $master_post->post_status;
        //TODO [WPML 3.3.] wp_insert_post() does accept 'post_category': even though is not part of the WP_Post object, it deals with it. But as far as I know $master_post doesn't have this property, when set with get_post(), so probably we need to fix that, shouldn't we?
        $post_array['post_category'] = $master_post->post_category;
        $post_array['comment_status'] = $master_post->comment_status;
        $post_array['ping_status'] = $master_post->ping_status;
        $post_array['post_name'] = $master_post->post_name;
        $post_array['menu_order'] = $master_post->menu_order;
        $post_array['post_type'] = $master_post->post_type;
        $post_array['post_mime_type'] = $master_post->post_mime_type;
        if ($master_post->post_parent) {
            $parent = icl_object_id($master_post->post_parent, $master_post->post_type, false, $lang_to);
            $post_array['post_parent'] = $parent;
        }
        $id = wp_insert_post($post_array);
        $sitepress->set_element_language_details($id, 'post_' . $post_array['post_type'], $trid, $lang_to, $lang_from, false);
    }
}
Ejemplo n.º 22
0
	function get_posts() {
		global $wpdb, $pagenow, $request, $user_ID;

		// Shorthand.
		$q = $this->query_vars;	

		// First let's clear some variables
		$whichcat = '';
		$whichauthor = '';
		$result = '';
		$where = '';
		$limits = '';
		$distinct = '';
		$join = '';

		if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
			$q['posts_per_page'] = get_settings('posts_per_page');
		if ( !isset($q['what_to_show']) )
			$q['what_to_show'] = get_settings('what_to_show');
		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_settings('posts_per_rss');
	
		$add_hours = intval(get_settings('gmt_offset'));
		$add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours));
		$wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)";

		// If a month is specified in the querystring, load that month
		if ( (int) $q['m'] ) {
			$q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
			$where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4);
			if (strlen($q['m'])>5)
				$where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2);
			if (strlen($q['m'])>7)
				$where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2);
			if (strlen($q['m'])>9)
				$where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2);
			if (strlen($q['m'])>11)
				$where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2);
			if (strlen($q['m'])>13)
				$where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2);
		}

		if ( (int) $q['hour'] ) {
			$q['hour'] = '' . intval($q['hour']);
			$where .= " AND HOUR(post_date)='" . $q['hour'] . "'";
		}

		if ( (int) $q['minute'] ) {
			$q['minute'] = '' . intval($q['minute']);
			$where .= " AND MINUTE(post_date)='" . $q['minute'] . "'";
		}

		if ( (int) $q['second'] ) {
			$q['second'] = '' . intval($q['second']);
			$where .= " AND SECOND(post_date)='" . $q['second'] . "'";
		}

		if ( (int) $q['year'] ) {
			$q['year'] = '' . intval($q['year']);
			$where .= " AND YEAR(post_date)='" . $q['year'] . "'";
		}

		if ( (int) $q['monthnum'] ) {
			$q['monthnum'] = '' . intval($q['monthnum']);
			$where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'";
		}

		if ( (int) $q['day'] ) {
			$q['day'] = '' . intval($q['day']);
			$where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'";
		}

		if ('' != $q['name']) {
			$q['name'] = sanitize_title($q['name']);
			$where .= " AND post_name = '" . $q['name'] . "'";
		} else if ('' != $q['pagename']) {
			$q['pagename'] = sanitize_title(basename(str_replace('%2F', '/', urlencode($q['pagename']))));
			$q['name'] = $q['pagename'];
			$where .= " AND post_name = '" . $q['pagename'] . "'";
		}


		if ( (int) $q['w'] ) {
			$q['w'] = ''.intval($q['w']);
			$where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'";
		}

		if ( intval($q['comments_popup']) )
			$q['p'] = intval($q['comments_popup']);

		// If a post number is specified, load that post
		if (($q['p'] != '') && intval($q['p']) != 0) {
			$q['p'] =  (int) $q['p'];
			$where = ' AND ID = ' . $q['p'];
		}

		if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) {
			$q['page_id'] = intval($q['page_id']);
			$q['p'] = $q['page_id'];
			$where = ' AND ID = '.$q['page_id'];
		}

		// If a search pattern is specified, load the posts that match
		if (!empty($q['s'])) {
			$q['s'] = addslashes_gpc($q['s']);
			$search = ' AND (';
			$q['s'] = preg_replace('/, +/', ' ', $q['s']);
			$q['s'] = str_replace(',', ' ', $q['s']);
			$q['s'] = str_replace('"', ' ', $q['s']);
			$q['s'] = trim($q['s']);
			if ($q['exact']) {
				$n = '';
			} else {
				$n = '%';
			}
			if (!$q['sentence']) {
				$s_array = explode(' ',$q['s']);
				$q['search_terms'] = $s_array;
				$search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))';
				for ( $i = 1; $i < count($s_array); $i = $i + 1) {
					$search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))';
				}
				$search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')';
				$search .= ')';
			} else {
				$search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))';
			}
		}

		// Category stuff

		if ((empty($q['cat'])) || ($q['cat'] == '0') || 
				// Bypass cat checks if fetching specific posts
				( $this->is_single || $this->is_page )) {
			$whichcat='';
		} else {
			$q['cat'] = ''.urldecode($q['cat']).'';
			$q['cat'] = addslashes_gpc($q['cat']);
			if (stristr($q['cat'],'-')) {
				// Note: if we have a negative, we ignore all the positives. It must
				// always mean 'everything /except/ this one'. We should be able to do
				// multiple negatives but we don't :-(
				$eq = '!=';
				$andor = 'AND';
				$q['cat'] = explode('-',$q['cat']);
				$q['cat'] = intval($q['cat'][1]);
			} else {
				$eq = '=';
				$andor = 'OR';
			}
			$join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) ";
			$cat_array = preg_split('/[,\s]+/', $q['cat']);
			$whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]);
			$whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' ');
			for ($i = 1; $i < (count($cat_array)); $i = $i + 1) {
				$whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]);
				$whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' ');
			}
			$whichcat .= ')';
			if ($eq == '!=') {
				$q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category.
			}
		}

		// Category stuff for nice URIs

		if ('' != $q['category_name']) {
			if (stristr($q['category_name'],'/')) {
				$q['category_name'] = explode('/',$q['category_name']);
				if ($q['category_name'][count($q['category_name'])-1]) {
					$q['category_name'] = $q['category_name'][count($q['category_name'])-1]; // no trailing slash
				} else {
					$q['category_name'] = $q['category_name'][count($q['category_name'])-2]; // there was a trailling slash
				}
			}
			$q['category_name'] = sanitize_title($q['category_name']);
			$tables = ", $wpdb->post2cat, $wpdb->categories";
			$join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) ";
			$whichcat = " AND (category_nicename = '" . $q['category_name'] . "'";
			$q['cat'] = $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE category_nicename = '" . $q['category_name'] . "'");
			$whichcat .= get_category_children($q['cat'], " OR category_id = ");
			$whichcat .= ")";
		}

		// Author/user stuff

		if ((empty($q['author'])) || ($q['author'] == '0')) {
			$whichauthor='';
		} else {
			$q['author'] = ''.urldecode($q['author']).'';
			$q['author'] = addslashes_gpc($q['author']);
			if (stristr($q['author'], '-')) {
				$eq = '!=';
				$andor = 'AND';
				$q['author'] = explode('-', $q['author']);
				$q['author'] = ''.intval($q['author'][1]);
			} else {
				$eq = '=';
				$andor = 'OR';
			}
			$author_array = preg_split('/[,\s]+/', $q['author']);
			$whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]);
			for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
				$whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]);
			}
			$whichauthor .= ')';
		}

		// Author stuff for nice URIs

		if ('' != $q['author_name']) {
			if (stristr($q['author_name'],'/')) {
				$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 trailling slash
				}
			}
			$q['author_name'] = sanitize_title($q['author_name']);
			$q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
			$whichauthor .= ' AND (post_author = '.intval($q['author']).')';
		}

		$where .= $search.$whichcat.$whichauthor;

		if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) {
			$q['order']='DESC';
		}

		// Order by
		if (empty($q['orderby'])) {
			$q['orderby']='date '.$q['order'];
		} else {
			// Used to filter values
			$allowed_keys = array('author','date','category','title');
			$q['orderby'] = urldecode($q['orderby']);
			$q['orderby'] = addslashes_gpc($q['orderby']);
			$orderby_array = explode(' ',$q['orderby']);
			if (!in_array($orderby_array[0],$allowed_keys)) {
				$orderby_array[0] = 'date';
			}
			$q['orderby'] = $orderby_array[0].' '.$q['order'];
			if (count($orderby_array)>1) {
				for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) {
					// Only allow certain values for safety
					if (in_array($orderby_array[$i],$allowed_keys)) {
						$q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order'];
					}
				}
			}
		}

		$now = gmdate('Y-m-d H:i:59');

		if ($pagenow != 'post.php' && $pagenow != 'edit.php') {
			$where .= " AND post_date_gmt <= '$now'";
			$distinct = 'DISTINCT';
		}

		if ($this->is_page) {
			$where .= ' AND (post_status = "static"';
		} else {
			$where .= ' AND (post_status = "publish"';
		}

		// Get private posts
		if (isset($user_ID) && ('' != intval($user_ID)))
			$where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')";
		else
			$where .= ')';

		// Apply filters on where and join prior to paging so that any
		// manipulations to them are reflected in the paging by day queries.
		$where = apply_filters('posts_where', $where);
		$join = apply_filters('posts_join', $join);

		// Paging
		if (empty($q['nopaging']) && ! $this->is_single) {
			$page = $q['paged'];
			if (empty($page)) {
				$page = 1;
			}

			if (($q['what_to_show'] == 'posts')) {
				$pgstrt = '';
				$pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', ';
				$limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
			} elseif ($q['what_to_show'] == 'days') {
				$startrow = $q['posts_per_page'] * (intval($page)-1);
				$start_date = $wpdb->get_var("SELECT max(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $startrow,1");
				$endrow = $startrow + $q['posts_per_page'] - 1;
				$end_date = $wpdb->get_var("SELECT min(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $endrow,1");

				if ($page > 1) {
					$where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'";
				} else {
					$where .= " AND post_date >= '$end_date'";
				}
			}
		}

		// Apply post-paging filters on where and join.  Only plugins that
		// manipulate paging queries should use these hooks.
		$where = apply_filters('posts_where_paged', $where);
		$where .= " GROUP BY $wpdb->posts.ID";
		$join = apply_filters('posts_join_paged', $join);
		$request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1".$where." ORDER BY post_" . $q['orderby'] . " $limits";

		if ($q['preview']) {
			$request = 'SELECT 1-1'; // dummy mysql query for the preview
			// little funky fix for IEwin, rawk on that code
			$is_winIE = ((preg_match('/MSIE/',$HTTP_USER_AGENT)) && (preg_match('/Win/',$HTTP_USER_AGENT)));
			if (($is_winIE) && (!isset($IEWin_bookmarklet_fix))) {
				$preview_content =  preg_replace('/\%u([0-9A-F]{4,4})/e',  "'&#'.base_convert('\\1',16,10).';'", $preview_content);
			}
		}

		$this->posts = $wpdb->get_results($request);
		$this->posts = apply_filters('the_posts', $this->posts);
		$this->post_count = count($this->posts);
		if ($this->post_count > 0) {
			$this->post = $this->posts[0];
		}

		update_post_caches($this->posts);
		
		// Save any changes made to the query vars.
		$this->query_vars = $q;
		return $this->posts;
	}
Ejemplo n.º 23
0
/**
 * Builds the WHERE part in search queries.
 *
 * @param string $where
 *
 * @return string
 */
function custom_search_where($where)
{
    global $wpdb, $wp_query, $cp_options;
    $old_where = $where;
    // intercept the old where statement
    if (is_search() && isset($_GET['s'])) {
        if (!cp_search_index_enabled()) {
            // get the custom fields to add to search
            $customs = cp_custom_search_fields();
            // add some internal custom fields to search
            $customs = array_merge($customs, array('cp_sys_ad_conf_id'));
        }
        $query = '';
        $var_q = stripslashes($_GET['s']);
        //empty the s parameter if set to default search text
        if (__('What are you looking for?', APP_TD) == $var_q) {
            $var_q = '';
        }
        if (isset($_GET['sentence']) || $var_q == '') {
            $search_terms = array($var_q);
        } else {
            preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $var_q, $matches);
            $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
        }
        if (!isset($_GET['exact'])) {
            $_GET['exact'] = '';
        }
        $n = $_GET['exact'] ? '' : '%';
        $searchand = '';
        foreach ((array) $search_terms as $term) {
            $term = addslashes_gpc($term);
            $query .= "{$searchand}(";
            if (!cp_search_index_enabled()) {
                $query .= "({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}')";
                $query .= " OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')";
                $query .= " OR ((t.name LIKE '{$n}{$term}{$n}')) OR ((t.slug LIKE '{$n}{$term}{$n}'))";
                foreach ($customs as $custom) {
                    $query .= " OR (";
                    $query .= "(m.meta_key = '{$custom}')";
                    $query .= " AND (m.meta_value LIKE '{$n}{$term}{$n}')";
                    $query .= ")";
                }
            } else {
                $query .= "({$wpdb->posts}.post_content_filtered LIKE '{$n}{$term}{$n}')";
            }
            $query .= ")";
            $searchand = ' AND ';
        }
        $term = esc_sql($var_q);
        if (!isset($_GET['sentence']) && count($search_terms) > 1 && $search_terms[0] != $var_q) {
            if (!cp_search_index_enabled()) {
                $query .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}')";
                $query .= " OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')";
            } else {
                $query .= " OR ({$wpdb->posts}.post_content_filtered LIKE '{$n}{$term}{$n}')";
            }
        }
        if (!empty($query)) {
            $where = " AND ({$query}) AND ({$wpdb->posts}.post_status = 'publish') ";
            // setup the array for post types
            $post_type_array = array();
            // always include the ads post type
            $post_type_array[] = APP_POST_TYPE;
            // check to see if we include blog posts
            if (!$cp_options->search_ex_blog) {
                $post_type_array[] = 'post';
            }
            // check to see if we include pages
            if (!$cp_options->search_ex_pages) {
                $post_type_array[] = 'page';
            }
            // build the post type filter sql from the array values
            $post_type_filter = "'" . implode("','", $post_type_array) . "'";
            // return the post type sql to complete the where clause
            $where .= " AND ({$wpdb->posts}.post_type IN ({$post_type_filter})) ";
        }
        remove_filter('posts_where', 'custom_search_where');
    }
    return $where;
}
Ejemplo n.º 24
0
 /**
  * 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.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID, $_wp_using_ext_object_cache;
     $this->parse_query();
     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 = '';
     $fields = '';
     $post_status_join = false;
     $page = 1;
     if (isset($q['caller_get_posts'])) {
         _deprecated_argument('WP_Query', '3.1', __('"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['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']);
     }
     // 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 = "{$wpdb->posts}.ID";
             break;
         case 'id=>parent':
             $fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent";
             break;
         default:
             $fields = "{$wpdb->posts}.*";
     }
     // If a month is specified in the querystring, load that month
     if ($q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'";
     }
     // If we've got a post_type AND its 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']);
         $where .= " AND {$wpdb->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 ({$wpdb->posts}.ID = '{$reqpage}')";
             $reqpage_obj = get_page($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 {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
     }
     if ($q['w']) {
         $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'";
     }
     if (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']) {
         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$wpdb->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']);
     }
     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 {$wpdb->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if (!empty($q['sentence'])) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\r\\n\\t ",+])|^)[^\\r\\n\\t ",+]+/', $q['s'], $matches);
             $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]);
         }
         $n = !empty($q['exact']) ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = esc_sql(like_escape($term));
             $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
             if (!is_user_logged_in()) {
                 $search .= " AND ({$wpdb->posts}.post_password = '') ";
             }
         }
     }
     // Allow plugins to contextually add/remove/modify the search section of the database query
     $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($wpdb->posts, 'ID');
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     if ($this->is_tax) {
         if (empty($post_type)) {
             $post_type = 'any';
             $post_status_join = true;
         } elseif (in_array('attachment', (array) $post_type)) {
             $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);
                 $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);
                 $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);
         }
     }
     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') {
         $whichauthor = '';
     } else {
         $q['author'] = (string) urldecode($q['author']);
         $q['author'] = addslashes_gpc($q['author']);
         if (strpos($q['author'], '-') !== false) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = (string) absint($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $_author_array = array();
         foreach ($author_array as $key => $_author) {
             $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author);
         }
         $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')';
         unset($author_array, $_author_array);
     }
     // 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 ({$wpdb->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'], $wpdb->posts);
     }
     $where .= $search . $whichauthor . $whichmimetype;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $orderby = "{$wpdb->posts}.post_date " . $q['order'];
     } elseif ('none' == $q['orderby']) {
         $orderby = '';
     } else {
         // Used to filter values
         $allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
             $allowed_keys[] = 'meta_value_num';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = array();
         foreach (explode(' ', $q['orderby']) as $i => $orderby) {
             // Only allow certain values for safety
             if (!in_array($orderby, $allowed_keys)) {
                 continue;
             }
             switch ($orderby) {
                 case 'menu_order':
                     break;
                 case 'ID':
                     $orderby = "{$wpdb->posts}.ID";
                     break;
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->postmeta}.meta_value";
                     break;
                 case 'meta_value_num':
                     $orderby = "{$wpdb->postmeta}.meta_value+0";
                     break;
                 case 'comment_count':
                     $orderby = "{$wpdb->posts}.comment_count";
                     break;
                 default:
                     $orderby = "{$wpdb->posts}.post_" . $orderby;
             }
             $orderby_array[] = $orderby;
         }
         $orderby = implode(',', $orderby_array);
         if (empty($orderby)) {
             $orderby = "{$wpdb->posts}.post_date " . $q['order'];
         } else {
             $orderby .= " {$q['order']}";
         }
     }
     if (is_array($post_type)) {
         $post_type_cap = 'multiple_post_type';
     } else {
         $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)) {
             $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')");
         }
     } elseif (!empty($post_type) && is_array($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')";
     } elseif (!empty($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'";
         $post_type_object = get_post_type_object($post_type);
     } elseif ($this->is_attachment) {
         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
         $post_type_object = get_post_type_object('attachment');
     } elseif ($this->is_page) {
         $where .= " AND {$wpdb->posts}.post_type = 'page'";
         $post_type_object = get_post_type_object('page');
     } else {
         $where .= " AND {$wpdb->posts}.post_type = 'post'";
         $post_type_object = get_post_type_object('post');
     }
     if (!empty($post_type_object)) {
         $edit_cap = $post_type_object->cap->edit_post;
         $read_cap = $post_type_object->cap->read_post;
         $edit_others_cap = $post_type_object->cap->edit_others_posts;
         $read_private_cap = $post_type_object->cap->read_private_posts;
     } else {
         $edit_cap = 'edit_' . $post_type_cap;
         $read_cap = 'read_' . $post_type_cap;
         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
         $read_private_cap = 'read_private_' . $post_type_cap . 's';
     }
     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) {
                 $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'";
             }
         } else {
             foreach (get_post_stati() as $status) {
                 if (in_array($status, $q_status)) {
                     if ('private' == $status) {
                         $p_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     } else {
                         $r_status[] = "{$wpdb->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[] = "({$wpdb->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[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $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) . "))";
             }
         }
         foreach ($statuswheres as $statuswhere) {
             $where .= " AND {$statuswhere}";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$wpdb->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 {$wpdb->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 {$wpdb->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 {$wpdb->posts}.post_status = '{$state}'" : " OR {$wpdb->posts}.post_author = {$user_ID} AND {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         $where .= ')';
     }
     if (!empty($this->meta_query->queries)) {
         $clauses = $this->meta_query->get_sql('post', $wpdb->posts, 'ID', $this);
         $join .= $clauses['join'];
         $where .= $clauses['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']) {
         $where = apply_filters_ref_array('posts_where', array($where, &$this));
         $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 (empty($q['offset'])) {
             $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
         }
         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
     }
     // Comments feeds
     if ($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('comment_feed_join', array($cjoin, &$this));
             $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this));
             $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this));
             $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
             $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 : '';
         $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";
         }
     }
     $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']) {
         $where = apply_filters_ref_array('posts_where_paged', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_paged', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this));
         $limits = apply_filters_ref_array('post_limits', array($limits, &$this));
         $fields = apply_filters_ref_array('posts_fields', array($fields, &$this));
         // Filter all clauses at once, for convenience
         $clauses = (array) apply_filters_ref_array('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('posts_selection', $where . $groupby . $orderby . $limits . $join);
     // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_request', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_request', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this));
         $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this));
         $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this));
         // Filter all clauses at once, for convenience
         $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this));
         foreach ($pieces as $piece) {
             ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : '';
         }
     }
     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 {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this));
     }
     if ('ids' == $q['fields']) {
         $this->posts = $wpdb->get_col($this->request);
         return $this->posts;
     }
     if ('id=>parent' == $q['fields']) {
         $this->posts = $wpdb->get_results($this->request);
         $r = array();
         foreach ($this->posts as $post) {
             $r[$post->ID] = $post->post_parent;
         }
         return $r;
     }
     if ($old_request == $this->request && "{$wpdb->posts}.*" == $fields) {
         // First get the IDs and then fill in the objects
         $this->request = "SELECT {$found_rows} {$distinct} {$wpdb->posts}.ID FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
         $this->request = apply_filters('posts_request_ids', $this->request, $this);
         $ids = $wpdb->get_col($this->request);
         if ($ids) {
             $this->set_found_posts($q, $limits);
             _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']);
             $this->posts = array_map('get_post', $ids);
         } else {
             $this->found_posts = $this->max_num_pages = 0;
             $this->posts = array();
         }
     } else {
         $this->posts = $wpdb->get_results($this->request);
         $this->set_found_posts($q, $limits);
     }
     // Raw results filter. Prior to status checks.
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this));
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this));
         $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this));
         $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this));
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $climits = apply_filters_ref_array('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]->ID);
         $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] = 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__in = implode(',', array_map('absint', $sticky_posts));
             // honor post type(s) if not set to any
             $stickies_where = '';
             if ('any' != $post_type && '' != $post_type) {
                 if (is_array($post_type)) {
                     $post_types = join("', '", $post_type);
                 } else {
                     $post_types = $post_type;
                 }
                 $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')";
             }
             $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}");
             foreach ($stickies as $sticky_post) {
                 // Ignore sticky posts the current user cannot read or are not published.
                 if ('publish' != $sticky_post->post_status) {
                     continue;
                 }
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this));
     }
     $this->post_count = count($this->posts);
     // Always sanitize
     foreach ($this->posts as $i => $post) {
         $this->posts[$i] = sanitize_post($post, 'raw');
     }
     if ($q['cache_results']) {
         update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
     }
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }
Ejemplo n.º 25
0
/**
 * Build duplicated posts from a master post only in case of the duplicate not being present at the time.
 *
 * @param  string                $master_post_id The ID of the post to duplicate from. Master post doesn't need to be in the default language.
 *
 * @uses SitePress
 */
function icl_makes_duplicates_public($master_post_id)
{
    global $sitepress;
    $master_post = get_post($master_post_id);
    if ($master_post->post_status == 'auto-draft' || $master_post->post_type == 'revision') {
        return;
    }
    $active_langs = $sitepress->get_active_languages();
    foreach ($active_langs as $lang_to => $one) {
        $trid = $sitepress->get_element_trid($master_post->ID, 'post_' . $master_post->post_type);
        $lang_from = $sitepress->get_source_language_by_trid($trid);
        if ($lang_from == $lang_to) {
            continue;
        }
        $post_array['post_author'] = $master_post->post_author;
        $post_array['post_date'] = $master_post->post_date;
        $post_array['post_date_gmt'] = $master_post->post_date_gmt;
        $post_array['post_content'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_content, $lang_to, array('context' => 'post', 'attribute' => 'content', 'key' => $master_post->ID)));
        $post_array['post_title'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_title, $lang_to, array('context' => 'post', 'attribute' => 'title', 'key' => $master_post->ID)));
        $post_array['post_excerpt'] = addslashes_gpc(apply_filters('icl_duplicate_generic_string', $master_post->post_excerpt, $lang_to, array('context' => 'post', 'attribute' => 'excerpt', 'key' => $master_post->ID)));
        $post_array['post_status'] = $master_post->post_status;
        $post_array['post_category'] = $master_post->post_category;
        $post_array['comment_status'] = $master_post->comment_status;
        $post_array['ping_status'] = $master_post->ping_status;
        $post_array['post_name'] = $master_post->post_name;
        $post_array['menu_order'] = $master_post->menu_order;
        $post_array['post_type'] = $master_post->post_type;
        $post_array['post_mime_type'] = $master_post->post_mime_type;
        if ($master_post->post_parent) {
            $parent = icl_object_id($master_post->post_parent, $master_post->post_type, false, $lang_to);
            $post_array['post_parent'] = $parent;
        }
        $id = wp_insert_post($post_array);
        $sitepress->set_element_language_details($id, 'post_' . $post_array['post_type'], $trid, $lang_to, $lang_from, false);
    }
}
if ($_GET["orderby"] == 'category') {
    global $author, $m;
    $orderby = 'category';
    if ($_GET["order"] == '') {
        $order = "DESC";
    } else {
        $order = $_GET["order"];
    }
    $year = '' . intval($_GET["m"]);
    $m = $year;
    $author = '' . intval($_GET["author"]);
    if (empty($author)) {
        $whichauthor = '';
    } else {
        $author = '' . urldecode($author) . '';
        $author = addslashes_gpc($author);
        if (stristr($author, '-')) {
            $eq = '!=';
            $andor = 'AND';
            $author = explode('-', $author);
            $author = '' . intval($author[1]);
        } else {
            $eq = '=';
            $andor = 'OR';
        }
        $author_array = explode(' ', $author);
        $whichauthor .= ' AND (post_author ' . $eq . ' ' . intval($author_array[0]);
        for ($i = 1; $i < count($author_array); $i = $i + 1) {
            $whichauthor .= ' ' . $andor . ' post_author ' . $eq . ' ' . intval($author_array[$i]);
        }
        $whichauthor .= ')';
Ejemplo n.º 27
0
             break;
     }
     exit;
     break;
 case 'find_posts':
     check_ajax_referer('find-posts');
     if (empty($_POST['ps'])) {
         exit;
     }
     $what = isset($_POST['pages']) ? 'page' : 'post';
     $s = stripslashes($_POST['ps']);
     preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
     $search_terms = array_map('_search_terms_tidy', $matches[0]);
     $searchand = $search = '';
     foreach ((array) $search_terms as $term) {
         $term = addslashes_gpc($term);
         $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '%{$term}%') OR ({$wpdb->posts}.post_content LIKE '%{$term}%'))";
         $searchand = ' AND ';
     }
     $term = $wpdb->escape($s);
     if (count($search_terms) > 1 && $search_terms[0] != $s) {
         $search .= " OR ({$wpdb->posts}.post_title LIKE '%{$term}%') OR ({$wpdb->posts}.post_content LIKE '%{$term}%')";
     }
     $posts = $wpdb->get_results("SELECT ID, post_title, post_status, post_date FROM {$wpdb->posts} WHERE post_type = '{$what}' AND post_status IN ('draft', 'publish') AND ({$search}) ORDER BY post_date_gmt DESC LIMIT 50");
     if (!$posts) {
         exit(__('No posts found.'));
     }
     $html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>' . __('Title') . '</th><th>' . __('Date') . '</th><th>' . __('Status') . '</th></tr></thead><tbody>';
     foreach ($posts as $post) {
         switch ($post->post_status) {
             case 'publish':
Ejemplo n.º 28
0
 function aioseop_ajax_save_meta()
 {
     if (!empty($_POST['_inline_edit']) && $_POST['_inline_edit'] != 'undefined') {
         check_ajax_referer('inlineeditnonce', '_inline_edit');
     } else {
         check_ajax_referer('screen-options-nonce', 'screenoptionnonce');
     }
     $post_id = intval($_POST['post_id']);
     $new_meta = $_POST['new_meta'];
     $target = $_POST['target_meta'];
     update_post_meta($post_id, '_aioseop_' . $target, esc_attr($new_meta));
     $result = get_post_meta($post_id, '_aioseop_' . $target, true);
     if ($result != '') {
         $label = $result;
     } else {
         $label = '';
         $result = '<strong><i>' . __('No', 'all_in_one_seo_pack') . ' ' . $target . '</i></strong>';
     }
     $output = $result . '<a id="' . $target . 'editlink' . $post_id . '" href="javascript:void(0);"';
     $output .= 'onclick=\'aioseop_ajax_edit_meta_form(' . $post_id . ', ' . json_encode($label) . ', "' . $target . '");return false;\' title="' . __('Edit') . '">';
     $output .= '<img class="aioseop_edit_button" id="aioseop_edit_id" src="' . AIOSEOP_PLUGIN_IMAGES_URL . '/cog_edit.png" /></a>';
     die("jQuery('div#aioseop_" . $target . "_" . $post_id . "').fadeOut('fast', function() {\n\t\t\t  jQuery('div#aioseop_" . $target . "_" . $post_id . "').html('" . addslashes_gpc($output) . "').fadeIn('fast');\n\t\t});");
 }
Ejemplo n.º 29
0
 /**
  * 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;
 }
Ejemplo n.º 30
0
 /**
  * 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.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID, $_wp_using_ext_object_cache;
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     $q = $this->fill_query_vars($q);
     // First let's clear some variables
     $distinct = '';
     $whichcat = '';
     $whichauthor = '';
     $whichmimetype = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $fields = "{$wpdb->posts}.*";
     $post_status_join = false;
     $page = 1;
     if (!isset($q['caller_get_posts'])) {
         $q['caller_get_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']);
     }
     // 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;
     }
     // If a month is specified in the querystring, load that month
     if ($q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'";
     }
     // If we've got a post_type AND its 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($q['name']);
         $where .= " AND {$wpdb->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'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
             $page_paths = '/' . trim($q['pagename'], '/');
             $q['pagename'] = sanitize_title(basename($page_paths));
             $q['name'] = $q['pagename'];
             $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')";
             $reqpage_obj = get_page($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'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
         $attach_paths = '/' . trim($q['attachment'], '/');
         $q['attachment'] = sanitize_title(basename($attach_paths));
         $q['name'] = $q['attachment'];
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
     }
     if ($q['w']) {
         $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'";
     }
     if (intval($q['comments_popup'])) {
         $q['p'] = absint($q['comments_popup']);
     }
     // If an attachment is requested by number, let it supercede 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 {$wpdb->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$wpdb->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']);
     }
     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 {$wpdb->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if (!empty($q['sentence'])) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches);
             $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]);
         }
         $n = !empty($q['exact']) ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = addslashes_gpc($term);
             $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         $term = esc_sql($q['s']);
         if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) {
             $search .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')";
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
             if (!is_user_logged_in()) {
                 $search .= " AND ({$wpdb->posts}.post_password = '') ";
             }
         }
     }
     // Allow plugins to contextually add/remove/modify the search section of the database query
     $search = apply_filters_ref_array('posts_search', array($search, &$this));
     // Category stuff
     if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) {
         $whichcat = '';
     } else {
         $q['cat'] = '' . urldecode($q['cat']) . '';
         $q['cat'] = addslashes_gpc($q['cat']);
         $cat_array = preg_split('/[,\\s]+/', $q['cat']);
         $q['cat'] = '';
         $req_cats = array();
         foreach ((array) $cat_array as $cat) {
             $cat = intval($cat);
             $req_cats[] = $cat;
             $in = $cat > 0;
             $cat = abs($cat);
             if ($in) {
                 $q['category__in'][] = $cat;
                 $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
             } else {
                 $q['category__not_in'][] = $cat;
                 $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
             }
         }
         $q['cat'] = implode(',', $req_cats);
     }
     if (!empty($q['category__in'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $include_cats = "'" . implode("', '", $q['category__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) ";
     }
     if (!empty($q['category__not_in'])) {
         $cat_string = "'" . implode("', '", $q['category__not_in']) . "'";
         $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'category' AND tt.term_id IN ({$cat_string}) )";
     }
     // Category stuff for nice URLs
     if ('' != $q['category_name'] && !$this->is_singular) {
         $q['category_name'] = implode('/', array_map('sanitize_title', explode('/', $q['category_name'])));
         $reqcat = get_category_by_path($q['category_name']);
         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
         $cat_paths = '/' . trim($q['category_name'], '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
         $q['category_name'] = sanitize_title(basename($cat_paths));
         $cat_paths = explode('/', $cat_paths);
         $cat_path = '';
         foreach ((array) $cat_paths as $pathdir) {
             $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir);
         }
         //if we don't match the entire hierarchy fallback on just matching the nicename
         if (empty($reqcat)) {
             $reqcat = get_category_by_path($q['category_name'], false);
         }
         if (!empty($reqcat)) {
             $reqcat = $reqcat->term_id;
         } else {
             $reqcat = 0;
         }
         $q['cat'] = $reqcat;
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' ";
         $in_cats = array($q['cat']);
         $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
         $in_cats = "'" . implode("', '", $in_cats) . "'";
         $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})";
         $groupby = "{$wpdb->posts}.ID";
     }
     // Tags
     if ('' != $q['tag']) {
         if (strpos($q['tag'], ',') !== false) {
             $tags = preg_split('/[,\\s]+/', $q['tag']);
             foreach ((array) $tags as $tag) {
                 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $tag;
             }
         } else {
             if (preg_match('/[+\\s]+/', $q['tag']) || !empty($q['cat'])) {
                 $tags = preg_split('/[+\\s]+/', $q['tag']);
                 foreach ((array) $tags as $tag) {
                     $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                     $q['tag_slug__and'][] = $tag;
                 }
             } else {
                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
                 $q['tag_slug__in'][] = $q['tag'];
             }
         }
     }
     if (!empty($q['category__in']) || !empty($q['meta_key']) || !empty($q['tag__in']) || !empty($q['tag_slug__in'])) {
         $groupby = "{$wpdb->posts}.ID";
     }
     if (!empty($q['tag__in']) && empty($q['cat'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
         $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) ";
         $reqtag = term_exists($q['tag__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag['term_id'];
         }
     }
     if (!empty($q['tag_slug__in']) && empty($q['cat'])) {
         $join = " INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) INNER JOIN {$wpdb->terms} ON ({$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id) ";
         $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' ";
         $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
         $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) ";
         $reqtag = get_term_by('slug', $q['tag_slug__in'][0], 'post_tag');
         if (!empty($reqtag)) {
             $q['tag_id'] = $reqtag->term_id;
         }
     }
     if (!empty($q['tag__not_in'])) {
         $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'";
         $whichcat .= " AND {$wpdb->posts}.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'post_tag' AND tt.term_id IN ({$tag_string}) )";
     }
     // Tag and slug intersections.
     $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag', 'tag__in' => 'post_tag', 'tag_slug__in' => 'post_tag');
     $tagin = array('tag__in', 'tag_slug__in');
     // These are used to make some exceptions below
     foreach ($intersections as $item => $taxonomy) {
         if (empty($q[$item])) {
             continue;
         }
         if (in_array($item, $tagin) && empty($q['cat'])) {
             continue;
         }
         // We should already have what we need if categories aren't being used
         if ($item != 'category__and') {
             $reqtag = term_exists($q[$item][0], 'post_tag');
             if (!empty($reqtag)) {
                 $q['tag_id'] = $reqtag['term_id'];
             }
         }
         if (in_array($item, array('tag_slug__and', 'tag_slug__in'))) {
             $taxonomy_field = 'slug';
         } else {
             $taxonomy_field = 'term_id';
         }
         $q[$item] = array_unique($q[$item]);
         $tsql = "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->term_relationships} tr ON (p.ID = tr.object_id) INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN {$wpdb->terms} t ON (tt.term_id = t.term_id)";
         $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')";
         if (!in_array($item, $tagin)) {
             // This next line is only helpful if we are doing an and relationship
             $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
         }
         $post_ids = $wpdb->get_col($tsql);
         if (count($post_ids)) {
             $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
         } else {
             $whichcat = " AND 0 = 1";
             break;
         }
     }
     // Taxonomies
     if ($this->is_tax) {
         if ('' != $q['taxonomy']) {
             $taxonomy = $q['taxonomy'];
             $tt[$taxonomy] = $q['term'];
         } else {
             foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) {
                 if ($t->query_var && '' != $q[$t->query_var]) {
                     $tt[$taxonomy] = $q[$t->query_var];
                     break;
                 }
             }
         }
         $terms = get_terms($taxonomy, array('slug' => $tt[$taxonomy], 'hide_empty' => !is_taxonomy_hierarchical($taxonomy)));
         if (is_wp_error($terms) || empty($terms)) {
             $whichcat = " AND 0 ";
         } else {
             foreach ($terms as $term) {
                 $term_ids[] = $term->term_id;
                 if (is_taxonomy_hierarchical($taxonomy)) {
                     $children = get_term_children($term->term_id, $taxonomy);
                     $term_ids = array_merge($term_ids, $children);
                 }
             }
             $post_ids = get_objects_in_term($term_ids, $taxonomy);
             if (!is_wp_error($post_ids) && !empty($post_ids)) {
                 $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") ";
                 if (empty($post_type)) {
                     $post_type = 'any';
                     $post_status_join = true;
                 } elseif (in_array('attachment', (array) $post_type)) {
                     $post_status_join = true;
                 }
             } else {
                 $whichcat = " AND 0 ";
             }
         }
     }
     // Author/user stuff
     if (empty($q['author']) || $q['author'] == '0') {
         $whichauthor = '';
     } else {
         $q['author'] = (string) urldecode($q['author']);
         $q['author'] = addslashes_gpc($q['author']);
         if (strpos($q['author'], '-') !== false) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = (string) absint($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $_author_array = array();
         foreach ($author_array as $key => $_author) {
             $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author);
         }
         $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')';
         unset($author_array, $_author_array);
     }
     // 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 trailling slash
             }
         }
         $q['author_name'] = sanitize_title($q['author_name']);
         $q['author'] = get_user_by('slug', $q['author_name']);
         if ($q['author']) {
             $q['author'] = $q['author']->ID;
         }
         $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')';
     }
     // MIME-Type stuff for attachment browsing
     if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) {
         $table_alias = $post_status_join ? $wpdb->posts : '';
         $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $table_alias);
     }
     $where .= $search . $whichcat . $whichauthor . $whichmimetype;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
     } elseif ('none' == $q['orderby']) {
         $q['orderby'] = '';
     } else {
         // Used to filter values
         $allowed_keys = array('author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
             $allowed_keys[] = 'meta_value_num';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = explode(' ', $q['orderby']);
         $q['orderby'] = '';
         foreach ($orderby_array as $i => $orderby) {
             // Only allow certain values for safety
             if (!in_array($orderby, $allowed_keys)) {
                 continue;
             }
             switch ($orderby) {
                 case 'menu_order':
                     break;
                 case 'ID':
                     $orderby = "{$wpdb->posts}.ID";
                     break;
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->postmeta}.meta_value";
                     break;
                 case 'meta_value_num':
                     $orderby = "{$wpdb->postmeta}.meta_value+0";
                     break;
                 case 'comment_count':
                     $orderby = "{$wpdb->posts}.comment_count";
                     break;
                 default:
                     $orderby = "{$wpdb->posts}.post_" . $orderby;
             }
             $q['orderby'] .= ($i == 0 ? '' : ',') . $orderby;
         }
         // append ASC or DESC at the end
         if (!empty($q['orderby'])) {
             $q['orderby'] .= " {$q['order']}";
         }
         if (empty($q['orderby'])) {
             $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order'];
         }
     }
     if (is_array($post_type)) {
         $post_type_cap = 'multiple_post_type';
     } else {
         $post_type_object = get_post_type_object($post_type);
         if (!empty($post_type_object)) {
             $post_type_cap = $post_type_object->capability_type;
         } else {
             $post_type_cap = $post_type;
         }
     }
     $exclude_post_types = '';
     $in_search_post_types = get_post_types(array('exclude_from_search' => false));
     if (!empty($in_search_post_types)) {
         $exclude_post_types .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')");
     }
     if ('any' == $post_type) {
         $where .= $exclude_post_types;
     } elseif (!empty($post_type) && is_array($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')";
     } elseif (!empty($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'";
         $post_type_object = get_post_type_object($post_type);
     } elseif ($this->is_attachment) {
         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
         $post_type_object = get_post_type_object('attachment');
     } elseif ($this->is_page) {
         $where .= " AND {$wpdb->posts}.post_type = 'page'";
         $post_type_object = get_post_type_object('page');
     } else {
         $where .= " AND {$wpdb->posts}.post_type = 'post'";
         $post_type_object = get_post_type_object('post');
     }
     if (!empty($post_type_object)) {
         $post_type_cap = $post_type_object->capability_type;
         $edit_cap = $post_type_object->cap->edit_post;
         $read_cap = $post_type_object->cap->read_post;
         $edit_others_cap = $post_type_object->cap->edit_others_posts;
         $read_private_cap = $post_type_object->cap->read_private_posts;
     } else {
         $edit_cap = 'edit_' . $post_type_cap;
         $read_cap = 'read_' . $post_type_cap;
         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
         $read_private_cap = 'read_private_' . $post_type_cap . 's';
     }
     if (isset($q['post_status']) && '' != $q['post_status']) {
         $statuswheres = array();
         $q_status = explode(',', $q['post_status']);
         $r_status = array();
         $p_status = array();
         $e_status = array();
         if ($q['post_status'] == 'any') {
             foreach (get_post_stati(array('exclude_from_search' => true)) as $status) {
                 $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'";
             }
         } else {
             foreach (get_post_stati() as $status) {
                 if (in_array($status, $q_status)) {
                     if ('private' == $status) {
                         $p_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     } else {
                         $r_status[] = "{$wpdb->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[] = "({$wpdb->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[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $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) . "))";
             }
         }
         foreach ($statuswheres as $statuswhere) {
             $where .= " AND {$statuswhere}";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$wpdb->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 {$wpdb->posts}.post_status = '{$state}'";
         }
         if (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 {$wpdb->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 {$wpdb->posts}.post_status = '{$state}'" : " OR {$wpdb->posts}.post_author = {$user_ID} AND {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         $where .= ')';
     }
     // postmeta queries
     if (!empty($q['meta_key']) || !empty($q['meta_value'])) {
         $join .= " JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) ";
     }
     if (!empty($q['meta_key'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s ", $q['meta_key']);
     }
     if (!empty($q['meta_value'])) {
         if (empty($q['meta_compare']) || !in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<='))) {
             $q['meta_compare'] = '=';
         }
         $where .= $wpdb->prepare("AND {$wpdb->postmeta}.meta_value {$q['meta_compare']} %s ", $q['meta_value']);
     }
     // 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']) {
         $where = apply_filters_ref_array('posts_where', array($where, &$this));
         $join = apply_filters_ref_array('posts_join', array($join, &$this));
     }
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = absint($q['paged']);
         if (empty($page)) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = '';
             $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
         }
     }
     // Comments feeds
     if ($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('comment_feed_join', array($cjoin, &$this));
             $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this));
             $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this));
             $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
             $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 : '';
         $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";
         }
     }
     $orderby = $q['orderby'];
     // Apply post-paging filters on where and join.  Only plugins that
     // manipulate paging queries should use these hooks.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_paged', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_paged', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this));
         $limits = apply_filters_ref_array('post_limits', array($limits, &$this));
         $fields = apply_filters_ref_array('posts_fields', array($fields, &$this));
     }
     // Announce current selection parameters.  For use by caching plugins.
     do_action('posts_selection', $where . $groupby . $orderby . $limits . $join);
     // Filter again for the benefit of caching plugins.  Regular plugins should use the hooks above.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_request', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_request', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this));
         $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this));
         $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this));
     }
     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 = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this));
     }
     $this->posts = $wpdb->get_results($this->request);
     // Raw results filter.  Prior to status checks.
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this));
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this));
         $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this));
         $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this));
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $climits = apply_filters_ref_array('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);
     }
     if (!$q['no_found_rows'] && !empty($limits)) {
         $found_posts_query = apply_filters_ref_array('found_posts_query', array('SELECT FOUND_ROWS()', &$this));
         $this->found_posts = $wpdb->get_var($found_posts_query);
         $this->found_posts = apply_filters_ref_array('found_posts', array($this->found_posts, &$this));
         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
     }
     // 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 && current_user_can($edit_cap, $this->posts[0]->ID)) {
             $this->posts[0] = 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['caller_get_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__in = implode(',', array_map('absint', $sticky_posts));
             // honor post type(s) if not set to any
             $stickies_where = '';
             if ('any' != $post_type && '' != $post_type) {
                 if (is_array($post_type)) {
                     $post_types = join("', '", $post_type);
                 } else {
                     $post_types = $post_type;
                 }
                 $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')";
             }
             $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}");
             foreach ($stickies as $sticky_post) {
                 // Ignore sticky posts the current user cannot read or are not published.
                 if ('publish' != $sticky_post->post_status) {
                     continue;
                 }
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this));
     }
     $this->post_count = count($this->posts);
     // Sanitize before caching so it'll only get done once
     for ($i = 0; $i < $this->post_count; $i++) {
         $this->posts[$i] = sanitize_post($this->posts[$i], 'raw');
     }
     if ($q['cache_results']) {
         update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
     }
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }