Esempio n. 1
0
/**
 * Count number of attachments for a clearbase post.
 *
 * If you set the optional mime_type parameter, then an array will still be
 * returned, but will only have the item you are looking for. It does not give
 * you the number of attachments that are children of a post. You can get that
 * by counting the number of children that post has.
 *
 * @since 2.5.0
 *
 * @global wpdb $wpdb
 *
 * @param int $post_id.  The ID of parent post
 *  
 * @param string|array $mime_type Optional. Array or comma-separated list of
 *                                MIME patterns. Default empty.
 * @return object An object containing the attachment counts by mime type.
 */
function clearbase_count_attachments($post = null, $mime_type = '')
{
    global $wpdb;
    if (!($post = get_post($post))) {
        throw new WP_Error('invalid_post', 'You must specify a valid post!');
    }
    $and = wp_post_mime_type_where($mime_type);
    $count = $wpdb->get_results($wpdb->prepare("SELECT post_mime_type, COUNT( * ) AS num_posts FROM {$wpdb->posts} \n        WHERE post_type = 'attachment' AND post_parent = %d \n        AND post_status != 'trash' {$and} GROUP BY post_mime_type", $post->ID), ARRAY_A);
    $counts = array();
    foreach ((array) $count as $row) {
        $counts[$row['post_mime_type']] = $row['num_posts'];
    }
    $counts['trash'] = $wpdb->get_var($wpdb->prepare("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' \n        AND post_parent = %d AND post_status = 'trash' {$and}", $post->ID));
    /**
     * Modify returned attachment counts by mime type.
     *
     * @since 3.7.0
     *
     * @param object  $counts    An object containing the attachment counts by
     *                          mime type.
     * @param WP_POST $post     The parent post of the attachments.
     * @param string $mime_type The mime type pattern used to filter the attachments
     *                          counted.
     */
    return apply_filters('clearbase_count_attachments', (object) $counts, $post, $mime_type);
}
Esempio n. 2
0
 /**
  * Construct a base SQL statement
  *
  * @since 1.0.36
  * @param array $what What columns to SELECT from the DB
  */
 private function base_select($what = array('*'))
 {
     global $wpdb;
     foreach ($what as $what_k => $what_v) {
         if ($what_v != '*') {
             $what[$what_k] = '`' . $what_v . '`';
         }
     }
     $what = implode(',', $what);
     return "SELECT {$what} FROM `{$wpdb->posts}` WHERE `post_status` = 'inherit' AND `post_type` = 'attachment' " . wp_post_mime_type_where('image') . " ";
 }
Esempio n. 3
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;
 }
Esempio n. 4
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;
 }
 function language_filter_upload_page()
 {
     global $sitepress, $wpdb;
     //save query arguments for building language-specific links
     $href_args = array();
     foreach ($_GET as $key => $value) {
         $href_args[$key] = urlencode(stripslashes($value));
     }
     //get language code
     if (isset($_GET['lang'])) {
         $lang_code = $_GET['lang'];
     } else {
         if (method_exists($sitepress, 'get_admin_language_cookie')) {
             $lang_code = $sitepress->get_admin_language_cookie();
         }
         if (empty($lang_code)) {
             $lang_code = $sitepress->get_default_language();
         }
     }
     $active_languages = $sitepress->get_active_languages();
     $active_languages[] = array('code' => 'all', 'display_name' => __('All languages', 'sitepress'));
     $langc['all'] = 0;
     $language_items = array();
     foreach ($active_languages as $lang) {
         //count language-specific attachments
         if ($lang['code'] != 'all') {
             //select all attachments
             $sql = $wpdb->prepare("\n\t\t\t\tSELECT COUNT(p.id)\n\t\t\t\tFROM {$wpdb->posts} AS p\n\t\t\t\tINNER JOIN {$wpdb->prefix}icl_translations AS t\n\t\t\t\t\tON t.element_id = p.id\n\t\t\t\tWHERE p.post_type = 'attachment'\n\t\t\t\tAND t.element_type ='post_attachment'\n\t\t\t\tAND t.language_code=%s\n\t\t\t", $lang['code']);
             //handle trash setting
             if (isset($_GET['status'])) {
                 $sql .= " AND p.post_status = 'trash' ";
             } else {
                 $sql .= " AND p.post_status != 'trash' ";
             }
             //select detached attachments
             if (isset($_GET['detached'])) {
                 $sql .= " AND p.post_parent = 0 ";
             }
             //select mime type(image,etc) attachments
             if (isset($_GET['post_mime_type'])) {
                 $sql .= wp_post_mime_type_where($_GET['post_mime_type'], 'p');
             }
             $sql = apply_filters('wpml-media_view-upload-page-sql', $sql, $lang);
             $res = apply_filters('wpml-media_view-upload-page-count', NULL, $lang);
             if (NULL === $res) {
                 $res = $wpdb->get_col($sql);
             }
             $langc[$lang['code']] = $res[0];
             $langc['all'] += $res[0];
         }
         //generation language block
         if ($lang['code'] == $lang_code) {
             $px = '<strong>';
             $sx = ' <span class="count">(' . $langc[$lang['code']] . ')</span></strong>';
         } else {
             $href_args['lang'] = $lang['code'];
             $px = '<a href="' . esc_url(add_query_arg($href_args, '')) . '">';
             $sx = '</a> <span class="count">(' . $langc[$lang['code']] . ')</span>';
         }
         $language_items[] = $px . $lang['display_name'] . $sx;
     }
     wp_enqueue_script('wpml-media-language-options', WPML_MEDIA_URL . '/res/js/language_options.js', array(), WPML_MEDIA_VERSION, true);
     wp_localize_script('wpml-media-language-options', 'language_items', $language_items);
 }
Esempio n. 6
0
/**
 * Generate a taxonomy- and term-specific [mla_gallery], limited by current_page and posts_per_page
 *
 * This function uses $wpdb functions for efficiency.
 *
 * @param array Attributes of the function: page, taxonomy, term, post_mime_type, posts_per_page, current_page
 *
 * @return integer number of posts matching taxonomy & term, before LIMIT. echoes HTML <h3>, <p> and <a> tags
 */
function mla_paginated_term_gallery($attr = NULL)
{
    global $wpdb;
    /*
     * Make sure $attr is an array, even if it's empty
     */
    if (empty($attr)) {
        $attr = array();
    } elseif (is_string($attr)) {
        $attr = shortcode_parse_atts($attr);
    }
    /*
     * Create the PHP variables we need
     */
    extract(shortcode_atts(array('page' => NULL, 'taxonomy' => 'attachment_tag', 'term' => '', 'post_mime_type' => 'all', 'posts_per_page' => 10, 'current_page' => 1), $attr));
    /*
     * Convert to objects for validation and labels
     */
    $taxonomy = get_taxonomy($taxonomy);
    $term = get_term_by('slug', $term, $taxonomy->name);
    if (empty($taxonomy)) {
        echo __('Taxonomy does not exist.', 'mla-child-theme');
        return;
    } elseif (empty($term)) {
        echo __('Term does not exist.', 'mla-child-theme');
        return;
    }
    $offset = absint($current_page - 1) * $posts_per_page;
    if ('all' == strtolower($post_mime_type)) {
        $count = $wpdb->get_var('SELECT COUNT(*) FROM ' . $wpdb->term_relationships . ' WHERE ( term_taxonomy_id = ' . $term->term_taxonomy_id . ' )');
        $posts = implode(',', $wpdb->get_col('SELECT object_id FROM ' . $wpdb->term_relationships . ' WHERE ( term_taxonomy_id = ' . $term->term_taxonomy_id . ' ) LIMIT ' . $offset . ', ' . $posts_per_page));
    } else {
        /*
         * $posts contains all post types, so we further limit the results to select attachments of the
         * desired MIME type, then apply the limit criteria.
         */
        $mime_where = wp_post_mime_type_where($post_mime_type, 'p');
        $posts = implode(',', $wpdb->get_col('SELECT object_id FROM ' . $wpdb->term_relationships . ' WHERE ( term_taxonomy_id = ' . $term->term_taxonomy_id . ' )'));
        $count = $wpdb->get_var('SELECT COUNT(*) FROM ' . $wpdb->posts . ' AS p WHERE ( p.ID IN ( ' . $posts . ' )' . $mime_where . ')');
        $posts = implode(',', $wpdb->get_col('SELECT p.ID FROM ' . $wpdb->posts . ' as p WHERE ( p.ID IN ( ' . $posts . ' )' . $mime_where . ') LIMIT ' . $offset . ', ' . $posts_per_page));
    }
    $href = empty($page) ? '{+link_url+}' : "{+site_url+}{$page}";
    /* translators: 1: term name, 2: taxonomy label */
    $output = '<h3>' . sprintf(__('Gallery for term "%1$s" in taxonomy "%2$s"', 'mla-child-theme'), $term->name, $taxonomy->labels->name) . '</h3>';
    $output .= '<p>' . do_shortcode(sprintf('[mla_gallery ids="%1$s" post_mime_type="%2$s" mla_paginate_current=1 mla_nolink_text="No items found" update_post_term_cache="false" mla_link_href="%3$s?post_id={+attachment_ID+}"]', $posts, $post_mime_type, $href) . "</p>\r\n");
    echo $output;
    return $count;
}
Esempio n. 7
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;
 }
 /**
  * Count of items in media library
  *
  * @access public
  * @param $counts_in
  * @return int
  */
 public static function recount_attachments($counts_in)
 {
     global $wpdb;
     global $current_user;
     $and = wp_post_mime_type_where('');
     $count = $wpdb->get_results("SELECT post_mime_type, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' AND post_author = {$current_user->ID} {$and} GROUP BY post_mime_type", ARRAY_A);
     $counts = array();
     foreach ((array) $count as $row) {
         $counts[$row['post_mime_type']] = $row['num_posts'];
     }
     $counts['trash'] = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_author = {$current_user->ID} AND post_status = 'trash' {$and}");
     return $counts;
 }
Esempio n. 9
0
 /**
  * Rebuild the image
  * 
  * @access public
  * @return void
  * @author Nicolas Juen
  */
 public function ajaxThumbnailRebuildAjax()
 {
     global $wpdb;
     // Get the nonce
     $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : '';
     // Time a the begining
     $start_time = microtime(true);
     // Get the action
     $action = $_POST["do"];
     // Get the thumbnails
     $thumbnails = isset($_POST['thumbnails']) ? $_POST['thumbnails'] : NULL;
     if ($action == "getlist") {
         // Check the nonce
         if (!wp_verify_nonce($nonce, 'getList')) {
             echo json_encode(array());
             die;
         }
         if (isset($_POST['post_types']) && !empty($_POST['post_types'])) {
             // Get image medias
             $whichmimetype = wp_post_mime_type_where('image', $wpdb->posts);
             // Get all parent from post type
             $attachments = $wpdb->get_results("SELECT *\r\n\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\tWHERE 1 = 1\r\n\t\t\t\t\tAND post_type = 'attachment'\r\n\t\t\t\t\t{$whichmimetype}\r\n\t\t\t\t\tAND post_parent IN (\r\n\t\t\t\t\t\tSELECT DISTINCT ID \r\n\t\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\t\tWHERE post_type IN ('" . implode("', '", $_POST['post_types']) . "')\r\n\t\t\t\t\t)");
         } else {
             $attachments =& get_children(array('post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null, 'output' => 'object'));
         }
         // Get the attachments
         foreach ($attachments as $attachment) {
             $res[] = array('id' => $attachment->ID, 'title' => $attachment->post_title);
         }
         // Return the Id's and Title of medias
         die(json_encode($res));
     } else {
         if ($action == "regen") {
             // Check the nonce
             if (!wp_verify_nonce($nonce, 'regen')) {
                 echo json_encode(array('error' => _e('Trying to cheat ?', 'sis')));
                 die;
             }
             // Get the id
             $id = $_POST["id"];
             // Check Id
             if ((int) $id == 0) {
                 die(json_encode(array('time' => round(microtime(true) - $start_time, 4), 'error' => __('No id given in POST datas.', 'sis'))));
             }
             // Get the path
             $fullsizepath = get_attached_file($id);
             // Regen the attachment
             if (FALSE !== $fullsizepath && @file_exists($fullsizepath)) {
                 set_time_limit(30);
                 if (wp_update_attachment_metadata($id, $this->wp_generate_attachment_metadata_custom($id, $fullsizepath, $thumbnails)) == false) {
                     die(json_encode(array('src' => wp_get_attachment_thumb_url($id), 'time' => round(microtime(true) - $start_time, 4), 'message' => sprintf(__('This file already exists in this size and have not been regenerated :<br/><a target="_blank" href="%1$s" >%2$s</a>', 'sis'), get_edit_post_link($id), get_the_title($id)))));
                 }
             } else {
                 die(json_encode(array('src' => wp_get_attachment_thumb_url($id), 'time' => round(microtime(true) - $start_time, 4), 'error' => sprintf(__('This file does not exists and have not been regenerated :<br/><a target="_blank" href="%1$s" >%2$s</a>', 'sis'), get_edit_post_link($id), get_the_title($id)))));
             }
             // Display the attachment url for feedback
             die(json_encode(array('time' => round(microtime(true) - $start_time, 4), 'src' => wp_get_attachment_thumb_url($id), 'title' => get_the_title($id))));
         }
     }
 }
 /**
  * Retrieve the terms in one or more taxonomies.
  *
  * Alternative to WordPress /wp-includes/taxonomy.php function get_terms() that provides
  * an accurate count of attachments associated with each term.
  *
  * taxonomy - string containing one or more (comma-delimited) taxonomy names
  * or an array of taxonomy names. Default 'post_tag'.
  *
  * post_mime_type - MIME type(s) of the items to include in the term-specific counts. Default 'all'.
  *
  * post_type - The post type(s) of the items to include in the term-specific counts.
  * The default is "attachment". 
  *
  * post_status - The post status value(s) of the items to include in the term-specific counts.
  * The default is "inherit".
  *
  * ids - A comma-separated list of attachment ID values for an item-specific cloud.
  *
  * include - An array, comma- or space-delimited string of term ids to include
  * in the return array.
  *
  * exclude - An array, comma- or space-delimited string of term ids to exclude
  * from the return array. If 'include' is non-empty, 'exclude' is ignored.
  *
  * parent - term_id of the terms' immediate parent; 0 for top-level terms.
  *
  * minimum - minimum number of attachments a term must have to be included. Default 0.
  *
  * no_count - 'true', 'false' (default) to suppress term-specific attachment-counting process.
  *
  * number - maximum number of term objects to return. Terms are ordered by count,
  * descending and then by term_id before this value is applied. Default 0.
  *
  * orderby - 'count', 'id', 'name' (default), 'none', 'random', 'slug'
  *
  * order - 'ASC' (default), 'DESC'
  *
  * no_orderby - 'true', 'false' (default) to suppress ALL sorting clauses else false.
  *
  * preserve_case - 'true', 'false' (default) to make orderby case-sensitive.
  *
  * pad_counts - 'true', 'false' (default) to to include the count of all children in their parents' count.
  *
  * limit - final number of term objects to return, for pagination. Default 0.
  *
  * offset - number of term objects to skip, for pagination. Default 0.
  *
  * @since 1.60
  *
  * @param	array	taxonomies to search and query parameters
  *
  * @return	array	array of term objects, empty if none found
  */
 public static function mla_get_terms($attr)
 {
     global $wpdb;
     /*
      * Make sure $attr is an array, even if it's empty
      */
     if (empty($attr)) {
         $attr = array();
     } elseif (is_string($attr)) {
         $attr = shortcode_parse_atts($attr);
     }
     /*
      * Merge input arguments with defaults
      */
     $attr = apply_filters('mla_get_terms_query_attributes', $attr);
     $arguments = shortcode_atts(self::$mla_get_terms_parameters, $attr);
     $arguments = apply_filters('mla_get_terms_query_arguments', $arguments);
     /*
      * Build an array of individual clauses that can be filtered
      */
     $clauses = array('fields' => '', 'join' => '', 'where' => '', 'order' => '', 'orderby' => '', 'limits' => '');
     /*
      * If we're not counting attachments per term, strip
      * post fields out of list and adjust the orderby  value
      */
     if ($no_count = 'true' == (string) $arguments['no_count']) {
         $field_array = explode(',', $arguments['fields']);
         foreach ($field_array as $index => $field) {
             if (false !== strpos($field, 'p.')) {
                 unset($field_array[$index]);
             }
         }
         $arguments['fields'] = implode(',', $field_array);
         $arguments['minimum'] = 0;
         $arguments['post_mime_type'] = 'all';
         if ('count' == strtolower($arguments['orderby'])) {
             $arguments['orderby'] = 'none';
         }
     }
     $clauses['fields'] = $arguments['fields'];
     $clause = array('INNER JOIN `' . $wpdb->term_taxonomy . '` AS tt ON t.term_id = tt.term_id');
     $clause_parameters = array();
     if (!$no_count) {
         $clause[] = 'LEFT JOIN `' . $wpdb->term_relationships . '` AS tr ON tt.term_taxonomy_id = tr.term_taxonomy_id';
         $clause[] = 'LEFT JOIN `' . $wpdb->posts . '` AS p ON tr.object_id = p.ID';
         /*
          * Add type and status constraints
          */
         if (is_array($arguments['post_type'])) {
             $post_types = $arguments['post_type'];
         } else {
             $post_types = array($arguments['post_type']);
         }
         $placeholders = array();
         foreach ($post_types as $post_type) {
             $placeholders[] = '%s';
             $clause_parameters[] = $post_type;
         }
         $clause[] = 'AND p.post_type IN (' . join(',', $placeholders) . ')';
         if (is_array($arguments['post_status'])) {
             $post_stati = $arguments['post_status'];
         } else {
             $post_stati = array($arguments['post_status']);
         }
         $placeholders = array();
         foreach ($post_stati as $post_status) {
             if ('private' != $post_status || is_user_logged_in()) {
                 $placeholders[] = '%s';
                 $clause_parameters[] = $post_status;
             }
         }
         $clause[] = 'AND p.post_status IN (' . join(',', $placeholders) . ')';
     }
     $clause = join(' ', $clause);
     $clauses['join'] = $wpdb->prepare($clause, $clause_parameters);
     /*
      * Start WHERE clause with a taxonomy constraint
      */
     if (is_array($arguments['taxonomy'])) {
         $taxonomies = $arguments['taxonomy'];
     } else {
         $taxonomies = array($arguments['taxonomy']);
     }
     foreach ($taxonomies as $taxonomy) {
         if (!taxonomy_exists($taxonomy)) {
             $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy', 'media-library-assistant'), $taxonomy);
             return $error;
         }
     }
     $clause_parameters = array();
     $placeholders = array();
     foreach ($taxonomies as $taxonomy) {
         $placeholders[] = '%s';
         $clause_parameters[] = $taxonomy;
     }
     $clause = array('tt.taxonomy IN (' . join(',', $placeholders) . ')');
     /*
      * The "ids" parameter can build an item-specific cloud.
      * Compile a list of all the terms assigned to the items.
      */
     if (!empty($arguments['ids']) && empty($arguments['include'])) {
         $ids = wp_parse_id_list($arguments['ids']);
         $placeholders = implode("','", $ids);
         $clause[] = "AND p.ID IN ( '{$placeholders}' )";
         $includes = array();
         foreach ($ids as $id) {
             foreach ($taxonomies as $taxonomy) {
                 $terms = get_the_terms($id, $taxonomy);
                 if (is_array($terms)) {
                     foreach ($terms as $term) {
                         $includes[$term->term_id] = $term->term_id;
                     }
                     // terms
                 }
             }
             // taxonomies
         }
         // ids
         /*
          * If there are no terms we want an empty cloud
          */
         if (empty($includes)) {
             $arguments['include'] = (string) 0x7fffffff;
         } else {
             ksort($includes);
             $arguments['include'] = implode(',', $includes);
         }
     }
     /*
      * Add include/exclude and parent constraints to WHERE cluse
      */
     if (!empty($arguments['include'])) {
         $placeholders = implode("','", wp_parse_id_list($arguments['include']));
         $clause[] = "AND t.term_id IN ( '{$placeholders}' )";
     } elseif (!empty($arguments['exclude'])) {
         $placeholders = implode("','", wp_parse_id_list($arguments['exclude']));
         $clause[] = "AND t.term_id NOT IN ( '{$placeholders}' )";
     }
     if ('' !== $arguments['parent']) {
         $parent = (int) $arguments['parent'];
         $clause[] = "AND tt.parent = '{$parent}'";
     }
     if ('all' !== strtolower($arguments['post_mime_type'])) {
         $where = str_replace('%', '%%', wp_post_mime_type_where($arguments['post_mime_type'], 'p'));
         if (0 == absint($arguments['minimum'])) {
             $clause[] = ' AND ( p.post_mime_type IS NULL OR ' . substr($where, 6);
         } else {
             $clause[] = $where;
         }
     }
     $clause = join(' ', $clause);
     $clauses['where'] = $wpdb->prepare($clause, $clause_parameters);
     /*
      * For the inner/initial query, always select the most popular terms
      */
     if ($arguments['no_orderby']) {
         $arguments['orderby'] = 'count';
         $arguments['order'] = 'DESC';
     }
     /*
      * Add sort order
      */
     $orderby = strtolower($arguments['orderby']);
     $order = strtoupper($arguments['order']);
     if ('DESC' != $order) {
         $order = 'ASC';
     }
     $clauses['order'] = $order;
     $clauses['orderby'] = "ORDER BY {$orderby}";
     /*
      * Count, Descending, is the default order so no further work
      * is needed unless a different order is specified
      */
     if ('count' != $orderby || 'DESC' != $order) {
         if ('true' == strtolower($arguments['preserve_case'])) {
             $binary_keys = array('name', 'slug');
         } else {
             $binary_keys = array();
         }
         $allowed_keys = array('empty_orderby_default' => 'name', 'count' => 'count', 'id' => 'term_id', 'name' => 'name', 'random' => 'RAND()', 'slug' => 'slug');
         $clause = 'ORDER BY ' . self::_validate_sql_orderby($arguments, '', $allowed_keys, $binary_keys);
         $clauses['orderby'] = substr($clause, 0, strrpos($clause, ' ' . $order));
     }
     // add ORDER BY
     /*
      * Add pagination
      */
     $clauses['limits'] = '';
     $offset = absint($arguments['offset']);
     $limit = absint($arguments['limit']);
     if (0 < $offset && 0 < $limit) {
         $clauses['limits'] = "LIMIT {$offset}, {$limit}";
     } elseif (0 < $limit) {
         $clauses['limits'] = "LIMIT {$limit}";
     } elseif (0 < $offset) {
         $clause_parameters = 0x7fffffff;
         $clauses['limits'] = "LIMIT {$offset}, {$clause_parameters}";
     }
     $clauses = apply_filters('mla_get_terms_clauses', $clauses);
     /*
      * Build the final query
      */
     $query = array('SELECT');
     $query[] = $clauses['fields'];
     $query[] = 'FROM `' . $wpdb->terms . '` AS t';
     $query[] = $clauses['join'];
     $query[] = 'WHERE (';
     $query[] = $clauses['where'];
     $query[] = ') GROUP BY tt.term_taxonomy_id';
     $clause_parameters = absint($arguments['minimum']);
     if (0 < $clause_parameters) {
         $query[] = "HAVING count >= {$clause_parameters}";
     }
     /*
      * If specifically told to omit the ORDER BY clause or the COUNT,
      * supply a sort order for the initial/inner query only
      */
     if (!($arguments['no_orderby'] || $no_count)) {
         $query[] = 'ORDER BY count DESC, t.term_id ASC';
     }
     /*
      * Limit the total number of terms returned
      */
     $terms_limit = absint($arguments['number']);
     if (0 < $terms_limit) {
         $query[] = "LIMIT {$terms_limit}";
     }
     /*
      * $final_clauses, if present, require an SQL subquery
      */
     $final_clauses = array();
     if ('count' != $orderby || 'DESC' != $order) {
         $final_clauses[] = $clauses['orderby'];
         $final_clauses[] = $clauses['order'];
     }
     if ('' !== $clauses['limits']) {
         $final_clauses[] = $clauses['limits'];
     }
     /*
      * If we're limiting the final results, we need to get an accurate total count first
      */
     if (!$no_count && (0 < $offset || 0 < $limit)) {
         $count_query = 'SELECT COUNT(*) as count FROM (' . join(' ', $query) . ' ) as subQuery';
         $count = $wpdb->get_results($count_query);
         $found_rows = $count[0]->count;
     }
     if (!empty($final_clauses)) {
         if (!$no_count) {
             array_unshift($query, 'SELECT * FROM (');
             $query[] = ') AS subQuery';
         }
         $query = array_merge($query, $final_clauses);
     }
     $query = join(' ', $query);
     $tags = $wpdb->get_results($query);
     if (!isset($found_rows)) {
         $found_rows = $wpdb->num_rows;
     }
     if (self::$mla_debug) {
         MLA::mla_debug_add('<strong>' . __('mla_debug query arguments', 'media-library-assistant') . '</strong> = ' . var_export($arguments, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug last_query', 'media-library-assistant') . '</strong> = ' . var_export($wpdb->last_query, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug last_error', 'media-library-assistant') . '</strong> = ' . var_export($wpdb->last_error, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug num_rows', 'media-library-assistant') . '</strong> = ' . var_export($wpdb->num_rows, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug found_rows', 'media-library-assistant') . '</strong> = ' . var_export($found_rows, true));
     }
     if ('true' == strtolower(trim($arguments['pad_counts']))) {
         self::_pad_term_counts($tags, reset($taxonomies), $post_types, $post_stati);
     }
     $tags['found_rows'] = $found_rows;
     $tags = apply_filters('mla_get_terms_query_results', $tags);
     return $tags;
 }
Esempio n. 11
0
/**
 * wp_count_attachments() - Count number of attachments
 *
 * {@internal Missing Long Description}}
 *
 * @package WordPress
 * @subpackage Post
 * @since 2.5
 *
 * @param string|array $post_mime_type Array or comma-separated list of MIME patterns
 * @return array Number of posts for each post_mime_type
 */

function wp_count_attachments( $mime_type = '' ) {
	global $wpdb;

	$and = wp_post_mime_type_where( $mime_type );
	$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' $and GROUP BY post_mime_type", ARRAY_A );

	$stats = array( );
	foreach( (array) $count as $row ) {
		$stats[$row['post_mime_type']] = $row['num_posts'];
	}

	return (object) $stats;
}
Esempio n. 12
0
 /**
  * Regenerate the thumbnails ajax action
  *
  * @return array
  * @param void
  * @author Nicolas Juen
  */
 public static function a_thumbnails_rebuild()
 {
     // Get the nonce
     $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : '';
     $offset = isset($_POST['offset']) ? absint($_POST['offset']) : 0;
     $post_types = isset($_POST['post_types']) ? $_POST['post_types'] : 'any';
     $thumbnails = isset($_POST['thumbnails']) ? $_POST['thumbnails'] : NULL;
     // Check the nonce
     if (!wp_verify_nonce($nonce, 'regen')) {
         SIS_Admin_Main::displayJson(array('error' => __('Trying to cheat ?', 'simple-image-sizes')));
     }
     if ($post_types !== 'any') {
         foreach ($_POST['post_types'] as $key => $type) {
             if (!post_type_exists($type)) {
                 unset($_POST['post_types'][$key]);
             }
         }
         if (empty($_POST['post_types'])) {
             SIS_Admin_Main::displayJson();
         }
         // Get image medias
         $whichmimetype = wp_post_mime_type_where('image', $wpdb->posts);
         // Get all parent from post type
         $attachment = $wpdb->get_var($wpdb->prepare("SELECT ID\r\n\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\tWHERE 1 = 1\r\n\t\t\t\tAND post_type = 'attachment'\r\n\t\t\t\t{$whichmimetype}\r\n\t\t\t\tAND post_parent IN (\r\n\t\t\t\t\tSELECT DISTINCT ID \r\n\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\tWHERE post_type IN ('" . implode("', '", $_POST['post_types']) . "')\r\n\t\t\t\t)\r\n\t\t\t\tLIMIT %d,1 \r\n\t\t\t", $offset));
     } else {
         $attachment = get_posts(array('post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1, 'post_status' => 'any', 'output' => 'object', 'offset' => $offset));
         $attachment = !empty($attachment) ? $attachment[0]->ID : 0;
     }
     if (empty($attachment)) {
         return array('message' => __('Regeneration ended', 'simple-image-sizes'));
     }
     SIS_Admin_Main::displayJson(SIS_Admin_Main::thumbnail_rebuild($attachment, $thumbnails));
 }
 public function _media_view_settings($settings = array(), $post = null)
 {
     $media_filter = clearbase_get_value('media_filter', '', clearbase_get_folder_settings($cb_post_id));
     if (!empty($media_filter)) {
         $post_mime_types = get_post_mime_types();
         $matches = wp_match_mime_types($media_filter, array_keys($post_mime_types));
         $settings['mimeTypes'] = wp_list_pluck(array_intersect_key($post_mime_types, $matches), 0);
         global $wpdb, $wp_locale;
         $post_parent = absint($post->ID);
         $and_where_mime = wp_post_mime_type_where($media_filter);
         $months = $wpdb->get_results("\n              SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month\n              FROM {$wpdb->posts}\n              WHERE post_parent = {$post_parent} AND post_type = 'attachment' {$and_where_mime}\n              ORDER BY post_date DESC");
         foreach ($months as $month_year) {
             $month_year->text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($month_year->month), $month_year->year);
         }
         $settings['months'] = $months;
     }
     return $settings;
 }
Esempio n. 14
0
 /**
  * Remove as abas desnecessárias e filtra o contador da galeria
  * 
  * @uses $wpdb
  * @uses self::get_custom_uploader_allowed_types
  * @uses wp_post_mime_type_where() Cria o SQL para os mime types
  *
  * @param array $default_tabs As abas default
  * @see http://shibashake.com/wordpress-theme/how-to-hook-into-the-media-upload-popup-interface Hack para o media uploader
  */
 function custom_uploader_tabs($default_tabs)
 {
     global $wpdb;
     $post_id = intval($_REQUEST['post_id']);
     // Hack para o count apenas mostrar os tipos permitidos de arquivo
     $allowed_mime_types = $this->get_custom_uploader_allowed_types();
     $gallery_query = "SELECT count(*)\n            \tFROM {$wpdb->posts}\n            \tWHERE post_type = 'attachment'\n            \tAND post_status != 'trash'\n            \tAND post_parent = %d";
     $gallery_query .= wp_post_mime_type_where($allowed_mime_types);
     if ($post_id) {
         $attachments = intval($wpdb->get_var($wpdb->prepare($gallery_query, $post_id)));
     }
     if (!empty($attachments)) {
         $default_tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>{$attachments}</span>");
     }
     // Remove as tabs desnecessárias (opções: 'type', 'type_url', 'gallery', 'library')
     unset($default_tabs['type_url']);
     return $default_tabs;
 }
Esempio n. 15
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;

		$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 ( '' !== $q['menu_order'] )
			$where .= " AND $wpdb->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($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);
		}

		// 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 || 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_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 $wpdb->posts.post_name = '" . $q['attachment'] . "'";
		}


		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'] );
		} elseif ( $q['post_parent__in'] ) {
			$post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
			$where .= " AND {$wpdb->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 {$wpdb->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 {$wpdb->posts}.ID = " . $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 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( $wpdb->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 = 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];

				$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 );

					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 );
			}
		}

		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 = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
			$where .= " AND {$wpdb->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 {$wpdb->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 ($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 = '';
		} elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
			$orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
		} elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
			$orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
		} 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':
						$orderby = "$wpdb->posts.menu_order";
						break;
					case 'ID':
						$orderby = "$wpdb->posts.ID";
						break;
					case 'rand':
						$orderby = 'RAND()';
						break;
					case $q['meta_key']:
					case 'meta_value':
						if ( isset( $q['meta_type'] ) ) {
							$meta_type = $this->meta_query->get_cast_for_type( $q['meta_type'] );
							$orderby = "CAST($wpdb->postmeta.meta_value AS {$meta_type})";
						} else {
							$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']}";
		}

		// 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 );

			/**
			 * Filter 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 ( '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 $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' );
		}

		$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) ) {
				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 );
			$this->post_count = count( $this->posts );
			$this->set_found_posts( $q, $limits );

			return $this->posts;
		}

		if ( 'id=>parent' == $q['fields'] ) {
			$this->posts = $wpdb->get_results( $this->request );
			$this->post_count = count( $this->posts );
			$this->set_found_posts( $q, $limits );

			$r = array();
			foreach ( $this->posts as $post )
				$r[ $post->ID ] = $post->post_parent;

			return $r;
		}

		$split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
		$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 $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->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 = $wpdb->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 );

		// 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]);
			$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( '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 ( !$q['suppress_filters'] )
			$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();
		}

		return $this->posts;
	}
Esempio n. 16
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;
 }
Esempio n. 17
0
/**
 * Count number of attachments for the mime type(s).
 *
 * If you set the optional mime_type parameter, then an array will still be
 * returned, but will only have the item you are looking for. It does not give
 * you the number of attachments that are children of a post. You can get that
 * by counting the number of children that post has.
 *
 * @since 2.5.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string|array $mime_type Optional. Array or comma-separated list of
 *                                MIME patterns. Default empty.
 * @return object An object containing the attachment counts by mime type.
 */
function wp_count_attachments($mime_type = '')
{
    global $wpdb;
    $and = wp_post_mime_type_where($mime_type);
    $count = $wpdb->get_results("SELECT post_mime_type, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' {$and} GROUP BY post_mime_type", ARRAY_A);
    $counts = array();
    foreach ((array) $count as $row) {
        $counts[$row['post_mime_type']] = $row['num_posts'];
    }
    $counts['trash'] = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status = 'trash' {$and}");
    /**
     * Modify returned attachment counts by mime type.
     *
     * @since 3.7.0
     *
     * @param object $counts    An object containing the attachment counts by
     *                          mime type.
     * @param string $mime_type The mime type pattern used to filter the attachments
     *                          counted.
     */
    return apply_filters('wp_count_attachments', (object) $counts, $mime_type);
}
Esempio n. 18
0
/**
 * Main shortcode function
 *
 * @since 0.1
 */
function file_gallery_shortcode($content = false, $attr = false)
{
    global $file_gallery, $wpdb, $post;
    // if the function is called directly, not via shortcode
    if (false !== $content && false === $attr) {
        $attr = wp_parse_args($content);
    }
    if (!isset($file_gallery->gallery_id)) {
        $file_gallery->gallery_id = 1;
    } else {
        $file_gallery->gallery_id++;
    }
    $options = get_option('file_gallery');
    if (isset($options['cache']) && true == $options['cache']) {
        if ('html' == $attr['output_type'] || isset($options['cache_non_html_output']) && true == $options['cache_non_html_output']) {
            $transient = 'filegallery_' . md5($post->ID . "_" . serialize($attr));
            $cache = get_transient($transient);
            if ($cache) {
                return $cache;
            }
        }
    }
    // if option to show galleries in excerpts is set to false...
    // ...replace [gallery] with user selected text
    if (!is_singular() && (!isset($options['in_excerpt']) || true != $options['in_excerpt'])) {
        return $options['in_excerpt_replace_content'];
    }
    $default_templates = unserialize(FILE_GALLERY_DEFAULT_TEMPLATES);
    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if (isset($attr['orderby'])) {
        $attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
        if (!$attr['orderby']) {
            unset($attr['orderby']);
        }
    }
    $defaults = array('order' => 'ASC', 'orderby' => '', 'id' => $post->ID, 'columns' => 3, 'size' => 'thumbnail', 'link' => 'attachment', 'include' => '', 'ids' => '', 'exclude' => '', 'template' => 'default', 'linkclass' => '', 'imageclass' => '', 'galleryclass' => '', 'rel' => 1, 'tags' => '', 'tags_from' => 'current', 'output_type' => 'html', 'output_params' => 1, 'attachment_ids' => '', 'mimetype' => '', 'limit' => -1, 'offset' => -1, 'paginate' => 0, 'link_size' => 'full', 'include_meta' => false);
    if (floatval(get_bloginfo('version')) >= 3.5) {
        $defaults['link'] = 'post';
    }
    // extract the defaults...
    extract(shortcode_atts($defaults, $attr));
    if (!in_array($template, $default_templates)) {
        $template_file = FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php';
        if (!is_readable($template_file)) {
            $template_file = FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php';
        }
    } else {
        if ('default' == $template) {
            $template_file = FILE_GALLERY_DEFAULT_TEMPLATE_ABSPATH . '/gallery.php';
            $template = FILE_GALLERY_DEFAULT_TEMPLATE_NAME;
        } else {
            $template_file = FILE_GALLERY_ABSPATH . '/templates/' . $template . '/gallery.php';
        }
    }
    // check if template exists and replace with default if it does not
    if (!is_readable($template_file)) {
        $template_file = FILE_GALLERY_ABSPATH . '/templates/default/gallery.php';
        $template = 'default';
    }
    // get overriding variables from the template file
    $overriding = true;
    ob_start();
    include $template_file;
    ob_end_clean();
    $overriding = false;
    if (is_array($file_gallery->overrides) && !empty($file_gallery->overrides)) {
        extract($file_gallery->overrides);
        $file_gallery->overrides = NULL;
    }
    $limit = (int) $limit;
    $offset = (int) $offset;
    $page = (int) get_query_var('page');
    if ('false' === $rel || is_numeric($rel) && 0 === (int) $rel) {
        $_rel = false;
    } elseif (1 === $rel) {
        $_rel = true;
    } else {
        $_rel = $rel;
    }
    if ('false' === $output_params || is_numeric($output_params) && 0 === (int) $output_params) {
        $output_params = false;
    } else {
        $output_params = true;
    }
    if ('false' === $paginate || is_numeric($paginate) && 0 === (int) $paginate || 0 > $limit) {
        $paginate = false;
        $found_rows = '';
    } else {
        $paginate = true;
        $found_rows = 'SQL_CALC_FOUND_ROWS';
        if (0 === $page) {
            $page = 1;
        }
        if (is_singular() && 1 < $page) {
            $offset = $limit * ($page - 1);
        }
    }
    $file_gallery->debug_add('pagination', compact('paginate', 'page'));
    /**/
    $_attachment_ids = explode(',', trim($attachment_ids, ','));
    $_include = explode(',', trim($include, ','));
    $_ids = explode(',', trim($ids, ','));
    $attachment_ids = array_merge($_attachment_ids, $_include, $_ids);
    $attachment_ids = array_unique($attachment_ids);
    $attachment_ids = implode(',', $attachment_ids);
    $attachment_ids = trim($attachment_ids, ',');
    $attachment_ids = trim($attachment_ids);
    /**/
    if (!isset($linkto)) {
        $linkto = $link;
    }
    $sql_mimetype = '';
    if ('' != $mimetype) {
        $mimetype = file_gallery_get_mime_type($mimetype);
        $sql_mimetype = wp_post_mime_type_where($mimetype);
    }
    $approved_attachment_post_statuses = apply_filters('file_gallery_approved_attachment_post_statuses', array('inherit'));
    $ignored_attachment_post_statuses = apply_filters('file_gallery_ignored_attachment_post_statuses', array('trash', 'private', 'pending', 'future'));
    if (!empty($approved_attachment_post_statuses)) {
        $post_statuses = " AND (post_status IN ('" . implode("', '", $approved_attachment_post_statuses) . "') ) ";
    } elseif (!empty($ignored_attachment_post_statuses)) {
        $post_statuses = " AND (post_status NOT IN ('" . implode("', '", $ignored_attachment_post_statuses) . "') ) ";
    } else {
        $post_statuses = "";
    }
    $file_gallery_query = new stdClass();
    // start with tags because they negate everything else
    if ('' != $tags) {
        if ('' == $orderby || 'file_gallery' == $orderby) {
            $orderby = "menu_order ID";
        }
        $query = array('post_status' => implode(',', $approved_attachment_post_statuses), 'post_type' => 'attachment', 'order' => $order, 'orderby' => $orderby, 'posts_per_page' => $limit, 'post_mime_type' => $mimetype, FILE_GALLERY_MEDIA_TAG_NAME => $tags);
        if ('current' == $tags_from) {
            $query['post_parent'] = $id;
        }
        if (!empty($exclude)) {
            $query['post__not_in'] = explode(',', preg_replace('/[^0-9,]+/', '', $exclude));
        }
        if (0 < $offset) {
            $query['offset'] = $offset;
        }
        $file_gallery_query = new WP_Query($query);
        $attachments = $file_gallery_query->posts;
        unset($query);
    } elseif ('' != $attachment_ids) {
        $attachment_ids = explode(',', $attachment_ids);
        $sql_limit = count($attachment_ids);
        if ('rand' == $orderby) {
            shuffle($attachment_ids);
        }
        $attachment_ids = implode(',', $attachment_ids);
        if ('' == $orderby || 'rand' == $orderby || $orderby == 'post__in') {
            $orderby = sprintf("FIELD(ID, %s)", $attachment_ids);
            $order = '';
        } elseif ('title' == $orderby) {
            $orderby = "post_title";
        }
        $query = sprintf("SELECT " . $found_rows . " * FROM {$wpdb->posts} \n\t\t\t WHERE ID IN (%s) \n\t\t\t AND post_type = 'attachment' \n\t\t\t" . $post_statuses . " ", $attachment_ids);
        $query .= $sql_mimetype;
        $query .= sprintf(" ORDER BY %s %s ", $orderby, $order);
        if (true !== $paginate) {
            $limit = $sql_limit;
        }
    } else {
        if ('' == $orderby) {
            $orderby = "menu_order ID";
        }
        $query = array('post_parent' => $id, 'post_status' => implode(',', $approved_attachment_post_statuses), 'post_type' => 'attachment', 'order' => $order, 'orderby' => $orderby, 'posts_per_page' => $limit, 'post_mime_type' => $mimetype);
        if (!empty($exclude)) {
            $query['post__not_in'] = explode(',', preg_replace('/[^0-9,]+/', '', $exclude));
        }
        if (0 < $offset) {
            $query['offset'] = $offset;
        }
        $file_gallery_query = new WP_Query($query);
        $attachments = $file_gallery_query->posts;
        unset($query);
    }
    if (isset($query)) {
        if (0 < $limit) {
            $query .= " LIMIT " . $limit;
        }
        if (0 < $offset) {
            $query .= " OFFSET " . $offset;
        }
        $attachments = $wpdb->get_results($query);
        if ('' != $found_rows) {
            $file_gallery_query->found_posts = $wpdb->get_var("SELECT FOUND_ROWS()");
            $file_gallery_query->max_num_pages = ceil($file_gallery_query->found_posts / $limit);
        }
    }
    $file_gallery->debug_add('attachments_query', compact('file_gallery_query'));
    if (empty($attachments)) {
        return '<!-- "File Gallery" plugin says: - No attachments found for the following shortcode arguments: "' . json_encode($attr) . '" -->';
    }
    // feed
    if (is_feed()) {
        $output = "\n";
        foreach ($attachments as $attachment) {
            $output .= wp_get_attachment_link($attachment->ID, $size, true) . "\n";
        }
        return $output;
    }
    $i = 0;
    $unique_ids = array();
    $gallery_items = '';
    if ('object' == $output_type || 'array' == $output_type) {
        $gallery_items = array();
    }
    $autoqueueclasses = array();
    if (defined('FILE_GALLERY_LIGHTBOX_CLASSES')) {
        $autoqueueclasses = maybe_unserialize(FILE_GALLERY_LIGHTBOX_CLASSES);
    } else {
        $autoqueueclasses = explode(',', $options['auto_enqueued_scripts']);
    }
    $file_gallery_this_template_counter = 1;
    // create output
    foreach ($attachments as $attachment) {
        $param = array('image_class' => $imageclass, 'link_class' => $linkclass, 'rel' => $_rel, 'title' => '', 'caption' => '', 'description' => '', 'thumb_alt' => '');
        $attachment_file = get_attached_file($attachment->ID);
        $attachment_is_image = file_gallery_file_is_displayable_image($attachment_file);
        $startcol = '';
        $endcol = '';
        $x = '';
        if ($output_params) {
            $plcai = array_intersect($autoqueueclasses, explode(' ', trim($linkclass)));
            if (!empty($plcai)) {
                if ($attachment_is_image) {
                    if (true === $param['rel']) {
                        $param['rel'] = $plcai[0] . '[' . $file_gallery->gallery_id . ']';
                    } elseif (!is_bool($param['rel'])) {
                        if (false !== strpos($_rel, '$GID$')) {
                            $param['rel'] = str_replace('$GID$', $file_gallery->gallery_id, $_rel);
                        } else {
                            $param['rel'] = $_rel . '[' . $file_gallery->gallery_id . ']';
                        }
                    }
                    $filter_args = array('gallery_id' => $file_gallery->gallery_id, 'linkrel' => $param['rel'], 'linkclass' => $param['link_class'], 'imageclass' => $param['image_class']);
                    if ($param['rel']) {
                        $param['rel'] = apply_filters('file_gallery_lightbox_linkrel', $param['rel'], 'linkrel', $filter_args);
                    }
                    $param['link_class'] = apply_filters('file_gallery_lightbox_linkclass', $param['link_class'], 'linkclass', $filter_args);
                    $param['image_class'] = apply_filters('file_gallery_lightbox_imageclass', $param['image_class'], 'imageclass', $filter_args);
                } else {
                    $param['link_class'] = str_replace(trim(implode(' ', $plcai)), '', trim($linkclass));
                }
            }
            // if rel is still true or false
            if (is_bool($param['rel'])) {
                $param['rel'] = '';
            }
            switch ($linkto) {
                case 'parent_post':
                    $param['link'] = get_permalink($wpdb->get_var("SELECT post_parent FROM {$wpdb->posts} WHERE ID = '" . $attachment->ID . "'"));
                    break;
                case 'file':
                    $param['link'] = wp_get_attachment_url($attachment->ID);
                    break;
                case 'attachment':
                case 'post':
                    $param['link'] = get_attachment_link($attachment->ID);
                    break;
                case 'none':
                    $param['link'] = '';
                    break;
                default:
                    // external url
                    $param['link'] = urldecode($linkto);
                    break;
            }
            $param['title'] = $attachment->post_title;
            $param['caption'] = $attachment->post_excerpt;
            $param['description'] = $attachment->post_content;
            if ($attachment_is_image) {
                $thumb_src = wp_get_attachment_image_src($attachment->ID, $size);
                $param['thumb_link'] = $thumb_src[0];
                $param['thumb_width'] = 0 == $thumb_src[1] ? file_gallery_get_image_size($param['thumb_link']) : $thumb_src[1];
                $param['thumb_height'] = 0 == $thumb_src[2] ? file_gallery_get_image_size($param['thumb_link'], true) : $thumb_src[2];
                if ('' != $param['link'] && 'full' != $link_size && in_array($link_size, file_gallery_get_intermediate_image_sizes())) {
                    $full_src = wp_get_attachment_image_src($attachment->ID, $link_size);
                    $param['link'] = $full_src[0];
                }
            } else {
                $param['thumb_link'] = wp_mime_type_icon($attachment->ID);
                $param['thumb_link'] = apply_filters('file_gallery_non_image_thumb_link', $param['thumb_link'], $attachment->post_mime_type, $attachment->ID);
                $param['thumb_width'] = '46';
                $param['thumb_height'] = '60';
            }
            if ($thumb_alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true)) {
                $param['thumb_alt'] = $thumb_alt;
            }
            $param['attachment_id'] = $attachment->ID;
        }
        $param = array_map('trim', $param);
        if ($include_meta) {
            $meta = get_post_custom($attachment->ID);
        }
        if ('object' == $output_type) {
            if ($output_params) {
                $attachment->params = (object) $param;
            }
            if ($include_meta) {
                $attachment->meta = (object) $meta;
            }
            $gallery_items[] = $attachment;
        } elseif ('array' == $output_type || 'json' == $output_type) {
            if ($output_params) {
                $attachment->params = $param;
            }
            if ($include_meta) {
                $attachment->meta = $meta;
            }
            $gallery_items[] = get_object_vars($attachment);
        } else {
            if ($columns > 0) {
                if (0 === $i || 0 === $i % $columns) {
                    $startcol = ' gallery-startcol';
                } elseif (($i + 1) % $columns == 0) {
                    // add the column break class
                    $endcol = ' gallery-endcol';
                }
            }
            // parse template
            ob_start();
            extract($param);
            include $template_file;
            $x = ob_get_contents();
            ob_end_clean();
            $file_gallery_this_template_counter++;
            if ($columns > 0 && $i + 1 % $columns == 0) {
                $x .= $cleartag;
            }
            $gallery_items .= $x;
            $i++;
        }
    }
    // handle data types
    if ('object' == $output_type || 'array' == $output_type) {
        $output = $gallery_items;
    } elseif ('json' == $output_type) {
        $output = json_encode($gallery_items);
    } else {
        $stc = '';
        $cols = '';
        $pagination_html = '';
        if (0 < (int) $columns) {
            $cols = ' columns_' . $columns;
        }
        if (isset($starttag_class) && '' != $starttag_class) {
            $stc = ' ' . $starttag_class;
        }
        $trans_append = "\n<!-- file gallery output cached on " . date('Y.m.d @ H:i:s', time()) . "-->\n";
        if (is_singular() && isset($file_gallery_query->max_num_pages) && 1 < $file_gallery_query->max_num_pages) {
            $pagination_html = file_gallery_do_pagination($file_gallery_query->max_num_pages, $page);
        }
        $gallery_class = apply_filters('file_gallery_galleryclass', 'gallery ' . str_replace(' ', '-', $template) . $cols . $stc . ' ' . $galleryclass);
        $output = '<' . $starttag . ' id="gallery-' . $file_gallery->gallery_id . '" class="' . $gallery_class . '">' . "\n" . $gallery_items . "\n" . $pagination_html . "\n</" . $starttag . '>';
    }
    if (isset($options['cache']) && true == $options['cache']) {
        if ('html' == $output_type) {
            set_transient($transient, $output . $trans_append, $options['cache_time']);
        } elseif (isset($options['cache_non_html_output']) && true == $options['cache_non_html_output']) {
            set_transient($transient, $output, $options['cache_time']);
        }
    }
    return apply_filters('file_gallery_output', $output, $post->ID, $file_gallery->gallery_id);
}
Esempio n. 19
0
/**
 * Count number of attachments for the mime type(s).
 *
 * If you set the optional mime_type parameter, then an array will still be
 * returned, but will only have the item you are looking for. It does not give
 * you the number of attachments that are children of a post. You can get that
 * by counting the number of children that post has.
 *
 * @since 2.5.0
 *
 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
 * @return array Number of posts for each mime type.
 */
function wp_count_attachments($mime_type = '')
{
    global $wpdb;
    $and = wp_post_mime_type_where($mime_type);
    $count = $wpdb->get_results("SELECT post_mime_type, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' {$and} GROUP BY post_mime_type", ARRAY_A);
    $stats = array();
    foreach ((array) $count as $row) {
        $stats[$row['post_mime_type']] = $row['num_posts'];
    }
    $stats['trash'] = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status = 'trash' {$and}");
    return (object) $stats;
}
Esempio n. 20
0
 /**
  * Filter out hidden attachments from the UI where we count attachments.
  *
  * @param stdClass $counts
  * @param string   $mime_type
  *
  * @return stdClass
  */
 public function hide_imports_from_count($counts, $mime_type)
 {
     // If we're not hiding imports, bail.
     if ('yes' !== get_option('seoslides_hideimports', 'yes')) {
         return $counts;
     }
     // We're hiding posts, so let's figure out how many attachments we really have in each status
     // The following logic is drawn directly from wp_count_attachments() in WordPress core.
     global $wpdb;
     // Get the term ID for the 'imported' taxonomy term
     $imported = get_term_by('name', 'imported', 'seoslides-flag');
     if (false === $imported) {
         return $counts;
     }
     $imported = $imported->term_taxonomy_id;
     $and = wp_post_mime_type_where($mime_type);
     $hide_and = $wpdb->prepare("AND ( {$wpdb->posts}.ID NOT IN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN (%d) ) )", $imported);
     $count = $wpdb->get_results("SELECT post_mime_type, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' {$hide_and} {$and} GROUP BY post_mime_type", ARRAY_A);
     $counts = array();
     foreach ((array) $count as $row) {
         $counts[$row['post_mime_type']] = $row['num_posts'];
     }
     $counts['trash'] = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status = 'trash' {$hide_and} {$and}");
     return $counts;
 }